/* ============================================================
   Chrome: Header, Footer, ProductCard, Newsletter, sub-components
   ============================================================ */
const NAV_LINKS = [
  { label: 'Shop All',    page: 'shop' },
  { label: 'Track Order', page: 'account' },
  { label: 'About',       page: 'about' },
  { label: 'Contact',     page: 'contact' },
];

/* ---------- Currency switch ---------- */
function CurrencySwitch({ compact }) {
  const { currency, setCurrency } = useStore();
  const C = BB.BRAND.currency;
  return (
    <div style={{ display: 'inline-flex', alignItems: 'center', gap: 2, border: '1px solid var(--line)', borderRadius: 100, padding: 3, background: 'var(--ivory)' }}>
      {[C.secondary, C.primary].map((cur) =>
      <button key={cur.code} className="cur-opt" onClick={() => setCurrency(cur.code)}
      style={{ fontSize: 11, fontWeight: 600, letterSpacing: '.08em', whiteSpace: 'nowrap', padding: compact ? '6px 11px' : '7px 13px', borderRadius: 100, transition: 'all .3s',
        background: currency === cur.code ? 'var(--ink)' : 'transparent', color: currency === cur.code ? 'var(--cream)' : 'var(--ink-soft)' }}>
          {cur.symbol} {cur.code}
        </button>
      )}
    </div>);
}

/* ---------- Text wordmark (config-driven logo) ---------- */
function Wordmark({ size = 26, onDark = false }) {
  const B = BB.BRAND;
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: Math.round(size * .3), whiteSpace: 'nowrap' }}>
      <span aria-hidden="true" style={{ width: Math.round(size * .92), height: Math.round(size * .92), borderRadius: Math.round(size * .2), background: 'var(--gold)', display: 'inline-grid', placeItems: 'center', color: '#fff', fontFamily: 'var(--serif)', fontSize: Math.round(size * .58), fontWeight: 700, flexShrink: 0 }}>T</span>
      <span style={{ fontFamily: 'var(--serif)', fontWeight: 700, fontSize: size, lineHeight: 1, letterSpacing: '-.02em', color: onDark ? '#fff' : 'var(--ink)' }}>
        {B.logoLead}<em style={{ fontStyle: 'normal', color: onDark ? 'var(--gold-soft)' : 'var(--gold-deep)' }}>{B.logoAccent}</em>
      </span>
    </span>);
}

