/* global React, Icon */
const { useState, useEffect, useCallback } = React;

const BRIDGE_URL = 'https://ipbridge.indiegroup.id';

// ============================================================
// CART DRAWER
// ============================================================
function CartDrawer({ cart, onClose, onRemove, onUpdateQty, navigate }) {
  const subtotal = cart.reduce((s, item) => s + (item.qty * (item.paper.price?.A4 || item.paper.price_min || 0)), 0);

  return (
    <div className="cart-overlay" onClick={onClose}>
      <div className="cart-drawer" onClick={e => e.stopPropagation()}>
        <div className="cart-head">
          <h3>Cart <span className="mono" style={{fontSize:14, fontWeight:400}}>({cart.length} item)</span></h3>
          <button className="btn btn-ghost btn-sm" onClick={onClose}><Icon.X /></button>
        </div>

        {cart.length === 0 ? (
          <div className="cart-empty">
            <p>Cart kosong.</p>
            <button className="btn btn-primary" onClick={onClose}>Browse kertas →</button>
          </div>
        ) : (
          <>
            <div className="cart-items">
              {cart.map((item, i) => {
                const price = item.paper.price?.[item.format] || item.paper.price_min || 0;
                return (
                  <div key={i} className="cart-item">
                    <div className="ci-swatch" style={{background: item.paper.swatchTone || '#F4EFE3'}} />
                    <div className="ci-info">
                      <div className="ci-name">{item.paper.name}</div>
                      <div className="ci-meta">{item.format} · {item.paper.gsm}gsm</div>
                      <div className="ci-price">Rp {price.toLocaleString('id-ID')} / lembar</div>
                    </div>
                    <div className="ci-right">
                      <div className="ci-qty">
                        <button onClick={() => onUpdateQty(i, Math.max(item.paper.moq || 10, item.qty - 10))}>−</button>
                        <span>{item.qty}</span>
                        <button onClick={() => onUpdateQty(i, item.qty + 10)}>+</button>
                      </div>
                      <div className="ci-subtotal">Rp {(price * item.qty).toLocaleString('id-ID')}</div>
                      <button className="ci-remove" onClick={() => onRemove(i)} title="Hapus"><Icon.X /></button>
                    </div>
                  </div>
                );
              })}
            </div>
            <div className="cart-foot">
              <div className="cart-subtotal">
                <span>Subtotal</span>
                <span className="mono">Rp {subtotal.toLocaleString('id-ID')}</span>
              </div>
              <p style={{fontSize:12, color:'var(--ink-meta)', margin:'8px 0 16px'}}>
                Ongkir: Rp 20.000 Jabodetabek · Rp 50.000 luar Jabodetabek
              </p>
              <button className="btn btn-primary btn-lg btn-block" onClick={() => { onClose(); navigate('/checkout'); }}>
                Checkout →
              </button>
            </div>
          </>
        )}
      </div>
    </div>
  );
}

