// FRZN — shared UI (Nav, Drawer, Modal, Toast, Checkout, Tweaks, LangSwitcher)
const { useState: useStateUI, useEffect: useEffectUI, useRef: useRefUI } = React;

const LANGS = [
  { code: 'en', label: 'English' },
  { code: 'it', label: 'Italiano' },
  { code: 'fr', label: 'Français' },
  { code: 'de', label: 'Deutsch' },
  { code: 'es', label: 'Español' },
];

const LangSwitcher = ({ lang, onChange }) => {
  const [open, setOpen] = useStateUI(false);
  const ref = useRefUI(null);
  useEffectUI(() => {
    const h = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', h);
    return () => document.removeEventListener('mousedown', h);
  }, []);
  const cur = LANGS.find(l => l.code === lang);
  return (
    <div ref={ref} className={`lang-switcher ${open ? 'open' : ''}`}>
      <button className="lang-btn" onClick={() => setOpen(o => !o)}>
        <span>◎</span>{cur?.code.toUpperCase() || 'EN'} <span style={{ opacity: 0.5 }}>▾</span>
      </button>
      <div className="lang-menu">
        {LANGS.map(l => (
          <button key={l.code} className={lang === l.code ? 'active' : ''} onClick={() => { onChange(l.code); setOpen(false); }}>
            <span>{l.label}</span><span className="code">{l.code.toUpperCase()}</span>
          </button>
        ))}
      </div>
    </div>
  );
};

const Nav = ({ t, lang, onLang, cartCount, onOpenCart, liveTemp, current }) => {
  const [hidden, setHidden] = useStateUI(false);
  const [mobileOpen, setMobileOpen] = useStateUI(false);
  const lastY = useRefUI(0);
  useEffectUI(() => {
    const h = () => {
      const y = window.scrollY;
      setHidden(y > 200 && y > lastY.current);
      lastY.current = y;
    };
    window.addEventListener('scroll', h, { passive: true });
    return () => window.removeEventListener('scroll', h);
  }, []);
  useEffectUI(() => {
    document.body.classList.toggle('mobile-open', mobileOpen);
  }, [mobileOpen]);

  return (
    <>
      <div className="urgency" aria-hidden="true">
        <div className="urgency-track">
          {Array.from({ length: 3 }).map((_, i) => <span key={i}>{t.urgency}</span>)}
        </div>
      </div>
      <nav className={`nav ${hidden ? 'hidden' : ''}`}>
        <div className="nav-inner">
          <a className="nav-brand" href={current === 'shop' ? './index.html' : '#top'}>
            FRZN<sup>® COLD/SAUNA</sup>
          </a>
          <div className="nav-links">
            <a href={current === 'shop' ? './index.html#science' : '#science'}>{t.nav.science}</a>
            <a href={current === 'shop' ? './index.html#how' : '#how'}>{t.nav.mechanism}</a>
            <a href={current === 'shop' ? './index.html#products' : '#products'}>{t.nav.system}</a>
            <a href="./shop.html">{t.nav.shop}</a>
            <a href={current === 'shop' ? './index.html#faq' : '#faq'}>{t.nav.faq}</a>
          </div>
          <div className="nav-right">
            <div className="live-temp"><span className="live-dot" /><span>{t.liveLabel} · {liveTemp.toFixed(1)}°C · Helsinki</span></div>
            <LangSwitcher lang={lang} onChange={onLang} />
            <button className="cart-btn" onClick={onOpenCart}>{t.cart.title}<span className="count">{cartCount}</span></button>
            <button className="hamburger" onClick={() => setMobileOpen(o => !o)}><span /><span /><span /></button>
          </div>
        </div>
      </nav>
      <div className="mobile-menu">
        <a href={current === 'shop' ? './index.html#science' : '#science'} onClick={() => setMobileOpen(false)}>{t.nav.science}</a>
        <a href={current === 'shop' ? './index.html#how' : '#how'} onClick={() => setMobileOpen(false)}>{t.nav.mechanism}</a>
        <a href={current === 'shop' ? './index.html#products' : '#products'} onClick={() => setMobileOpen(false)}>{t.nav.system}</a>
        <a href="./shop.html" onClick={() => setMobileOpen(false)}>{t.nav.shop}</a>
        <a href={current === 'shop' ? './index.html#ritual' : '#ritual'} onClick={() => setMobileOpen(false)}>{t.nav.ritual}</a>
        <a href={current === 'shop' ? './index.html#faq' : '#faq'} onClick={() => setMobileOpen(false)}>{t.nav.faq}</a>
        <div className="lang-strip">
          {LANGS.map(l => (
            <button key={l.code} className={lang === l.code ? 'active' : ''} onClick={() => onLang(l.code)}>{l.code.toUpperCase()}</button>
          ))}
        </div>
      </div>
    </>
  );
};

const ThermalSwatch = () => (
  <div style={{ position: 'absolute', inset: 0, background: 'radial-gradient(circle at 40% 30%, #DC2626 0%, #1E3A8A 60%, #0A0D10 100%)', opacity: 0.6 }} />
);

