/* AMBER & ZAFRAN — App shell: routing, language, cart, tweaks */

const TWEAK_DEFAULTS = {
  "heroDefault": "veil",
  "headingFont": "Marcellus",
  "gold": "#DCB16B",
  "burgundy": "#762538",
  "showHeroPicker": false,
  "startLang": "en"
};

/* ---- Status bar (mobile chrome) ---- */
function StatusBar({ dark }) {
  const col = dark ? 'var(--white)' : 'var(--ink)';
  return (
    <div className="statusbar" style={{ color: col }}>
      <span>9:41</span>
      <div className="dots">
        <svg width="18" height="11" viewBox="0 0 18 11" fill="none"><rect x="0" y="6" width="3" height="5" rx="1" fill={col}/><rect x="4.5" y="4" width="3" height="7" rx="1" fill={col}/><rect x="9" y="2" width="3" height="9" rx="1" fill={col}/><rect x="13.5" y="0" width="3" height="11" rx="1" fill={col} opacity="0.4"/></svg>
        <svg width="16" height="11" viewBox="0 0 16 11" fill="none"><path d="M8 2.2C10.3 2.2 12.4 3.1 14 4.6L8 11 2 4.6C3.6 3.1 5.7 2.2 8 2.2Z" fill={col}/></svg>
        <svg width="25" height="12" viewBox="0 0 25 12" fill="none"><rect x="0.5" y="0.5" width="21" height="11" rx="3" stroke={col} opacity="0.5"/><rect x="2" y="2" width="16" height="8" rx="1.5" fill={col}/><rect x="23" y="4" width="1.5" height="4" rx="0.75" fill={col} opacity="0.5"/></svg>
      </div>
    </div>
  );
}

/* ---- Nav menu overlay ---- */
function NavMenu({ t, lang, setLang, close, go }) {
  const links = [['home', t.nav.home], ['shop', t.nav.shop], ['collections', t.nav.collections], ['gifting', t.nav.gifting], ['story', t.nav.story], ['wishlist', t.nav.wishlist]];
  return (
    <div className="menu">
      <StatusBar dark />
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '8px 20px 14px' }}>
        <button onClick={() => setLang(lang === 'en' ? 'ar' : 'en')} style={{ display: 'flex', alignItems: 'center', gap: 7, color: 'var(--gold)', fontFamily: 'var(--sans)', fontSize: 12, letterSpacing: '.1em' }}><Icon.globe /> {lang === 'en' ? 'العربية' : 'EN'}</button>
        <button className="iconbtn" style={{ color: 'var(--white)' }} onClick={close} aria-label={lang === 'ar' ? 'إغلاق' : 'Close menu'}><Icon.close /></button>
      </div>
      <nav style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', padding: '0 30px' }}>
        {links.map(([v, label], i) => (
          <button key={i} onClick={() => { go(v); close(); }} style={{ textAlign: lang === 'ar' ? 'right' : 'left', padding: '15px 0', borderBottom: '1px solid rgba(255,255,255,.1)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <span style={{ fontFamily: lang === 'ar' ? 'var(--arabic-display)' : 'var(--serif)', fontSize: 30, color: 'var(--white)' }}>{label}</span>
            <span style={{ fontFamily: 'var(--serif)', fontSize: 12, color: 'var(--gold)' }}>{String(i + 1).padStart(2, '0')}</span>
          </button>
        ))}
      </nav>
      <div style={{ padding: '24px 30px 36px', textAlign: 'center' }}>
        <img src="assets/mark-gold.png" alt="" style={{ width: 56, margin: '0 auto 12px' }} />
        <div style={{ fontFamily: lang === 'ar' ? 'var(--arabic)' : 'var(--serif-it)', fontStyle: lang === 'ar' ? 'normal' : 'italic', fontSize: 14, color: 'var(--rose)' }}>{t.tagline}</div>
      </div>
    </div>
  );
}

