/* AMBER & ZAFRAN — shared UI primitives */
const { useState, useEffect, useRef, useCallback } = React;

/* ---------- Icons (1.4px hairline, luxury) ---------- */
const Icon = {
  menu: (p) => <svg width="22" height="22" viewBox="0 0 22 22" fill="none" {...p}><path d="M3 6.5h16M3 11h16M3 15.5h11" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round"/></svg>,
  bag: (p) => <svg width="22" height="22" viewBox="0 0 22 22" fill="none" {...p}><path d="M6 7V5.5a5 5 0 0110 0V7M4.2 7h13.6l-.9 11.2a1.6 1.6 0 01-1.6 1.5H6.7a1.6 1.6 0 01-1.6-1.5L4.2 7z" stroke="currentColor" strokeWidth="1.3" strokeLinejoin="round"/></svg>,
  search: (p) => <svg width="22" height="22" viewBox="0 0 22 22" fill="none" {...p}><circle cx="10" cy="10" r="6.2" stroke="currentColor" strokeWidth="1.3"/><path d="M15 15l4 4" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round"/></svg>,
  heart: (p) => <svg width="18" height="18" viewBox="0 0 22 22" fill="none" {...p}><path d="M11 18.5S3.5 13.8 3.5 8.6A4.1 4.1 0 0111 6.1a4.1 4.1 0 017.5 2.5c0 5.2-7.5 9.9-7.5 9.9z" stroke="currentColor" strokeWidth="1.3" strokeLinejoin="round"/></svg>,
  heartFill: (p) => <svg width="18" height="18" viewBox="0 0 22 22" {...p}><path d="M11 18.5S3.5 13.8 3.5 8.6A4.1 4.1 0 0111 6.1a4.1 4.1 0 017.5 2.5c0 5.2-7.5 9.9-7.5 9.9z" fill="currentColor"/></svg>,
  close: (p) => <svg width="22" height="22" viewBox="0 0 22 22" fill="none" {...p}><path d="M5 5l12 12M17 5L5 17" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round"/></svg>,
  arrow: (p) => <svg width="16" height="16" viewBox="0 0 18 18" fill="none" {...p}><path d="M2 9h13M10 4l5 5-5 5" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round" strokeLinejoin="round"/></svg>,
  star: (p) => <svg width="13" height="13" viewBox="0 0 24 24" {...p}><path d="M12 2l2.9 6.3 6.9.7-5.1 4.6 1.4 6.8L12 17.8 5.9 20.4l1.4-6.8L2.2 9l6.9-.7L12 2z" fill="currentColor"/></svg>,
  plus: (p) => <svg width="16" height="16" viewBox="0 0 18 18" fill="none" {...p}><path d="M9 3v12M3 9h12" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round"/></svg>,
  minus: (p) => <svg width="16" height="16" viewBox="0 0 18 18" fill="none" {...p}><path d="M3 9h12" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round"/></svg>,
  chevron: (p) => <svg width="16" height="16" viewBox="0 0 18 18" fill="none" {...p}><path d="M6 3l6 6-6 6" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round" strokeLinejoin="round"/></svg>,
  sliders: (p) => <svg width="18" height="18" viewBox="0 0 20 20" fill="none" {...p}><path d="M3 6h10M16 6h1M3 14h1M7 14h10" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round"/><circle cx="14" cy="6" r="2" stroke="currentColor" strokeWidth="1.3"/><circle cx="5" cy="14" r="2" stroke="currentColor" strokeWidth="1.3"/></svg>,
  globe: (p) => <svg width="18" height="18" viewBox="0 0 20 20" fill="none" {...p}><circle cx="10" cy="10" r="7.3" stroke="currentColor" strokeWidth="1.2"/><path d="M10 2.7c2.4 2 2.4 12.6 0 14.6M10 2.7c-2.4 2-2.4 12.6 0 14.6M3 7.5h14M3 12.5h14" stroke="currentColor" strokeWidth="1.2"/></svg>,
  check: (p) => <svg width="14" height="14" viewBox="0 0 18 18" fill="none" {...p}><path d="M3.5 9.5l3.5 3.5L14.5 5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>,
  lock: (p) => <svg width="14" height="14" viewBox="0 0 18 18" fill="none" {...p}><rect x="3.5" y="8" width="11" height="7.5" rx="1.4" stroke="currentColor" strokeWidth="1.3"/><path d="M6 8V5.6a3 3 0 016 0V8" stroke="currentColor" strokeWidth="1.3"/></svg>,
};