const CartDrawer = ({ t, open, onClose, items, onQty, onRemove, onCheckout }) => {
  const total = items.reduce((s, it) => s + it.price * it.qty, 0);
  return (
    <>
      <div className={`drawer-backdrop ${open ? 'open' : ''}`} onClick={onClose} />
      <aside className={`drawer ${open ? 'open' : ''}`}>
        <div className="drawer-head">
          <h3>{t.cart.title} · {items.length} {items.length === 1 ? t.cart.item : t.cart.items}</h3>
          <button className="drawer-close" onClick={onClose}>✕</button>
        </div>
        {items.length === 0 ? (
          <div className="drawer-empty">
            <p>{t.cart.empty}</p>
            <button className="btn btn-primary" onClick={onClose}><span>{t.cart.browse}</span></button>
          </div>
        ) : (
          <>
            <div className="drawer-items">
              {items.map(it => (
                <div key={it.cartId} className="drawer-item">
                  <div className="drawer-item-img"><ThermalSwatch /></div>
                  <div className="drawer-item-info">
                    <span className="name">{it.name}</span>
                    <span className="meta">{it.id} · {it.size}</span>
                    <div className="qty">
                      <button onClick={() => onQty(it.cartId, it.qty - 1)}>−</button>
                      <span>{it.qty}</span>
                      <button onClick={() => onQty(it.cartId, it.qty + 1)}>+</button>
                    </div>
                  </div>
                  <div>
                    <div className="drawer-item-price">€{it.price * it.qty}</div>
                    <button className="drawer-item-remove" onClick={() => onRemove(it.cartId)}>{t.cart.remove}</button>
                  </div>
                </div>
              ))}
            </div>
            <div className="drawer-foot">
              <div className="drawer-shipping">{t.cart.shipping}</div>
              <div className="drawer-total"><span className="label">{t.cart.subtotal}</span><span>€{total}</span></div>
              <button className="btn btn-accent" style={{ width: '100%', justifyContent: 'center' }} onClick={onCheckout}><span>{t.cart.reserve}</span></button>
            </div>
          </>
        )}
      </aside>
    </>
  );
};

const Checkout = ({ t, open, items, onClose, onConfirm }) => {
  const [pay, setPay] = useStateUI('card');
  const total = items.reduce((s, it) => s + it.price * it.qty, 0);
  return (
    <div className={`checkout ${open ? 'open' : ''}`}>
      <div className="checkout-head">
        <div className="mono">FRZN · {t.cart.checkout.toUpperCase()}</div>
        <button onClick={onClose} className="mono">✕ CLOSE</button>
      </div>
      <div className="checkout-body">
        <div className="checkout-form">
          <div className="checkout-step">
            <h4><span>01 · Contact</span><span className="num">STEP 1/3</span></h4>
            <div className="field"><label>Email</label><input type="email" placeholder="you@somewhere.cold" defaultValue="" /></div>
          </div>
          <div className="checkout-step">
            <h4><span>02 · Delivery</span><span className="num">STEP 2/3</span></h4>
            <div className="field-row"><div className="field"><label>First name</label><input /></div><div className="field"><label>Last name</label><input /></div></div>
            <div className="field"><label>Address</label><input placeholder="Via Brera, 12" /></div>
            <div className="field-row-3"><div className="field"><label>City</label><input /></div><div className="field"><label>ZIP</label><input /></div><div className="field"><label>Country</label>
              <select defaultValue="IT">
                <option value="IT">IT</option><option value="FR">FR</option><option value="DE">DE</option><option value="ES">ES</option>
                <option value="NL">NL</option><option value="BE">BE</option><option value="FI">FI</option><option value="SE">SE</option><option value="DK">DK</option><option value="NO">NO</option>
              </select>
            </div></div>
          </div>
          <div className="checkout-step">
            <h4><span>03 · Payment</span><span className="num">STEP 3/3</span></h4>
            <div className="pay-methods">
              {['card','klarna','paypal'].map(p => (
                <button key={p} className={`pay-method ${pay === p ? 'active' : ''}`} onClick={() => setPay(p)}>{p.toUpperCase()}</button>
              ))}
            </div>
            {pay === 'card' && (<>
              <div className="field"><label>Card number</label><input placeholder="4242 4242 4242 4242" /></div>
              <div className="field-row"><div className="field"><label>Expiry</label><input placeholder="MM/YY" /></div><div className="field"><label>CVC</label><input placeholder="123" /></div></div>
            </>)}
            {pay === 'klarna' && <p style={{ fontFamily: 'var(--font-serif)', fontStyle: 'italic', fontSize: 17, color: 'var(--ink-2)' }}>Klarna 3× — €{Math.round(total/3)} now · €{Math.round(total/3)} × 2</p>}
            {pay === 'paypal' && <p style={{ fontFamily: 'var(--font-serif)', fontStyle: 'italic', fontSize: 17, color: 'var(--ink-2)' }}>You\u2019ll be redirected to PayPal to complete.</p>}
          </div>
          <button className="btn btn-accent" style={{ width: '100%', justifyContent: 'center', marginTop: 24 }} onClick={onConfirm}>
            <span>RESERVE · €{total}</span><span>→</span>
          </button>
          <div className="trust-strip">
            <span>◎ SSL SECURE</span><span>↩ 60-DAY RETURN</span><span>✓ EU SHIPPING FREE</span><span>♺ CARBON NEG.</span>
          </div>
        </div>
        <div className="checkout-summary">
          <div className="mono" style={{ color: 'var(--ink-3)', marginBottom: 16 }}>ORDER · ED. 001</div>
          {items.map(it => (
            <div key={it.cartId} className="summary-item">
              <div className="thumb"><ThermalSwatch /></div>
              <div><div className="n">{it.name} · {it.size}</div><div className="m">{it.id} · QTY {it.qty}</div></div>
              <div className="p">€{it.price * it.qty}</div>
            </div>
          ))}
          <div className="summary-totals">
            <div className="row"><span>Subtotal</span><span>€{total}</span></div>
            <div className="row"><span>Shipping</span><span>FREE</span></div>
            <div className="row"><span>VAT included</span><span>€{Math.round(total * 0.18)}</span></div>
            <div className="row grand"><span>Total</span><span>€{total}</span></div>
          </div>
        </div>
      </div>
    </div>
  );
};