/* ---------- Header — always light, sticky ---------- */
function Header() {
  const { nav, cartCount, setDrawer, user } = useStore();
  const [scrolled, setScrolled] = useState(false);
  const [mobile, setMobile] = useState(false);
  const [searchOpen, setSearchOpen] = useState(false);

  useEffect(() => {
    const f = () => setScrolled(window.scrollY > 28);
    f(); window.addEventListener('scroll', f); return () => window.removeEventListener('scroll', f);
  }, []);

  return (
    <>
      <div className="announce" style={{ background: 'var(--ink)', color: 'var(--gold-soft)', textAlign: 'center', fontSize: 12, letterSpacing: '.14em', textTransform: 'uppercase', padding: '9px 16px', fontWeight: 600 }}>
        Free delivery on orders over {BB.fmt(BB.BRAND.shipping.freeThreshold, BB.BRAND.currency.primary.code)} · Nationwide
      </div>

      <header style={{
        position: 'sticky', top: 0, left: 0, right: 0, zIndex: 100,
        background: scrolled ? 'rgba(250,246,238,.94)' : 'var(--cream)',
        backdropFilter: 'blur(18px)', WebkitBackdropFilter: 'blur(18px)',
        borderBottom: '1px solid var(--line)',
        transition: 'all .45s ease',
      }}>
        <div className="container wide" style={{ display: 'grid', gridTemplateColumns: '1fr auto 1fr', alignItems: 'center', height: scrolled ? 66 : 82, transition: 'height .4s', gap: 16 }}>
          {/* left nav (desktop) */}
          <nav className="hide-mob" style={{ display: 'flex', gap: 26 }}>
            {NAV_LINKS.map((l) =>
            <button key={l.label} className="link-u" onClick={() => nav(l.page, l.params || {})}
            style={{ fontSize: 12.5, letterSpacing: '.1em', textTransform: 'uppercase', fontWeight: 500, color: 'var(--ink)' }}>{l.label}</button>
            )}
          </nav>
          {/* mobile menu btn */}
          <button className="show-mob icobtn" onClick={() => setMobile(true)} aria-label="Menu" style={{ justifySelf: 'start', marginLeft: -10, color: 'var(--ink)' }}><I.menu width={24} height={24} /></button>

          {/* logo */}
          <button onClick={() => nav('home')} style={{ textAlign: 'center', lineHeight: 1, flexShrink: 0, padding: '0 10px', minHeight: 44, display: 'inline-flex', alignItems: 'center' }}>
            <Wordmark size={scrolled ? 24 : 27} />
          </button>

          {/* right actions */}
          <div style={{ display: 'flex', gap: 16, alignItems: 'center', flex: 1, justifyContent: 'flex-end', color: 'var(--ink)' }}>
            <div className="hide-mob"><CurrencySwitch /></div>
            <button className="icobtn" onClick={() => setSearchOpen(true)} aria-label="Search" style={{ color: 'var(--ink)' }}><I.search width={21} height={21} /></button>
            {user ? (
              <button className="hide-mob" onClick={() => nav('account')} aria-label="My account"
                style={{ width: 34, height: 34, borderRadius: '50%', background: 'var(--gold)', display: 'grid', placeItems: 'center', color: '#fff', fontFamily: 'var(--serif)', fontSize: 14, fontWeight: 700, border: 'none', cursor: 'pointer', flexShrink: 0, transition: 'transform .25s' }}
                onMouseEnter={e => e.currentTarget.style.transform='scale(1.08)'}
                onMouseLeave={e => e.currentTarget.style.transform='scale(1)'}>
                {(user.firstName || user.name || 'U')[0].toUpperCase()}
              </button>
            ) : (
              <button className="hide-mob" onClick={() => nav('auth', { mode: 'signin' })} aria-label="Sign in"
                style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 11, letterSpacing: '.1em', textTransform: 'uppercase', fontWeight: 600, color: 'var(--ink)', background: 'none', border: 'none', cursor: 'pointer', transition: 'opacity .2s' }}
                onMouseEnter={e => e.currentTarget.style.opacity='.7'}
                onMouseLeave={e => e.currentTarget.style.opacity='1'}>
                <I.user width={20} height={20} />
                Sign in
              </button>
            )}
            <button className="icobtn" onClick={() => setDrawer(true)} aria-label="Cart" style={{ position: 'relative', color: 'var(--ink)' }}>
              <I.bag width={22} height={22} />
              {cartCount > 0 && <span style={{ position: 'absolute', top: 1, right: 1, background: 'var(--gold)', color: '#fff', fontSize: 10, fontWeight: 700, minWidth: 17, height: 17, borderRadius: 100, display: 'grid', placeItems: 'center', padding: '0 4px' }}>{cartCount}</span>}
            </button>
          </div>
        </div>
      </header>

      {searchOpen && <SearchOverlay onClose={() => setSearchOpen(false)} />}
      <MobileNav open={mobile} onClose={() => setMobile(false)} />
    </>);
}

