// CartDrawer, SearchDrawer, AuthModal

const CartDrawer = () => {
  const { cart, cartOpen, setCartOpen, cartTotal, updateQty, removeItem, setRoute } = useApp();
  const shippingFree = cartTotal >= 2000;
  const shipping = shippingFree ? 0 : 120;
  const checkout = () => { setCartOpen(false); setRoute('checkout'); };
  return (
    <>
      <div className={cx('drawer-backdrop', cartOpen && 'open')} onClick={() => setCartOpen(false)}/>
      <aside className={cx('drawer', cartOpen && 'open')}>
        <div className="drawer-head">
          <h3>購物車 · {cart.length} 件</h3>
          <button onClick={() => setCartOpen(false)} aria-label="close"><IconClose/></button>
        </div>
        <div className="drawer-body">
          {cart.length === 0 ? (
            <div style={{ padding: '60px 0', textAlign: 'center' }}>
              <IconBag size={32} style={{ color: 'var(--mute-2)' }}/>
              <p style={{ marginTop: 12, fontSize: 13, color: 'var(--mute)' }}>購物車是空的</p>
              <button className="btn ghost sm" style={{ marginTop: 20 }}
                onClick={() => { setCartOpen(false); setRoute('shop'); }}>開始選購</button>
            </div>
          ) : (
            <>
              {!shippingFree && (
                <div style={{ padding: 14, background: 'var(--surface)', fontSize: 12, marginBottom: 16, textAlign: 'center' }}>
                  再購 <b>NT${(2000 - cartTotal).toLocaleString()}</b> 即享免運
                  <div style={{ height: 4, background: 'var(--line)', marginTop: 10, position: 'relative' }}>
                    <div style={{ position: 'absolute', inset: 0, width: `${Math.min(100, cartTotal / 2000 * 100)}%`, background: 'var(--accent)' }}/>
                  </div>
                </div>
              )}
              <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
                {cart.map(item => (
                  <div key={item.key} style={{ display: 'flex', gap: 12 }}>
                    <div className="ph" data-label={item.id} style={{ width: 84, height: 108, flexShrink: 0 }}/>
                    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 4 }}>
                      <div style={{ fontSize: 13, fontWeight: 500 }}>{item.name}</div>
                      <div style={{ fontSize: 11, color: 'var(--mute)', letterSpacing: '0.06em' }}>
                        {item.color} · Size {item.size}
                      </div>
                      <div style={{ marginTop: 'auto', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                        <div style={{ display: 'inline-flex', border: '1px solid var(--line-2)' }}>
                          <button style={{ width: 28, height: 28 }} onClick={() => updateQty(item.key, item.qty - 1)}><IconMinus size={12}/></button>
                          <div style={{ width: 28, height: 28, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12, fontFamily: 'var(--f-mono)' }}>{item.qty}</div>
                          <button style={{ width: 28, height: 28 }} onClick={() => updateQty(item.key, item.qty + 1)}><IconPlus size={12}/></button>
                        </div>
                        <div style={{ fontFamily: 'var(--f-mono)', fontSize: 13 }}>{fmtPrice(item.price * item.qty)}</div>
                      </div>
                    </div>
                    <button onClick={() => removeItem(item.key)} style={{ alignSelf: 'start', color: 'var(--mute)' }}><IconClose size={16}/></button>
                  </div>
                ))}
              </div>
            </>
          )}
        </div>
        {cart.length > 0 && (
          <div className="drawer-foot">
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, color: 'var(--mute)' }}>
              <span>運費</span><span>{shipping === 0 ? 'FREE' : fmtPrice(shipping)}</span>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 16, fontWeight: 600 }}>
              <span>小計</span><span style={{ fontFamily: 'var(--f-mono)' }}>{fmtPrice(cartTotal + shipping)}</span>
            </div>
            <button className="btn full" onClick={checkout}>前往結帳 <IconArrow size={14}/></button>
            <button className="btn ghost full sm" onClick={() => setCartOpen(false)}>繼續購物</button>
          </div>
        )}
      </aside>
    </>
  );
};