const Modal = ({ open, title, body, onClose }) => (
  <div className={`modal-backdrop ${open ? 'open' : ''}`} onClick={onClose}>
    <div className="modal" onClick={e => e.stopPropagation()}>
      <h3>{title}</h3>
      <p>{body}</p>
      <button className="btn btn-primary" onClick={onClose}><span>Close</span></button>
    </div>
  </div>
);

const TweaksPanel = ({ visible, values, onChange, onClose }) => {
  if (!visible) return null;
  const ACCENTS = [
    { k:'thermal',hex:'#E8542A'},{k:'ice',hex:'#3B82F6'},{k:'mint',hex:'#00B39A'},
    { k:'ember',hex:'#C2410C'},{k:'xenon',hex:'#FFB800'},{k:'graphite',hex:'#0A0D10'},
  ];
  return (
    <div className="tweaks visible">
      <div className="tweaks-head"><span>Tweaks</span><button onClick={onClose} className="mono">✕</button></div>
      <div className="tweaks-body">
        <div className="tweak-group"><label>Aesthetic</label><div className="tweak-row">
          {[['glacial','Glacial'],['nordic','Nordic'],['clinical','Clinical']].map(([k,l]) => (
            <button key={k} className={`tweak-chip ${values.theme===k?'active':''}`} onClick={() => onChange('theme', k)}>{l}</button>))}
        </div></div>
        <div className="tweak-group"><label>Accent</label><div className="tweak-row">
          {ACCENTS.map(a => (<button key={a.k} className={`tweak-swatch ${values.accent===a.hex?'active':''}`} style={{ background: a.hex }} onClick={() => onChange('accent', a.hex)} />))}
        </div></div>
        <div className="tweak-group"><label>Hero copy</label><div className="tweak-row">
          {[['thermal','Thermal'],['vitality','Vitality'],['protocol','Protocol']].map(([k,l]) => (
            <button key={k} className={`tweak-chip ${values.copy===k?'active':''}`} onClick={() => onChange('copy', k)}>{l}</button>))}
        </div></div>
        <div className="tweak-group"><label>Typography</label><div className="tweak-row">
          {[['display','Bricolage'],['editorial','Fraunces'],['grotesk','Archivo']].map(([k,l]) => (
            <button key={k} className={`tweak-chip ${values.font===k?'active':''}`} onClick={() => onChange('font', k)}>{l}</button>))}
        </div></div>
        <div className="tweak-group"><label>Product card</label><div className="tweak-row">
          {[['default','Lab'],['editorial','Editorial'],['spec','Spec']].map(([k,l]) => (
            <button key={k} className={`tweak-chip ${values.card===k?'active':''}`} onClick={() => onChange('card', k)}>{l}</button>))}
        </div></div>
        <div className="tweak-group"><label>Density</label><div className="tweak-row">
          {[['compact','Compact'],['normal','Normal'],['spacious','Spacious']].map(([k,l]) => (
            <button key={k} className={`tweak-chip ${values.density===k?'active':''}`} onClick={() => onChange('density', k)}>{l}</button>))}
        </div></div>
      </div>
    </div>
  );
};

const Toast = ({ msg, show }) => (<div className={`toast ${show ? 'show' : ''}`}>{msg}</div>);

const StickyBuy = ({ t, onReserve, show }) => (
  <div className={`sticky-buy ${show ? 'visible' : ''}`}>
    <div>
      <div className="label">FRZN · ED. 001</div>
      <div className="title">From €140 · {t.hero.metaReleaseV}</div>
    </div>
    <button onClick={onReserve}>{t.hero.reserve} →</button>
  </div>
);

Object.assign(window, { LANGS, Nav, LangSwitcher, CartDrawer, Checkout, Modal, TweaksPanel, Toast, StickyBuy, ThermalSwatch });