// ============================================================
// CHECKOUT PAGE
// ============================================================
function CheckoutPage({ cart, navigate, onOrderSuccess, authProfile }) {
  const [form, setForm] = useState({
    name: authProfile?.full_name || '',
    email: authProfile?.email || '',
    phone: authProfile?.phone || authProfile?.phone_normalized || '',
    studio: '',
    street: '', city: '', province: '', postal_code: '', notes: ''
  });
  const [addresses, setAddresses] = useState([]);
  const [selectedAddrId, setSelectedAddrId] = useState(null);
  const [saveAddr, setSaveAddr] = useState(false);

  // Load saved addresses kalau user login
  React.useEffect(() => {
    if (authProfile && window.IndieAuth) {
      window.IndieAuth.loadAddresses().then(addrs => {
        setAddresses(addrs);
        // Auto-fill alamat default kalau ada
        const def = addrs.find(a => a.is_default) || addrs[0];
        if (def) {
          setSelectedAddrId(def.id);
          setForm(f => ({
            ...f,
            street:      def.street || '',
            city:        def.city || '',
            province:    def.province || '',
            postal_code: def.postal_code || '',
          }));
        }
      });
    }
  }, [authProfile]);

  // Update form kalau authProfile berubah (user baru login)
  React.useEffect(() => {
    if (authProfile) {
      setForm(f => ({
        ...f,
        name:  f.name  || authProfile.full_name || '',
        email: f.email || authProfile.email     || '',
        phone: f.phone || authProfile.phone || authProfile.phone_normalized || '',
      }));
    }
  }, [authProfile]);

  const applyAddress = (addr) => {
    setSelectedAddrId(addr.id);
    setForm(f => ({
      ...f,
      street:      addr.street || '',
      city:        addr.city || '',
      province:    addr.province || '',
      postal_code: addr.postal_code || '',
    }));
  };
  const [loading, setLoading] = useState(false);
  const [redirecting, setRedirecting] = useState(false);
  const [error, setError] = useState(null);

  const subtotal = cart.reduce((s, item) => {
    const price = item.paper.price?.[item.format] || item.paper.price?.A4 || item.paper.price_min || 0;
    return s + (price * item.qty);
  }, 0);

  const JABODETABEK = ['jakarta','bogor','depok','tangerang','bekasi','serpong','ciputat','pamulang','bintaro'];
  const isJabo = JABODETABEK.some(k => form.city.toLowerCase().includes(k));
  const shippingCost = form.city ? (isJabo ? 20000 : 50000) : 0;
  const total = subtotal + shippingCost;

  const set = (k, v) => setForm(f => ({...f, [k]: v}));

  const handleSubmit = async () => {
    if (!form.name || !form.email || !form.phone || !form.street || !form.city) {
      setError('Mohon lengkapi semua field yang wajib diisi.');
      return;
    }
    setLoading(true);
    setError(null);
    try {
      const items = cart.map(item => {
        const price = item.paper.price?.[item.format] || item.paper.price_min || 0;
        return {
          acc_product_id: item.paper.acc_id,
          // selectedGsm = key dari price map (contoh: "176")
          // name_suffix di Acc App = gsm string (contoh: "176")
          acc_variant_id: item.paper.variants?.find(v => {
            const suffix = (v.name_suffix || '').trim();
            const varGsm = parseInt(suffix, 10);
            const selectedGsm = parseInt(item.format, 10); // item.format menyimpan gsm key
            return varGsm > 0 && varGsm === selectedGsm;
          })?.id || null,
          product_name:   item.paper.name,
          sku:            item.paper.sku || null,
          format:         item.format,
          gsm:            item.paper.gsm,
          qty:            item.qty,
          unit_price:     price,
        };
      });

      const res = await fetch(BRIDGE_URL + '/checkout', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          customer: { name: form.name, email: form.email, phone: form.phone, studio: form.studio || undefined },
          shipping: { street: form.street, city: form.city, province: form.province, postal_code: form.postal_code, notes: form.notes || undefined },
          items,
        }),
      });

      const data = await res.json();
      if (!data.ok) throw new Error(data.error || 'Checkout gagal');

      // Redirect ke Xendit payment page
      // Simpan alamat kalau user checklist
      if (saveAddr && authProfile && window.IndieAuth) {
        window.IndieAuth.saveAddress({
          street:      form.street,
          city:        form.city,
          province:    form.province,
          postal_code: form.postal_code,
          recipient_name: form.name,
          phone:       form.phone,
          is_default:  addresses.length === 0,
          label:       form.city || 'Alamat',
        }).catch(e => console.warn('[Checkout] saveAddress error:', e.message));
      }
      onOrderSuccess(data.order_number);
      setRedirecting(true);
      // Delay 1.5s supaya state ter-render dulu, baru redirect
      setTimeout(() => {
        window.location.href = data.payment_url;
      }, 1500);

    } catch (err) {
      setError(err.message);
      setLoading(false);
    }
  };

  if (redirecting) {
    return (
      <main className="fade-in">
        <div className="shell" style={{padding:'clamp(80px,15vw,160px) 0', textAlign:'center', maxWidth:480}}>
          <div style={{width:48, height:48, border:'3px solid var(--paper-card-edge)', borderTopColor:'var(--terracotta)', borderRadius:'50%', animation:'spin 800ms linear infinite', margin:'0 auto 24px'}} />
          <h2 style={{fontFamily:'var(--font-display)', fontWeight:300, fontSize:'clamp(28px,5vw,48px)', margin:'0 0 12px'}}>
            Menuju halaman pembayaran…
          </h2>
          <p style={{color:'var(--ink-meta)', fontSize:14}}>
            Mohon tunggu, jangan tutup halaman ini.
          </p>
        </div>
      </main>
    );
  }

  if (cart.length === 0 && !redirecting) {
    return (
      <main className="fade-in">
        <div className="shell" style={{padding:'80px 0', textAlign:'center'}}>
          <h2>Cart kosong</h2>
          <button className="btn btn-primary" onClick={() => navigate('/gallery')}>Browse kertas →</button>
        </div>
      </main>
    );
  }

  return (
    <main className="fade-in checkout-page">
      <div className="shell">
        <nav className="crumb" style={{paddingTop:24}}>
          <a onClick={() => navigate('/gallery')}>Gallery</a>
          <span className="sep">/</span>
          <span className="here">Checkout</span>
        </nav>

        <div className="checkout-grid">
          {/* LEFT — form */}
          <div className="checkout-form-col">
            <h2 style={{marginBottom:24}}>Shipping details</h2>

            <div className="field">
              <label>Nama lengkap *</label>
              <input type="text" value={form.name} onChange={e => set('name', e.target.value)} placeholder="Nama lengkap" />
            </div>
            <div className="field-row">
              <div className="field">
                <label>Email *</label>
                <input type="email" value={form.email} onChange={e => set('email', e.target.value)} placeholder="hello@studio.com" />
              </div>
              <div className="field">
                <label>WhatsApp *</label>
                <input type="text" value={form.phone} onChange={e => set('phone', e.target.value)} placeholder="+62 81..." />
              </div>
            </div>
            <div className="field">
              <label>Studio / Company (opsional)</label>
              <input type="text" value={form.studio} onChange={e => set('studio', e.target.value)} placeholder="Studio Tertier" />
            </div>

            <h3 style={{marginTop:32, marginBottom:16}}>Alamat pengiriman</h3>
            {addresses.length > 0 && (
              <div className="saved-addresses" style={{marginBottom:16}}>
                <div style={{fontSize:11, fontWeight:600, textTransform:'uppercase', letterSpacing:'0.1em', color:'var(--ink-meta)', marginBottom:8}}>Alamat tersimpan</div>
                <div style={{display:'flex', flexDirection:'column', gap:8}}>
                  {addresses.map(addr => (
                    <div
                      key={addr.id}
                      className={"saved-addr-item" + (selectedAddrId === addr.id ? " is-active" : "")}
                      onClick={() => applyAddress(addr)}
                    >
                      <div style={{fontWeight:500, fontSize:13}}>{addr.label || 'Alamat'}</div>
                      <div style={{fontSize:12, color:'var(--ink-meta)', marginTop:2}}>
                        {addr.street}, {addr.city} {addr.postal_code}
                      </div>
                    </div>
                  ))}
                  <div
                    className={"saved-addr-item" + (!selectedAddrId || !addresses.find(a=>a.id===selectedAddrId) ? " is-active" : "")}
                    onClick={() => { setSelectedAddrId(null); setForm(f=>({...f, street:'', city:'', province:'', postal_code:''})); }}
                  >
                    <div style={{fontWeight:500, fontSize:13}}>+ Alamat baru</div>
                  </div>
                </div>
              </div>
            )}

            <div className="field">
              <label>Alamat lengkap *</label>
              <textarea value={form.street} onChange={e => set('street', e.target.value)} placeholder="Jl. Senopati No. 12, RT 01/RW 02" />
            </div>
            <div className="field-row">
              <div className="field">
                <label>Kota *</label>
                <input type="text" value={form.city} onChange={e => set('city', e.target.value)} placeholder="Jakarta Selatan" />
              </div>
              <div className="field">
                <label>Provinsi</label>
                <input type="text" value={form.province} onChange={e => set('province', e.target.value)} placeholder="DKI Jakarta" />
              </div>
            </div>
            <div className="field-row">
              <div className="field">
                <label>Kode pos</label>
                <input type="text" value={form.postal_code} onChange={e => set('postal_code', e.target.value)} placeholder="12110" />
              </div>
              <div className="field">
                <label>Catatan (opsional)</label>
                <input type="text" value={form.notes} onChange={e => set('notes', e.target.value)} placeholder="Titip ke satpam" />
              </div>
            </div>

            {authProfile && (
              <div style={{display:'flex', alignItems:'center', gap:8, marginTop:8, marginBottom:4}}>
                <input type="checkbox" id="save-addr" checked={saveAddr} onChange={e => setSaveAddr(e.target.checked)} style={{width:14, height:14, cursor:'pointer'}} />
                <label htmlFor="save-addr" style={{fontSize:12, color:'var(--ink-soft)', cursor:'pointer'}}>Simpan alamat ini untuk order berikutnya</label>
              </div>
            )}
          {error && (
              <div style={{padding:'12px 16px', background:'#FEF2F2', border:'1px solid #FECACA', borderRadius:4, color:'#DC2626', fontSize:13, marginTop:16}}>
                {error}
              </div>
            )}
          </div>

          {/* RIGHT — order summary */}
          <div className="checkout-summary-col">
            <div className="checkout-summary">
              <h3>Order summary</h3>
              <div className="summary-items">
                {cart.map((item, i) => {
                  const price = item.paper.price?.[item.format] || item.paper.price_min || 0;
                  return (
                    <div key={i} className="summary-item">
                      <div className="si-swatch" style={{background: item.paper.swatchTone || '#F4EFE3'}} />
                      <div className="si-info">
                        <div className="si-name">{item.paper.name}</div>
                        <div className="si-meta">{item.format} · {item.qty} lembar</div>
                      </div>
                      <div className="si-price mono">Rp {(price * item.qty).toLocaleString('id-ID')}</div>
                    </div>
                  );
                })}
              </div>
              <div className="summary-line">
                <span>Subtotal</span>
                <span className="mono">Rp {subtotal.toLocaleString('id-ID')}</span>
              </div>
              <div className="summary-line">
                <span>Ongkir {form.city ? (isJabo ? '(Jabodetabek)' : '(Luar Jabodetabek)') : ''}</span>
                <span className="mono">{form.city ? 'Rp ' + shippingCost.toLocaleString('id-ID') : '—'}</span>
              </div>
              <div className="summary-total">
                <span>Total</span>
                <span className="mono">Rp {form.city ? total.toLocaleString('id-ID') : '...'}</span>
              </div>
              <button
                className="btn btn-primary btn-lg btn-block"
                onClick={handleSubmit}
                disabled={loading}
                style={{marginTop:20}}
              >
                {loading ? 'Membuat order...' : 'Bayar sekarang →'}
              </button>
              <p style={{fontSize:11, color:'var(--ink-meta)', textAlign:'center', marginTop:8, lineHeight:1.5}}>
                Kamu akan diarahkan ke halaman pembayaran Xendit.<br/>
                Semua metode pembayaran tersedia.
              </p>
            </div>
          </div>
        </div>
      </div>
    </main>
  );
}