/* ---- Cart drawer ---- */
function Cart({ t, lang, cart, close, onChangeQty, onRemove, go }) {
  const subtotal = cart.reduce((s, it) => s + it.price * it.qty, 0);
  const setQty = (it, d) => onChangeQty(it.productVariantId, Math.max(1, it.qty + d));
  const remove = (it) => onRemove(it.productVariantId);
  return (
    <>
      <div className="scrim" onClick={close}></div>
      <div className="drawer">
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '24px 24px 18px', borderBottom: '1px solid var(--line)' }}>
          <span style={{ fontFamily: lang === 'ar' ? 'var(--arabic-display)' : 'var(--serif)', fontSize: 24 }}>{t.bag}</span>
          <button onClick={close} aria-label={lang === 'ar' ? 'إغلاق السلة' : 'Close cart'}><Icon.close /></button>
        </div>
        {cart.length === 0 ? (
          <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 20, padding: 30 }}>
            <img src="assets/mark-black.png" alt="" style={{ width: 70, opacity: .5 }} />
            <p className="body" style={{ textAlign: 'center' }}>{t.bagEmpty}</p>
            <button className="btn btn-fill" onClick={() => { close(); go('shop'); }}>{t.continue}</button>
          </div>
        ) : (
          <>
            <div style={{ flex: 1, overflowY: 'auto', padding: '8px 24px' }}>
              {cart.map((it, i) => (
                <div key={i} style={{ display: 'flex', gap: 14, padding: '18px 0', borderBottom: '1px solid var(--line-2)' }}>
                  <div style={{ width: 64, height: 80, background: 'linear-gradient(160deg,#efe6da,#e2d4c4)', position: 'relative', flex: 'none', overflow: 'hidden' }}>
                    <div style={{ position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%,-50%)' }}><Flacon p={it.p} scale={0.42} showLabel={false} /></div>
                  </div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontFamily: lang === 'ar' ? 'var(--arabic)' : 'var(--serif)', fontSize: 16 }}>{lang === 'ar' ? it.p.ar : it.p.name}</div>
                    <div style={{ fontFamily: 'var(--sans)', fontSize: 10, letterSpacing: '.1em', color: 'var(--ink-soft)', textTransform: 'uppercase', marginTop: 3 }}>{it.size}</div>
                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 12 }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 12, border: '1px solid var(--line)', padding: '5px 10px' }}>
                        <button onClick={() => setQty(it, -1)}><Icon.minus /></button>
                        <span style={{ fontFamily: 'var(--serif)', fontSize: 14, minWidth: 16, textAlign: 'center' }}>{it.qty}</span>
                        <button onClick={() => setQty(it, 1)}><Icon.plus /></button>
                      </div>
                      <span style={{ fontFamily: 'var(--sans)', fontSize: 14 }}>{t.currency} {it.price * it.qty}</span>
                    </div>
                    {it.inStock === false && (
                      <div style={{ fontFamily: 'var(--sans)', fontSize: 10, letterSpacing: '.06em', color: 'var(--burgundy)', marginTop: 6 }}>
                        {lang === 'ar' ? `متبقٍ ${it.availableQty} فقط في المخزون` : `Only ${it.availableQty} left in stock`}
                      </div>
                    )}
                    <button onClick={() => remove(it)} style={{ fontFamily: 'var(--sans)', fontSize: 10, letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--ink-soft)', marginTop: 10, borderBottom: '1px solid var(--line)' }}>{t.remove}</button>
                  </div>
                </div>
              ))}
            </div>
            <div style={{ padding: '20px 24px 28px', borderTop: '1px solid var(--line)', background: 'var(--cream)' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 4 }}>
                <span style={{ fontFamily: 'var(--sans)', fontSize: 11, letterSpacing: '.16em', textTransform: 'uppercase', color: 'var(--ink-soft)' }}>{t.subtotal}</span>
                <span style={{ fontFamily: 'var(--serif)', fontSize: 26 }}>{t.currency} {subtotal}</span>
              </div>
              <div style={{ fontFamily: lang === 'ar' ? 'var(--arabic)' : 'var(--sans)', fontSize: 11, color: 'var(--ink-soft)', marginBottom: 16 }}>{t.freeNote}</div>
              <button className="btn btn-burg btn-block" onClick={() => { close(); go('checkout'); }}>{t.checkout} <Icon.arrow className="arr" /></button>
            </div>
          </>
        )}
      </div>
    </>
  );
}