/* ---------- Gold filigree ornament ---------- */
function Ornament() {
  return (
    <div className="orn">
      <span></span>
      <svg width="34" height="14" viewBox="0 0 34 14" fill="none">
        <path d="M17 1c2.6 0 4 2.2 4 4s-1.7 4-4 4-4-1.7-4-4 1.4-4 4-4z" stroke="currentColor" strokeWidth="1"/>
        <path d="M13 5H1M21 5h12M5 5l-2 2M5 5l-2-2M29 5l2 2M29 5l2-2" stroke="currentColor" strokeWidth="1"/>
        <circle cx="17" cy="5" r="1.4" fill="currentColor"/>
      </svg>
      <span></span>
    </div>
  );
}

/* ---------- CSS flacon (perfume bottle art-direction) ---------- */
function Flacon({ p, scale = 1, showLabel = true }) {
  return (
    <div className="flacon" style={{ transform: `scale(${scale})`, '--amber-top': p.top, '--amber-bot': p.bot }}>
      <div className="cap"></div>
      <div className="collar"></div>
      <div className="glass">
        {showLabel && (
          <div className="label">
            <div className="fa">عنبر</div>
            <div className="en">{p.name}</div>
            <div className="ln"></div>
          </div>
        )}
      </div>
    </div>
  );
}

/* ---------- Loading / error states (Phase 2 — Supabase reads are async,
   the old mock data never needed either of these) ---------- */
function LoadingState({ lang }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'center', padding: '70px 24px' }}>
      <span style={{ fontFamily: 'var(--sans)', fontSize: 11, letterSpacing: '.2em', textTransform: 'uppercase', color: 'var(--ink-soft)' }}>
        {lang === 'ar' ? 'جارٍ التحميل…' : 'Loading…'}
      </span>
    </div>
  );
}

function ErrorState({ lang, onRetry }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 16, padding: '70px 24px', textAlign: 'center' }}>
      <p className="body">{lang === 'ar' ? 'تعذّر تحميل العطور. يرجى المحاولة مرة أخرى.' : 'Couldn’t load fragrances. Please try again.'}</p>
      {onRetry && <button className="btn btn-fill" onClick={onRetry}>{lang === 'ar' ? 'إعادة المحاولة' : 'Retry'}</button>}
    </div>
  );
}

/* ---------- Stars ---------- */
function Stars({ r = 5, c = 'var(--gold-deep-on-light)' }) {
  return <span style={{ display: 'inline-flex', gap: 2, color: c }}>{[1,2,3,4,5].map(i => <Icon.star key={i} style={{ opacity: i <= r ? 1 : .25 }} />)}</span>;
}

/* ---------- Scroll reveal hook ---------- */
function Reveal({ children, delay = 0, className = '', as = 'div', ...rest }) {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current; if (!el) return;
    const io = new IntersectionObserver((es) => {
      es.forEach(e => { if (e.isIntersecting) { setTimeout(() => el.classList.add('in'), delay); io.unobserve(el); } });
    }, { threshold: 0.14, root: el.closest('.screen') });
    io.observe(el);
    return () => io.disconnect();
  }, [delay]);
  const Tag = as;
  return <Tag ref={ref} className={`rv ${className}`} {...rest}>{children}</Tag>;
}

/* ---------- Product card ---------- */
function ProductCard({ p, lang, t, onOpen, wished, onWish, style }) {
  const badgeMap = {
    signature: [t.featuredK, false], bestseller: ['Best Seller', false],
    new: ['New', false], limited: ['Limited', true],
  };
  const badgeArMap = { signature: 'مميّز', bestseller: 'الأكثر مبيعاً', new: 'جديد', limited: 'محدود' };
  const badge = p.badge ? badgeMap[p.badge] : null;
  return (
    <div
      className="pcard" style={style} onClick={() => onOpen(p)}
      role="button" tabIndex={0} aria-label={lang === 'ar' ? p.ar : p.name}
      onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); onOpen(p); } }}
    >
      <div className="img" style={p.cardBg ? { background: p.cardBg } : undefined}>
        {p.badge && <span className={`tag ${badge && badge[1] ? 'gold' : ''}`}>{lang === 'ar' ? badgeArMap[p.badge] : badge[0]}</span>}
        <button
          className="wish" onClick={(e) => { e.stopPropagation(); onWish(p.id); }}
          aria-label={wished ? (lang === 'ar' ? 'إزالة من المفضّلة' : 'Remove from wishlist') : (lang === 'ar' ? 'إضافة إلى المفضّلة' : 'Add to wishlist')}
          aria-pressed={wished}
          style={{ color: wished ? 'var(--burgundy)' : 'var(--ink)' }}
        >
          {wished ? <Icon.heartFill /> : <Icon.heart />}
        </button>
        <Flacon p={p} />
      </div>
      <div className="meta">
        <div className="nm">{lang === 'ar' ? p.ar : p.name}</div>
        <div className="fa">{lang === 'ar' ? p.name : p.ar}</div>
        <div className="sub">{lang === 'ar' ? p.familyAr : p.family}</div>
        <div className="pr">{t.currency} {p.price}</div>
      </div>
    </div>
  );
}