/* ---------- Mobile nav ---------- */
function MobileNav({ open, onClose }) {
  const { nav, user } = useStore();
  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 160, pointerEvents: open ? 'auto' : 'none' }}>
      <div onClick={onClose} style={{ position: 'absolute', inset: 0, background: 'rgba(33,26,17,.4)', opacity: open ? 1 : 0, transition: 'opacity .4s' }} />
      <aside style={{ position: 'absolute', top: 0, left: 0, height: '100%', width: 'min(340px, 86vw)', background: 'var(--cream)', padding: '28px', transform: open ? 'none' : 'translateX(-100%)', transition: 'transform .5s cubic-bezier(.2,.8,.2,1)', display: 'flex', flexDirection: 'column' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 30 }}>
          <Wordmark size={24} />
          <button className="icobtn" onClick={onClose} aria-label="Close" style={{ marginRight: -10 }}><I.close width={24} height={24} /></button>
        </div>
        <nav style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
          {NAV_LINKS.map((l) =>
          <button key={l.label} onClick={() => {nav(l.page, l.params || {});onClose();}}
          style={{ fontFamily: 'var(--serif)', fontWeight: 600, fontSize: 28, textAlign: 'left', padding: '8px 0', color: 'var(--ink)' }}>{l.label}</button>
          )}
          {user
            ? <button onClick={() => {nav('account');onClose();}} style={{ fontFamily: 'var(--serif)', fontWeight: 600, fontSize: 28, textAlign: 'left', padding: '8px 0', color: 'var(--ink)' }}>Account</button>
            : <button onClick={() => {nav('auth',{mode:'signin'});onClose();}} style={{ fontFamily: 'var(--serif)', fontWeight: 600, fontSize: 28, textAlign: 'left', padding: '8px 0', color: 'var(--ink)' }}>Sign in</button>
          }
        </nav>
        <div style={{ marginTop: 24 }}>
          <p className="eyebrow" style={{ marginBottom: 12 }}>Categories</p>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
            {BB.navCategories.map(c => <button key={c.id} className="chip" onClick={() => {nav('shop', { cat: c.id });onClose();}}>{c.short}</button>)}
          </div>
        </div>
        <div style={{ marginTop: 'auto' }}><CurrencySwitch /></div>
      </aside>
    </div>);
}

/* ---------- Search overlay ---------- */
function SearchOverlay({ onClose }) {
  const { nav } = useStore();
  const [q, setQ] = useState('');
  const ref = useRef();
  useEffect(() => {ref.current && ref.current.focus();}, []);
  const match = (p) => (p.name + ' ' + p.short + ' ' + Object.values(p.specs || {}).join(' ')).toLowerCase().includes(q.toLowerCase());
  const results = q.trim() ? BB.products.filter(match).slice(0, 6) : [];
  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 170, background: 'rgba(250,246,238,.98)', backdropFilter: 'blur(8px)', animation: 'fade .3s', padding: 'var(--gutter)', overflowY: 'auto' }}>
      <div className="container" style={{ maxWidth: 760 }}>
        <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: 24 }}><button className="icobtn" onClick={onClose} aria-label="Close"><I.close width={28} height={28} /></button></div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, borderBottom: '2px solid var(--ink)', paddingBottom: 14 }}>
          <I.search width={28} height={28} />
          <input ref={ref} value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search rice, serum, laptop, Mustang…"
          style={{ flex: 1, border: 'none', background: 'transparent', fontFamily: 'var(--serif)', fontWeight: 600, fontSize: 'clamp(24px,4vw,40px)', outline: 'none', color: 'var(--ink)' }} />
        </div>
        <div style={{ marginTop: 22, display: 'flex', flexDirection: 'column', gap: 4 }}>
          {results.map((p) => {
            const c = BB.catOf(p);
            return (
            <button key={p.id} onClick={() => {nav('product', { id: p.id });onClose();}} style={{ display: 'flex', alignItems: 'center', gap: 16, padding: '12px', borderRadius: 'var(--r-md)', textAlign: 'left', transition: 'background .2s' }} onMouseEnter={(e) => e.currentTarget.style.background = 'var(--cream-deep)'} onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}>
              <Ph src={p.img} label="" variant={p.ph} style={{ width: 58, height: 58, borderRadius: 'var(--r-sm)', flexShrink: 0 }} />
              <div style={{ minWidth: 0 }}>
                <span className="cat-tag">{c ? c.short : ''}</span>
                <div style={{ fontFamily: 'var(--serif)', fontWeight: 600, fontSize: 19, lineHeight: 1.2 }}>{p.name}</div>
                <div style={{ fontSize: 13, color: 'var(--ink-soft)' }}>{BB.specLine(p)}</div>
              </div>
            </button>);
          })}
          {q.trim() && results.length === 0 && <p className="muted" style={{ padding: 12 }}>No matches — try “rice”, “serum”, “laptop” or “Mustang”.</p>}
          {!q.trim() && (
            <div style={{ padding: 12 }}>
              <p className="eyebrow" style={{ marginBottom: 12 }}>Browse categories</p>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                {BB.navCategories.map(c => <button key={c.id} className="chip" onClick={() => {nav('shop', { cat: c.id });onClose();}}>{c.name}</button>)}
              </div>
            </div>
          )}
        </div>
      </div>
    </div>);
}

