// app.jsx — storefront root: state, routing, fly-to-cart animation, Tweaks
// NOTE: admin is now a separate file (Admin Dashboard.html)

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "palette": ["#F2EBDD", "#1C140F", "#8E2B3A", "#B08A3E"],
  "fontPair": "aref-fraunces",
  "gridCols": 3,
  "dark": false
}/*EDITMODE-END*/;

const PALETTES = {
  'garnet-bone':    { name:'Garnet',     colors:['#F2EBDD','#1C140F','#8E2B3A','#B08A3E'] },
  'oudh-noir':      { name:'Oudh Noir',  colors:['#15100B','#F0E7D6','#C2453F','#C79A4C'] },
  'saffron-ivory':  { name:'Saffron',    colors:['#F4EEE2','#211913','#C06A2C','#7C6A45'] },
  'rose-attar':     { name:'Rose Attar', colors:['#F3E7E2','#1E1411','#A23B53','#9C7A4A'] },
  'jade-parchment': { name:'Jade',       colors:['#EFEBDD','#16190F','#3F5C46','#B08A3E'] },
};

const FONT_PAIRS = {
  'aref-fraunces': {
    name: 'Aref Ruqaa × Fraunces',
    google: 'Aref+Ruqaa:wght@400;700|El+Messiri:wght@400;500;600;700|Fraunces:ital,opsz,wght@0,9..144,400;0,9..144,500;0,9..144,600;1,9..144,400;1,9..144,500|Hanken+Grotesk:wght@400;500;600;700',
    arHead: '"Aref Ruqaa", serif', arBody: '"El Messiri", system-ui, sans-serif',
    enHead: '"Fraunces", serif', enBody: '"Hanken Grotesk", system-ui, sans-serif',
  },
  'messiri-fraunces': {
    name: 'El Messiri × Fraunces',
    google: 'El+Messiri:wght@400;500;600;700|Fraunces:ital,opsz,wght@0,9..144,400;0,9..144,500;1,9..144,400|Hanken+Grotesk:wght@400;500;600;700',
    arHead: '"El Messiri", serif', arBody: '"El Messiri", system-ui, sans-serif',
    enHead: '"Fraunces", serif', enBody: '"Hanken Grotesk", system-ui, sans-serif',
  },
  'reem-marcellus': {
    name: 'Reem Kufi × Marcellus',
    google: 'Reem+Kufi:wght@400;500;600;700|Marcellus:wght@400|Hanken+Grotesk:wght@400;500;600',
    arHead: '"Reem Kufi", sans-serif', arBody: '"Reem Kufi", sans-serif',
    enHead: '"Marcellus", serif', enBody: '"Hanken Grotesk", sans-serif',
  },
};

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [route, _setRoute] = React.useState('home');
  const [routeData, setRouteData] = React.useState(null);
  const [lang, setLang] = React.useState('ar');
  const [cart, setCart] = React.useState([]);
  const [pdpProduct, setPdpProduct] = React.useState(null);
  const [searchOpen, setSearchOpen] = React.useState(false);
  const [lastOrder, setLastOrder] = React.useState(null);
  const cartBadgeRef = React.useRef();

  const setRoute = (r, data) => {
    _setRoute(r);
    setRouteData(data || null);
    window.scrollTo({ top: 0, behavior: 'instant' });
  };

  const openPDP = (p) => { setPdpProduct(p); setRoute('pdp'); };

  // ── flying bottle animation ───────────────────
  const flyToCart = (sourceEl, color) => {
    if (!sourceEl || !cartBadgeRef.current) return;
    const srcRect = sourceEl.getBoundingClientRect();
    const tgtRect = cartBadgeRef.current.getBoundingClientRect();
    const fly = document.createElement('div');
    fly.className = 'fly';
    fly.style.background = `linear-gradient(170deg, ${color}, color-mix(in oklab, ${color} 55%, #000))`;
    fly.style.left = srcRect.left + srcRect.width / 2 - 20 + 'px';
    fly.style.top = srcRect.top + srcRect.height / 2 - 25 + 'px';
    document.body.appendChild(fly);
    requestAnimationFrame(() => {
      fly.style.transform = `translate(${tgtRect.left - srcRect.left - srcRect.width / 2 + 20 + tgtRect.width/2}px, ${tgtRect.top - srcRect.top - srcRect.height / 2 + 25}px) scale(0.2) rotate(360deg)`;
      fly.style.opacity = '0.3';
    });
    setTimeout(() => {
      fly.remove();
      const badge = document.querySelector('[data-cart-badge]');
      if (badge) { badge.classList.remove('cart-badge-shake'); void badge.offsetWidth; badge.classList.add('cart-badge-shake'); }
    }, 720);
  };

  const addToCart = (product, sourceEl, size) => {
    const sz = size || product.sizes[1];
    setCart(prev => {
      const idx = prev.findIndex(i => i.id === product.id && i.size === sz.ml);
      if (idx >= 0) {
        const next = [...prev];
        next[idx] = { ...next[idx], qty: next[idx].qty + 1 };
        return next;
      }
      return [...prev, {
        id: product.id, name_ar: product.name_ar, name_en: product.name_en,
        tone: product.tone, concentration: product.concentration,
        size: sz.ml, price: sz.price, qty: 1,
      }];
    });
    flyToCart(sourceEl, product.tone);
  };

  // ── theme injection ────────────────────────────
  const fontPair = FONT_PAIRS[t.fontPair] || FONT_PAIRS['messiri-cormorant'];

  React.useEffect(() => {
    document.documentElement.lang = lang;
    document.documentElement.dir = lang === 'ar' ? 'rtl' : 'ltr';
  }, [lang]);

  React.useEffect(() => {
    const id = 'dyn-fonts';
    let l = document.getElementById(id);
    if (!l) { l = document.createElement('link'); l.id = id; l.rel = 'stylesheet'; document.head.appendChild(l); }
    l.href = `https://fonts.googleapis.com/css2?family=${fontPair.google.replace(/\|/g, '&family=')}&family=JetBrains+Mono:wght@400;500&display=swap`;
  }, [t.fontPair]);

  const styleVars = {
    '--bg':       t.palette[0],
    '--bg-2':     `color-mix(in oklab, ${t.palette[0]} 88%, ${t.palette[1]})`,
    '--paper':    `color-mix(in oklab, ${t.palette[0]} 96%, #fff)`,
    '--ink':      t.palette[1],
    '--ink-2':    `color-mix(in oklab, ${t.palette[1]} 75%, ${t.palette[0]})`,
    '--ink-3':    `color-mix(in oklab, ${t.palette[1]} 50%, ${t.palette[0]})`,
    '--line':     `color-mix(in oklab, ${t.palette[1]} 14%, transparent)`,
    '--line-2':   `color-mix(in oklab, ${t.palette[1]} 7%, transparent)`,
    '--accent':   t.palette[2],
    '--accent-2': t.palette[3],
    '--f-ar-head': fontPair.arHead,
    '--f-ar-body': fontPair.arBody,
    '--f-en-head': fontPair.enHead,
    '--f-en-body': fontPair.enBody,
  };

  const cartCount = cart.reduce((s, i) => s + i.qty, 0);
  const minimalNav = route === 'checkout' || route === 'confirm';

  return (
    <div className="app" style={styleVars}
         data-theme={t.dark ? 'dark' : 'light'}
         data-lang={lang}
         data-grid={String(t.gridCols)}
         data-screen-label={route}>

      <Nav route={route} setRoute={setRoute} cartCount={cartCount}
           lang={lang} setLang={setLang}
           cartBadgeRef={cartBadgeRef}
           onSearchOpen={() => setSearchOpen(true)} />

      <SearchOverlay open={searchOpen} onClose={() => setSearchOpen(false)}
                     onPick={openPDP} lang={lang} />

      {route === 'home'     && <Home lang={lang} setRoute={setRoute} openPDP={openPDP} />}
      {route === 'shop'     && <Shop lang={lang} openPDP={openPDP} addToCart={addToCart} filterPrefill={routeData} />}
      {route === 'pdp'      && pdpProduct && <PDP product={pdpProduct} lang={lang} addToCart={addToCart} setRoute={setRoute} openPDP={openPDP} />}
      {route === 'cart'     && <Cart items={cart} setItems={setCart} lang={lang} setRoute={setRoute} />}
      {route === 'checkout' && <Checkout items={cart} lang={lang} setRoute={(r) => { if (r === 'confirm') setCart([]); setRoute(r); }} setLastOrder={setLastOrder} />}
      {route === 'confirm'  && <Confirmation order={lastOrder} lang={lang} setRoute={setRoute} />}
      {route === 'story'    && <Story lang={lang} setRoute={setRoute} />}
      {route === 'attars'   && <Attars lang={lang} setRoute={setRoute} />}

      {!minimalNav && <Footer lang={lang} setRoute={setRoute} />}

      <IstabraqTweaks t={t} setTweak={setTweak} lang={lang} />
    </div>
  );
}