/* ---- Root App ---- */
function App() {
  const [tw, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [lang, setLang] = useState(tw.startLang || 'en');
  // Phase 3C-A: if the browser was just redirected back from Network's
  // hosted payment page, land on a neutral "confirming/cancelled"
  // screen instead of silently dropping the customer on the Homepage
  // with no explanation. This is the one place this SPA reads the
  // real URL at all — everything else navigates via in-memory `view`
  // state, never the address bar.
  const [view, setView] = useState(() => {
    const params = new URLSearchParams(window.location.search);
    const payment = params.get('payment');
    const orderNumber = params.get('order');
    if (payment && orderNumber) {
      window.history.replaceState({}, '', window.location.pathname);
      return { name: 'payment-return', product: { outcome: payment, orderNumber } };
    }
    return { name: 'home', product: null };
  });
  const [hero, setHero] = useState(tw.heroDefault);
  const [menu, setMenu] = useState(false);
  const [cartOpen, setCartOpen] = useState(false);
  // Phase 3A: cart is persisted server-side (Supabase, via the Cart
  // API) and keyed by an anonymous guest session id in localStorage —
  // `cart` itself stays the exact same array shape it always was
  // ({key,p,size,price,qty}, see app/cart.js's mapCartItem), so the
  // drawer/Checkout JSX below didn't need to change to read it.
  const [cart, setCart] = useState([]);
  const [promo, setPromo] = useState(null);
  const [discountAmount, setDiscountAmount] = useState(0);
  const [wish, setWish] = useState([]);
  const [toast, setToast] = useState('');
  const [scrolled, setScrolled] = useState(false);
  const screenRef = useRef(null);
  const rootRef = useRef(null);
  const t = AZ.T[lang];

  // Phase 7 — Production Readiness Audit: Escape closes whichever
  // overlay (nav menu, cart drawer) is open — these are dismissed by
  // tapping a backdrop today, which has no keyboard equivalent.
  useEffect(() => {
    const onKeyDown = (e) => {
      if (e.key !== 'Escape') return;
      if (menu) setMenu(false);
      else if (cartOpen) setCartOpen(false);
    };
    document.addEventListener('keydown', onKeyDown);
    return () => document.removeEventListener('keydown', onKeyDown);
  }, [menu, cartOpen]);

  useEffect(() => {
    if (rootRef.current) rootRef.current.classList.remove('settled');
    const id = setTimeout(() => rootRef.current && rootRef.current.classList.add('settled'), 2600);
    return () => clearTimeout(id);
  }, [view, hero]);
  useEffect(() => { setHero(tw.heroDefault); }, [tw.heroDefault]);
  useEffect(() => { if (screenRef.current) screenRef.current.scrollTop = 0; }, [view]);
  useEffect(() => {
    const el = screenRef.current; if (!el) return;
    const fn = () => setScrolled(el.scrollTop > 30);
    el.addEventListener('scroll', fn); return () => el.removeEventListener('scroll', fn);
  }, [view]);

  // Mouse drag-to-scroll for every .hscroll row (Shop/Search chips, Homepage
  // rails, Loyalty scroller, PDP related). Touch already scrolls these
  // natively, so this only activates for pointerType === 'mouse' — a desktop
  // mouse has no horizontal wheel axis and no visible scrollbar here, so
  // without this there's no way to scroll these rows without a trackpad.
  useEffect(() => {
    let dragEl = null, startX = 0, startScroll = 0, moved = false;
    const onDown = (e) => {
      if (e.pointerType !== 'mouse') return;
      const row = e.target.closest && e.target.closest('.hscroll');
      if (!row) return;
      dragEl = row; startX = e.clientX; startScroll = row.scrollLeft; moved = false;
      row.classList.add('dragging');
    };
    const onMove = (e) => {
      if (!dragEl) return;
      const dx = e.clientX - startX;
      if (Math.abs(dx) > 3) moved = true;
      dragEl.scrollLeft = startScroll - dx;
    };
    const endDrag = () => { if (dragEl) dragEl.classList.remove('dragging'); dragEl = null; };
    const onClickCapture = (e) => {
      if (moved) { e.preventDefault(); e.stopPropagation(); moved = false; }
    };
    document.addEventListener('pointerdown', onDown);
    document.addEventListener('pointermove', onMove);
    document.addEventListener('pointerup', endDrag);
    document.addEventListener('click', onClickCapture, true);
    return () => {
      document.removeEventListener('pointerdown', onDown);
      document.removeEventListener('pointermove', onMove);
      document.removeEventListener('pointerup', endDrag);
      document.removeEventListener('click', onClickCapture, true);
    };
  }, []);

  const go = useCallback((name, product = null) => { setView({ name, product }); setMenu(false); }, []);
  const onOpen = useCallback((p) => { setView({ name: 'pdp', product: p }); }, []);
  const toggleWish = useCallback((id) => setWish(w => w.includes(id) ? w.filter(x => x !== id) : [...w, id]), []);

  // Loads the persisted cart once on first mount (the guest session id,
  // if any, already lives in localStorage from a previous visit — see
  // app/cart.js). This is what makes the cart survive a page refresh.
  const applyCartResult = useCallback((result) => {
    setCart(result.items);
    setPromo(result.promo);
    setDiscountAmount(result.discountAmount);
  }, []);
  useEffect(() => {
    AZCart.fetchCart().then(applyCartResult).catch((e) => console.error('Failed to load cart', e));
  }, [applyCartResult]);

  const addToCart = useCallback((p, size, qty) => {
    const variantId = size[2];
    AZCart.addItem(variantId, qty).then(applyCartResult).catch((e) => console.error('Failed to add to cart', e));
    setToast(t.adding); setTimeout(() => setToast(''), 1900);
  }, [t, applyCartResult]);
  const changeCartQty = useCallback((productVariantId, qty) => {
    AZCart.setItemQuantity(productVariantId, qty).then(applyCartResult).catch((e) => console.error('Failed to update cart', e));
  }, [applyCartResult]);
  const removeFromCart = useCallback((productVariantId) => {
    AZCart.removeItem(productVariantId).then(applyCartResult).catch((e) => console.error('Failed to remove cart item', e));
  }, [applyCartResult]);
  const applyPromoCode = useCallback((code) => {
    return AZCart.applyPromo(code).then((result) => { applyCartResult(result); return result.promo; });
  }, [applyCartResult]);
  const removePromoCode = useCallback(() => {
    AZCart.removePromo().then(applyCartResult).catch((e) => console.error('Failed to remove promo', e));
  }, [applyCartResult]);
  // Phase 3B: after a real order is placed, the cart that became it was
  // marked "converted" server-side — this fetches the fresh, empty
  // active cart the next checkout starts from (no local setCart([])
  // needed; the server is still the single source of truth, same
  // principle as every other cart mutation).
  const refreshCartAfterOrder = useCallback(() => {
    AZCart.fetchCart().then(applyCartResult).catch((e) => console.error('Failed to refresh cart after order', e));
  }, [applyCartResult]);

  const cartCount = cart.reduce((s, it) => s + it.qty, 0);
  const isPdp = view.name === 'pdp';
  // appbar dark on PDP gallery top & home veil top
  const DARK_TOP_PAGES = ['shop', 'wishlist', 'story', 'collections', 'gifting', 'vip'];
  const appbarDark = !scrolled && ((view.name === 'home' && hero === 'veil') || DARK_TOP_PAGES.includes(view.name) || (isPdp && false));
  const heroDarkTop = (view.name === 'home' && hero === 'veil') || DARK_TOP_PAGES.includes(view.name);
  const statusDark = !scrolled && heroDarkTop;

  return (
    <div ref={rootRef} dir={t.dir} style={{ position: 'relative', '--gold': tw.gold, '--burgundy': tw.burgundy, '--serif': `'${tw.headingFont}', 'Cormorant Garamond', Georgia, serif`, height: '100%' }}>
      <div className="screen" ref={screenRef}>
        {view.name !== 'checkout' && view.name !== 'search' && (
        <div style={{ position: 'sticky', top: 0, zIndex: 36 }}>
          <div style={{ background: scrolled ? 'rgba(251,248,243,.86)' : 'transparent', backdropFilter: scrolled ? 'blur(18px)' : 'none', transition: 'background .4s var(--ease)' }}>
            <StatusBar dark={statusDark && !scrolled} />
            <div className={`appbar ${scrolled ? 'solid' : ''}`} style={{ color: (heroDarkTop && !scrolled) ? 'var(--white)' : 'var(--ink)' }}>
              <button className="iconbtn" onClick={() => setMenu(true)} aria-label={lang === 'ar' ? 'القائمة' : 'Menu'}><Icon.menu /></button>
              <button onClick={() => go('home')}><Wordmark tagline /></button>
              <div style={{ display: 'flex' }}>
                <button className="iconbtn" onClick={() => go('search')} aria-label={lang === 'ar' ? 'بحث' : 'Search'}><Icon.search /></button>
                <button className="iconbtn" onClick={() => setLang(lang === 'en' ? 'ar' : 'en')} aria-label={lang === 'en' ? 'التبديل إلى العربية' : 'Switch to English'} style={{ fontFamily: 'var(--sans)', fontSize: 11, letterSpacing: '.08em', width: 'auto', padding: '0 8px' }}>{lang === 'en' ? 'ع' : 'EN'}</button>
                <button className="iconbtn" onClick={() => setCartOpen(true)} aria-label={lang === 'ar' ? 'السلة' : 'Cart'}><Icon.bag />{cartCount > 0 && <span className="bag-count">{cartCount}</span>}</button>
              </div>
            </div>
          </div>
        </div>
        )}

        <main style={{ marginTop: (view.name === 'checkout' || view.name === 'search') ? 0 : -98 }}>
          {view.name === 'home' && <Home t={t} lang={lang} go={go} onOpen={onOpen} wish={wish} toggleWish={toggleWish} hero={hero} setHero={setHero} />}
          {view.name === 'shop' && <Shop t={t} lang={lang} go={go} onOpen={onOpen} wish={wish} toggleWish={toggleWish} initialCollectionId={view.product && view.product.collectionId} />}
          {view.name === 'search' && <Search t={t} lang={lang} go={go} onOpen={onOpen} wish={wish} toggleWish={toggleWish} />}
          {view.name === 'wishlist' && <Wishlist t={t} lang={lang} go={go} onOpen={onOpen} wish={wish} toggleWish={toggleWish} />}
          {view.name === 'story' && <Story t={t} lang={lang} go={go} />}
          {view.name === 'collections' && <Collections t={t} lang={lang} go={go} />}
          {view.name === 'gifting' && <Gifting t={t} lang={lang} go={go} />}
          {view.name === 'vip' && <VIP t={t} lang={lang} go={go} />}
          {view.name === 'pdp' && <PDP product={view.product} t={t} lang={lang} go={go} addToCart={addToCart} onOpen={onOpen} wish={wish} toggleWish={toggleWish} />}
          {view.name === 'checkout' && <Checkout t={t} lang={lang} go={go} cart={cart} promo={promo} discountAmount={discountAmount} applyPromoCode={applyPromoCode} removePromoCode={removePromoCode} onOrderPlaced={refreshCartAfterOrder} />}
          {view.name === 'payment-return' && <PaymentReturn t={t} lang={lang} go={go} outcome={view.product.outcome} orderNumber={view.product.orderNumber} />}
        </main>
      </div>

      {/* PDP back button (floating) */}
      {isPdp && (
        <button onClick={() => go('shop')} style={{ position: 'absolute', top: 56, left: t.dir === 'rtl' ? 'auto' : 18, right: t.dir === 'rtl' ? 18 : 'auto', zIndex: 40, width: 42, height: 42, borderRadius: '50%', background: 'rgba(251,248,243,.85)', backdropFilter: 'blur(8px)', display: 'grid', placeItems: 'center', boxShadow: '0 4px 16px rgba(0,0,0,.12)' }}>
          <Icon.chevron style={{ transform: t.dir === 'rtl' ? 'none' : 'rotate(180deg)' }} />
        </button>
      )}

      {menu && <NavMenu t={t} lang={lang} setLang={setLang} close={() => setMenu(false)} go={go} />}
      {cartOpen && <Cart t={t} lang={lang} cart={cart} close={() => setCartOpen(false)} onChangeQty={changeCartQty} onRemove={removeFromCart} go={go} />}
      {toast && <div className="toast"><Icon.bag style={{ color: 'var(--gold)' }} /> {toast}</div>}

      <TweaksPanel>
        <TweakSection label={lang === 'ar' ? 'الواجهة' : 'Hero'} />
        <TweakRadio label="Direction" value={tw.heroDefault} options={['veil', 'split', 'atelier']} onChange={v => setTweak('heroDefault', v)} />
        <TweakSection label="Typography" />
        <TweakSelect label="Heading face" value={tw.headingFont} options={['Marcellus', 'Cormorant Garamond']} onChange={v => setTweak('headingFont', v)} />
        <TweakSection label="Palette" />
        <TweakColor label="Gold" value={tw.gold} options={['#DCB16B', '#C9A24A', '#E4C078', '#B8893B']} onChange={v => setTweak('gold', v)} />
        <TweakColor label="Burgundy" value={tw.burgundy} options={['#762538', '#5E1B2A', '#8A2E3E', '#4A1622']} onChange={v => setTweak('burgundy', v)} />
        <TweakSection label="Language" />
        <TweakRadio label="Start in" value={tw.startLang} options={['en', 'ar']} onChange={v => { setTweak('startLang', v); setLang(v); }} />
      </TweaksPanel>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
Object.assign(window, { StatusBar });