/* ---------- Product card — category-aware ---------- */
function ProductCard({ p, delay }) {
  const { nav, addToCart, money, wish, toggleWish } = useStore();
  const [hover, setHover] = useState(false);
  const liked = wish.includes(p.id);
  const tag = p.tags && p.tags[0];
  const c = BB.catOf(p);
  const isVehicle = p.cat === 'vehicles';
  return (
    <Reveal className="pcard" delay={delay} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}>
      <div style={{ position: 'relative', cursor: 'pointer' }} onClick={() => nav('product', { id: p.id })}>
        <Ph src={p.img} label={p.name} variant={p.ph} style={{ aspectRatio: '1/1', borderRadius: 'var(--r-md)', transition: 'transform .6s cubic-bezier(.2,.8,.2,1)', transform: hover ? 'scale(1.02)' : 'none' }} />
        {tag && <span className={`badge badge-${tag}`} style={{ position: 'absolute', top: 12, left: 12 }}>{tag === 'best' ? 'Bestseller' : 'New'}</span>}
        <button className="qbtn" onClick={(e) => {e.stopPropagation();toggleWish(p.id);}} aria-label="Save for later"
        style={{ position: 'absolute', top: 8, right: 8, background: 'rgba(255,255,255,.88)', backdropFilter: 'blur(4px)', color: liked ? 'var(--blush)' : 'var(--ink)' }}>
          <I.heart width={18} height={18} style={{ fill: liked ? 'var(--blush)' : 'none' }} />
        </button>
        <div style={{ position: 'absolute', left: 12, right: 12, bottom: 12, transform: hover ? 'translateY(0)' : 'translateY(8px)', opacity: hover ? 1 : 0, transition: 'all .35s' }}>
          <button className="btn btn-primary btn-block btn-sm" onClick={(e) => {e.stopPropagation(); isVehicle ? nav('product', { id: p.id }) : addToCart(p);}}>{isVehicle ? 'View listing' : 'Quick add'}</button>
        </div>
      </div>
      <div style={{ paddingTop: 13 }}>
        <span className="cat-tag">{c ? c.short : ''}</span>
        <h4 onClick={() => nav('product', { id: p.id })} style={{ fontSize: 18.5, cursor: 'pointer', lineHeight: 1.15, marginTop: 4 }}>{p.name}</h4>
        <p style={{ fontSize: 13, color: 'var(--ink-soft)', marginTop: 5, lineHeight: 1.45 }}>{BB.specLine(p)}</p>
        <div style={{ fontWeight: 600, fontSize: 15.5, marginTop: 7 }}>{money(p.price)}</div>
      </div>
    </Reveal>);
}