// ============================================================
// ORDER SUCCESS PAGE
// ============================================================
function OrderSuccessPage({ navigate }) {
  const params = new URLSearchParams(window.location.hash.split('?')[1] || '');
  const orderNumber = params.get('order') || '';
  const [order, setOrder] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!orderNumber) { setLoading(false); return; }
    fetch(BRIDGE_URL + '/order/' + orderNumber)
      .then(r => r.json())
      .then(d => { setOrder(d.order); setLoading(false); })
      .catch(() => setLoading(false));
  }, [orderNumber]);

  return (
    <main className="fade-in">
      <div className="shell" style={{paddingBlock:'clamp(60px,10vw,120px)', maxWidth:600, textAlign:'center'}}>
        <div style={{
          display:'inline-block', border:'3px solid var(--terracotta)',
          color:'var(--terracotta)', padding:'8px 20px',
          fontFamily:'var(--font-mono)', fontSize:13, letterSpacing:'0.2em',
          fontWeight:700, transform:'rotate(-3deg)', marginBottom:32,
        }}>PEMBAYARAN · DITERIMA</div>

        <h1 style={{fontFamily:'var(--font-display)', fontSize:'clamp(40px,8vw,72px)', fontWeight:300, lineHeight:0.95, margin:'0 0 16px'}}>
          Terima<br/><em style={{color:'var(--terracotta)'}}>kasih.</em>
        </h1>

        {loading ? (
          <p style={{color:'var(--ink-meta)'}}>Memuat detail order…</p>
        ) : order ? (
          <>
            <p style={{fontSize:16, color:'var(--ink-soft)', margin:'16px 0 8px'}}>
              Order <strong style={{fontFamily:'var(--font-mono)'}}>{order.order_number}</strong> berhasil diterima.
            </p>
            <p style={{fontSize:14, color:'var(--ink-meta)'}}>
              Total: Rp {order.total?.toLocaleString('id-ID')} · Status: <strong>{order.status}</strong>
            </p>
            <p style={{fontSize:13, color:'var(--ink-meta)', marginTop:16}}>
              Tim INDIE Paper akan menghubungi via WhatsApp untuk konfirmasi pengiriman.
            </p>
          </>
        ) : (
          <p style={{color:'var(--ink-meta)'}}>Order #{orderNumber}</p>
        )}

        <div style={{display:'flex', gap:12, justifyContent:'center', marginTop:40, flexWrap:'wrap'}}>
          <button className="btn btn-primary btn-lg" onClick={() => navigate('/gallery')}>Kembali ke Gallery</button>
          <button className="btn btn-ghost btn-lg" onClick={() => navigate('/sample-request')}>Request sample kit</button>
        </div>
      </div>
    </main>
  );
}