function Story({ lang, setRoute }) {
  const t = (ar, en) => lang === 'ar' ? ar : en;
  return (
    <section className="section story-section">
      <div className="story-inner">
        <div className="eyebrow">{t('قصتنا', 'Our story')}</div>
        <h1 className="h-display story-title">
          {t('بدأت من حقول الورد في ميسور.', 'It began in the rose fields of Mysore.')}
        </h1>
        <p className="story-body">
          {t('استبرق هي بيت عطور مقرّه دبي، يستورد ويوزّع أرقى العطور المقطّرة يدوياً من بيوت العائلات الهندية. نعمل مع 12 عطّاراً عبر ميسور، آسام، كشمير، ولكنو — كل قطرة تحمل توقيع صانعها.',
             'Istabraq is a Dubai-based perfumery, importing and decanting the finest hand-distilled fragrances from Indian family ateliers. We work with 12 attar masters across Mysore, Assam, Kashmir and Lucknow — every drop bears its maker\'s signature.')}
        </p>
        <button className="btn lg" style={{ marginTop: 32 }} onClick={() => setRoute('shop')}>
          {t('تسوّق الكولكشن', 'Shop the collection')} <I.arrow />
        </button>
      </div>
    </section>
  );
}

function Attars({ lang, setRoute }) {
  const t = (ar, en) => lang === 'ar' ? ar : en;
  return (
    <>
      <section className="attars-hero">
        <div className="eyebrow">{t('العطّارون', 'The Attar Masters')}</div>
        <h1 className="h-display attars-hero-title">
          {t('اثنا عشر يداً', 'Twelve hands')}
          <em>{t('تقطّر روح الهند.', 'distil the soul of India.')}</em>
        </h1>
        <p className="attars-hero-sub">
          {t('خلف كل زجاجة من استبرق، عطّار يعمل بطرق توارثتها العائلات منذ قرون. هؤلاء بعضٌ منهم.',
             'Behind every Istabraq bottle is an attar maker working by methods passed down through families for centuries. These are a few of them.')}
        </p>
      </section>

      <section className="attars-list">
        {ATTARS.map((a, i) => (
          <article key={a.id} className="attar-row" style={{ '--at': a.tone }}>
            <div className="attar-portrait">
              <div className="attar-portrait-glow" />
              <div className="attar-monogram serif-en">{a.name_en.split(' ').map(w => w[0]).join('')}</div>
              <div className="attar-no mono">N°{String(i + 1).padStart(2, '0')}</div>
            </div>
            <div className="attar-body">
              <div className="attar-meta">
                <span>{lang === 'ar' ? a.city_ar : a.city_en}</span>
                <span className="dot-sep">·</span>
                <span className="mono">{t('منذ', 'since')} {a.since}</span>
              </div>
              <h2 className="h-display attar-name">{lang === 'ar' ? a.name_ar : a.name_en}</h2>
              <div className="attar-craft serif-en">{lang === 'ar' ? a.craft_ar : a.craft_en}</div>
              <p className="attar-bio">{lang === 'ar' ? a.bio_ar : a.bio_en}</p>
              <blockquote className="attar-quote">"{lang === 'ar' ? a.quote_ar : a.quote_en}"</blockquote>
            </div>
          </article>
        ))}
      </section>

      <section className="manifesto" style={{ borderTop: '1px solid var(--line)' }}>
        <div className="manifesto-inner">
          <div className="eyebrow" style={{ color: 'rgba(255,255,255,0.6)' }}>{t('الكولكشن', 'The collection')}</div>
          <h2 className="h-display manifesto-title">{t('تذوّق عملهم', 'Taste their work')}</h2>
          <button className="btn lg" style={{ background: '#fff', color: '#1a1a1a', borderColor: '#fff' }} onClick={() => setRoute('shop')}>
            {t('تسوّق العطور', 'Shop the fragrances')} <I.arrow />
          </button>
        </div>
      </section>
    </>
  );
}