/* ---------- Brand wordmark (typeset) ---------- */
function Wordmark({ tagline, small }) {
  return (
    <div className="brand" style={{ fontSize: small ? 14 : 16 }}>
      <span>Amber & Zafran</span>
      {tagline && <small>Luxury Scents</small>}
    </div>
  );
}

/* ---------- Footer ---------- */
function Footer({ t, lang, go }) {
  // Each item is [label, view-name-to-navigate-to]. Boutique/Collections/
  // Gifting/VIP/Our Story all have real dedicated pages. "Journal" and
  // "Boutiques" have no dedicated page yet, so they route to the closest
  // real equivalent (Our Story, and the Boutique itself) rather than being
  // dead links — same "no fake destinations" principle as the rest of the
  // app. "The Circle of Amber" (loyalty) lives on the Homepage, so it goes home.
  const col = (title, items) => (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      <div style={{ fontFamily: 'var(--sans)', fontSize: 10, letterSpacing: '.28em', textTransform: 'uppercase', color: 'var(--gold)' }}>{title}</div>
      {items.map(([label, target], i) => (
        <button key={i} onClick={() => go(target)} style={{ fontFamily: lang === 'ar' ? 'var(--arabic)' : 'var(--serif)', fontSize: 15, color: 'rgba(253,253,253,.78)', textAlign: lang === 'ar' ? 'right' : 'left' }}>{label}</button>
      ))}
    </div>
  );
  return (
    <footer style={{ background: 'var(--black)', color: 'var(--white)', padding: '60px 24px 40px' }}>
      <div style={{ textAlign: 'center', marginBottom: 40 }}>
        <img src="assets/mark-gold.png" alt="" style={{ width: 84, margin: '0 auto', opacity: .95 }} />
        <div style={{ fontFamily: lang === 'ar' ? 'var(--arabic-display)' : 'var(--serif)', fontSize: 24, letterSpacing: lang === 'ar' ? 0 : '.18em', marginTop: 14 }}>
          {lang === 'ar' ? 'عنبر وزعفران' : 'AMBER & ZAFRAN'}
        </div>
        <div style={{ fontFamily: lang === 'ar' ? 'var(--arabic)' : 'var(--serif-it)', fontStyle: lang === 'ar' ? 'normal' : 'italic', fontSize: 14, color: 'var(--rose)', marginTop: 8 }}>{t.tagline}</div>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 36, marginBottom: 44 }}>
        {col(t.footShop, [
          [t.nav.shop, 'shop'],
          [t.nav.collections, 'collections'],
          [t.nav.gifting, 'gifting'],
        ])}
        {col(t.footHouse, [
          [t.nav.story, 'story'],
          [lang === 'ar' ? 'المجلة' : 'Journal', 'story'],
          [t.loyaltyT, 'home'],
          [lang === 'ar' ? 'المتاجر' : 'Boutiques', 'shop'],
        ])}
      </div>
      <div className="rule" style={{ background: 'rgba(255,255,255,.12)' }}></div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 26, fontFamily: 'var(--sans)', fontSize: 10, letterSpacing: '.14em', color: 'rgba(253,253,253,.5)', textTransform: 'uppercase' }}>
        <span>© 2026 Amber & Zafran</span>
        <span>Amman · Jordan</span>
      </div>
    </footer>
  );
}

Object.assign(window, { Icon, Ornament, Flacon, Stars, Reveal, ProductCard, Wordmark, Footer });