const SearchDrawer = () => {
  const { searchOpen, setSearchOpen, setRoute } = useApp();
  const [q, setQ] = React.useState('');
  const results = React.useMemo(() => {
    if (!q.trim()) return [];
    const s = q.toLowerCase();
    return PRODUCTS.filter(p => p.name.toLowerCase().includes(s) || (p.zh && p.zh.includes(q))).slice(0, 6);
  }, [q]);
  const popular = ['軌道星芒', 'Hoodie', 'Friday Drop', '聯名', 'Cargo'];
  if (!searchOpen) return null;
  return (
    <>
      <div className="drawer-backdrop open" onClick={() => setSearchOpen(false)}/>
      <div style={{ position: 'fixed', top: 0, left: 0, right: 0, background: '#fff', zIndex: 61, padding: '24px 0' }}>
        <div className="container-wide">
          <div style={{ display: 'flex', gap: 16, alignItems: 'center' }}>
            <IconSearch/>
            <input autoFocus value={q} onChange={e => setQ(e.target.value)}
              placeholder="Search products, collections..."
              style={{ flex: 1, height: 48, border: 0, outline: 'none', fontSize: 20, background: 'transparent' }}/>
            <button onClick={() => setSearchOpen(false)}><IconClose/></button>
          </div>
          <div style={{ borderTop: '1px solid var(--line)', marginTop: 16, paddingTop: 20 }}>
            {!q && (
              <div>
                <div className="eyebrow" style={{ marginBottom: 10 }}>熱門搜尋</div>
                <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                  {popular.map(p => <button key={p} className="tag-pill" onClick={() => setQ(p)}>{p}</button>)}
                </div>
              </div>
            )}
            {q && results.length > 0 && (
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(160px, 1fr))', gap: 16 }}>
                {results.map(p => (
                  <div key={p.id} className="product-card" onClick={() => { setRoute('product', { id: p.id }); setSearchOpen(false); }}>
                    <div className="img-wrap"><div className="ph" data-label={p.id}/></div>
                    <div className="meta">
                      <div className="title">{p.name}</div>
                      <div className="price">{fmtPrice(p.price)}</div>
                    </div>
                  </div>
                ))}
              </div>
            )}
            {q && results.length === 0 && (
              <div style={{ padding: 40, textAlign: 'center', color: 'var(--mute)', fontSize: 13 }}>
                查無商品「{q}」
              </div>
            )}
          </div>
        </div>
      </div>
    </>
  );
};

const AuthModal = () => {
  const { authOpen, setAuthOpen, authMode, setAuthMode, login } = useApp();
  const [email, setEmail] = React.useState('');
  const [pw, setPw] = React.useState('');
  const [name, setName] = React.useState('');
  const submit = (e) => { e.preventDefault(); if (email) login(email); };
  if (!authOpen) return null;
  return (
    <div className="modal-backdrop open" onClick={() => setAuthOpen(false)}>
      <div className="modal" onClick={e => e.stopPropagation()} style={{ padding: 40 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 32 }}>
          <FridayLogo size={22} color="#0a0a0a"/>
          <button onClick={() => setAuthOpen(false)}><IconClose/></button>
        </div>
        <h2 className="display" style={{ fontSize: 32, marginBottom: 8 }}>
          {authMode === 'login' ? 'Welcome back' : 'Join Friday'}
        </h2>
        <p style={{ fontSize: 13, color: 'var(--mute)', marginBottom: 28 }}>
          {authMode === 'login' ? '登入以查看訂單與會員福利' : '註冊享首購 95 折 + 生日禮'}
        </p>
        <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          {authMode === 'signup' && (
            <div className="field">
              <label>Name</label>
              <input className="input" value={name} onChange={e => setName(e.target.value)} placeholder="Your name"/>
            </div>
          )}
          <div className="field">
            <label>Email</label>
            <input className="input" type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="you@friday.com" required/>
          </div>
          <div className="field">
            <label>Password</label>
            <input className="input" type="password" value={pw} onChange={e => setPw(e.target.value)} placeholder="••••••••" required/>
          </div>
          {authMode === 'login' && (
            <div style={{ fontSize: 11, textAlign: 'right' }}>
              <a href="#" style={{ color: 'var(--mute)', textDecoration: 'underline' }}>忘記密碼？</a>
            </div>
          )}
          <button type="submit" className="btn full" style={{ marginTop: 8 }}>
            {authMode === 'login' ? 'Sign In' : 'Create Account'}
          </button>
        </form>
        <div style={{ textAlign: 'center', fontSize: 12, color: 'var(--mute)', marginTop: 20 }}>
          {authMode === 'login' ? (
            <>第一次來?  <a href="#" onClick={e => { e.preventDefault(); setAuthMode('signup'); }} style={{ color: 'var(--ink)', textDecoration: 'underline' }}>建立帳戶</a></>
          ) : (
            <>已有帳戶?  <a href="#" onClick={e => { e.preventDefault(); setAuthMode('login'); }} style={{ color: 'var(--ink)', textDecoration: 'underline' }}>登入</a></>
          )}
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { CartDrawer, SearchDrawer, AuthModal });