function Footer({ lang, setRoute }) {
  const t = (ar, en) => lang === 'ar' ? ar : en;
  const go = (r, data) => { if (setRoute) setRoute(r, data); };
  return (
    <footer className="footer">
      <div className="footer-brand">
        <div className="brand-mark">{lang === 'ar' ? 'استبرق' : 'ISTABRAQ'}</div>
        <div className="brand-mark-en" style={{ color: 'rgba(255,255,255,0.6)' }}>{t('عطور هندية، مقطّرة في دبي', 'Indian perfumery, decanted in Dubai')}</div>
        <p className="footer-desc">
          {t('بيت عطور صغير يجمع روائح الهند ويُحضرها لخزانتك.', 'A small perfumery bringing India\'s scents to your shelf.')}
        </p>
      </div>
      <div className="footer-cols">
        <div>
          <h4>{t('المتجر', 'Shop')}</h4>
          <a onClick={() => go('shop')}>{t('كل العطور', 'All fragrances')}</a>
          <a onClick={() => go('shop', { family: 'oud' })}>{t('العود', 'Oud')}</a>
          <a onClick={() => go('shop', { family: 'rose' })}>{t('الورد', 'Rose')}</a>
          <a onClick={() => go('shop')}>{t('عينات', 'Samples')}</a>
        </div>
        <div>
          <h4>{t('عن استبرق', 'Istabraq')}</h4>
          <a onClick={() => go('story')}>{t('قصتنا', 'Our story')}</a>
          <a onClick={() => go('attars')}>{t('العطّارون', 'Attar masters')}</a>
          <a onClick={() => go('attars')}>{t('المتاجر', 'Boutiques')}</a>
        </div>
        <div>
          <h4>{t('المساعدة', 'Help')}</h4>
          <a>{t('الشحن والإرجاع', 'Shipping & returns')}</a>
          <a>{t('الأسئلة الشائعة', 'FAQ')}</a>
          <a>{t('اتصل بنا', 'Contact')}</a>
        </div>
      </div>
      <div className="footer-bottom">
        <span>© 2026 Istabraq Perfumery · TRN 100123456700003</span>
        <a href="Admin Dashboard.html" className="footer-admin"><I.lock /> {t('دخول الإدارة', 'Admin')}</a>
      </div>
    </footer>
  );
}

function IstabraqTweaks({ t, setTweak, lang }) {
  return (
    <TweaksPanel title="Tweaks">
      <TweakSection label="Theme">
        <TweakColor label="Palette" value={t.palette}
                    options={Object.values(PALETTES).map(p => p.colors)}
                    onChange={(v) => setTweak('palette', v)} />
        <TweakToggle label="Dark mode" value={t.dark} onChange={(v) => setTweak('dark', v)} />
      </TweakSection>
      <TweakSection label="Typography">
        <TweakSelect label="Font pair" value={t.fontPair}
                     options={Object.entries(FONT_PAIRS).map(([k, v]) => ({ value: k, label: v.name }))}
                     onChange={(v) => setTweak('fontPair', v)} />
      </TweakSection>
      <TweakSection label="Catalog">
        <TweakRadio label="Grid" value={t.gridCols}
                    options={[{value:2,label:'2'},{value:3,label:'3'},{value:4,label:'4'}]}
                    onChange={(v) => setTweak('gridCols', v)} />
      </TweakSection>
    </TweaksPanel>
  );
}

window.App = App;