// ============================================================
// ORDER FAILED PAGE
// ============================================================
function OrderFailedPage({ navigate }) {
  const params = new URLSearchParams(window.location.hash.split('?')[1] || '');
  const orderNumber = params.get('order') || '';

  return (
    <main className="fade-in">
      <div className="shell" style={{paddingBlock:'clamp(60px,10vw,120px)', maxWidth:560, textAlign:'center'}}>
        <h1 style={{fontFamily:'var(--font-display)', fontSize:'clamp(36px,7vw,64px)', fontWeight:300, margin:'0 0 16px'}}>
          Pembayaran<br/><em>dibatalkan.</em>
        </h1>
        <p style={{color:'var(--ink-meta)', marginBottom:32}}>
          Order {orderNumber ? <strong style={{fontFamily:'var(--font-mono)'}}>{orderNumber}</strong> : ''} belum dibayar.
          Tidak ada yang dicharge. Kamu bisa coba lagi kapan saja.
        </p>
        <div style={{display:'flex', gap:12, justifyContent:'center', flexWrap:'wrap'}}>
          <button className="btn btn-primary btn-lg" onClick={() => navigate('/gallery')}>Kembali ke Gallery</button>
        </div>
      </div>
    </main>
  );
}

window.CartDrawer    = CartDrawer;
window.CheckoutPage  = CheckoutPage;
window.OrderSuccessPage = OrderSuccessPage;
window.OrderFailedPage  = OrderFailedPage;