/* ---------- Newsletter ---------- */
function Newsletter() {
  const { toast } = useStore();
  const [email, setEmail] = useState('');
  const [done, setDone] = useState(false);
  const submit = (e) => {e.preventDefault();if (!email.includes('@')) return;setDone(true);toast('You\u2019re on the list', 'check');};
  return (
    <section style={{ background: 'var(--cream-deep)', color: 'var(--ink)', borderTop: '1px solid var(--line)' }}>
      <div className="container" style={{ padding: 'clamp(56px,8vw,96px) var(--gutter)', textAlign: 'center', maxWidth: 720 }}>
        <h2 style={{ fontSize: 'clamp(30px,4.5vw,48px)', marginBottom: 28, color: 'var(--ink)' }}>Restocks &amp; new arrivals</h2>
        {done ?
        <p style={{ fontFamily: 'var(--serif)', fontWeight: 600, fontSize: 24, color: 'var(--gold-deep)' }}>Thank you — you're on the list.</p> :
        <form onSubmit={submit} style={{ display: 'flex', gap: 10, maxWidth: 480, margin: '0 auto', flexWrap: 'wrap' }}>
            <input value={email} onChange={(e) => setEmail(e.target.value)} type="email" placeholder="Your email address" required
          style={{ flex: 1, minWidth: 220, padding: '16px 20px', borderRadius: 'var(--r-md)', border: '1.5px solid var(--line)', background: 'var(--ivory)', color: 'var(--ink)' }} />
            <button className="btn btn-gold" type="submit">Subscribe</button>
          </form>
        }
      </div>
    </section>);
}

/* ---------- Footer ---------- */
function Footer() {
  const { nav } = useStore();
  const B = BB.BRAND;
  const col = (title, links) =>
  <div>
      <h5 className="eyebrow" style={{ marginBottom: 16, color: 'var(--ink-soft)' }}>{title}</h5>
      <ul style={{ listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 10 }}>
        {links.map(([l, page, params]) => <li key={l}><button className="link-u" style={{ fontSize: 14.5, color: 'var(--ink)', textAlign: 'left' }} onClick={() => nav(page, params || {})}>{l}</button></li>)}
      </ul>
    </div>;

  return (
    <footer style={{ background: 'var(--cream-deep)', borderTop: '1px solid var(--line)' }}>
      <div className="container wide footer-grid" style={{ padding: 'clamp(56px,7vw,88px) var(--gutter) 40px' }}>
        <div style={{ maxWidth: 340 }}>
          <Wordmark size={26} />
          <p style={{ fontSize: 14.5, color: 'var(--ink-soft)', marginTop: 14, lineHeight: 1.6 }}>{B.blurb}</p>
          <div style={{ display: 'flex', gap: 14, marginTop: 20, flexWrap: 'wrap' }}>
            <a href={B.whatsapp} target="_blank" rel="noopener" style={{ display: 'inline-flex', alignItems: 'center', gap: 7, fontSize: 13, fontWeight: 600, color: 'var(--ink-soft)' }}><I.wa width={16} height={16} /> WhatsApp</a>
            <a href={B.instagram} target="_blank" rel="noopener" style={{ display: 'inline-flex', alignItems: 'center', gap: 7, fontSize: 13, fontWeight: 600, color: 'var(--ink-soft)' }}><I.ig width={16} height={16} /> {B.social}</a>
          </div>
        </div>
        {col('Shop', [['All products', 'shop'], ...BB.navCategories.map(c => [c.name, 'shop', { cat: c.id }])])}
        {col('Support', [['Track my order', 'account'], ['Shipping & Delivery', 'policy', { id: 'shipping' }], ['Returns & Refunds', 'policy', { id: 'returns' }], ['Payments & Pricing', 'policy', { id: 'payments' }], ['Contact us', 'contact']])}
        {col('Company', [['About us', 'about'], ['My Account', 'account'], ['Privacy', 'policy', { id: 'privacy' }]])}
      </div>
      <div className="container wide" style={{ display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: 12, padding: '22px var(--gutter)', borderTop: '1px solid var(--line)', fontSize: 12.5, color: 'var(--ink-faint)' }}>
        <span>© {new Date().getFullYear()} {B.name} · All rights reserved</span>
        <span>Powered by <a href="https://thecollectivesynergy.com" target="_blank" rel="noopener" style={{ color: 'var(--ink-soft)', fontWeight: 600 }}>The Collective Synergy</a></span>
        <span style={{ display: 'flex', gap: 8, alignItems: 'center' }}><I.shield width={15} height={15} /> Secure checkout · {B.currency.secondary.code} &amp; {B.currency.primary.code}</span>
      </div>
    </footer>);
}

Object.assign(window, { Header, Footer, ProductCard, Newsletter, CurrencySwitch, Wordmark, NAV_LINKS });
