/* ============================================================
   Chrome: Header, Footer, ProductCard, Newsletter, sub-components
   ============================================================ */
const NAV_LINKS = [
{ label: 'Categories',   page: 'shop' },
{ label: 'Packages',     page: 'packages' },
{ label: 'Custom Order', page: 'custom-order' },
{ label: 'Our Story',    page: 'about' },
{ label: 'Contact',      page: 'contact' }];


/* ---------- Currency switch ---------- */
function CurrencySwitch({ compact, transparent }) {
  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.primary, C.secondary].map((cur) =>
      <button key={cur.code} 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>);

}

/* ---------- Wordmark (HePortal) ---------- */
function Wordmark({ size = 30, onDark = false }) {
  const inkCol = onDark ? '#fff' : 'var(--ink)';
  return (
    <span style={{ display: 'inline-flex', alignItems: 'baseline', gap: 0, whiteSpace: 'nowrap', lineHeight: 1 }}>
      <span style={{ fontFamily: 'var(--sans)', fontWeight: 300, fontSize: size * 0.58, letterSpacing: '.22em', textTransform: 'uppercase', color: onDark ? 'rgba(255,255,255,.55)' : 'var(--ink-faint)', marginRight: size * 0.1, alignSelf: 'center' }}>✿</span>
      <span style={{ fontFamily: 'var(--serif)', fontWeight: 400, fontSize: size, letterSpacing: '-.01em', color: inkCol, lineHeight: 1 }}>He</span>
      <em style={{ fontFamily: 'var(--serif)', fontStyle: 'italic', fontWeight: 500, fontSize: size, letterSpacing: '-.02em', lineHeight: 1, color: onDark ? '#fff' : 'var(--gold)' }}>Portal</em>
    </span>
  );
}

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

  const isHome = route.page === 'home';
  // On the homepage hero, start transition once user scrolls past 80px
  useEffect(() => {
    const threshold = isHome ? 80 : 28;
    const f = () => setScrolled(window.scrollY > threshold);
    f(); window.addEventListener('scroll', f); return () => window.removeEventListener('scroll', f);
  }, [isHome]);

  // transparent = floating over full-bleed video hero
  const transparent = isHome && !scrolled;
  // white icons when: floating over hero OR scrolled into dark frosted header
  const onDark    = transparent || scrolled;
  const iconColor = onDark ? 'rgba(255,255,255,.90)' : 'var(--ink)';

  return (
    <>
      {/* Announcement bar — hidden on homepage (header floats over video) */}
      {!isHome && (
        <div style={{ background: 'var(--ink)', color: 'var(--cream)', textAlign: 'center', fontSize: 12, letterSpacing: '.16em', textTransform: 'uppercase', padding: '9px 16px', fontWeight: 500 }}>
          Premium quality artificial florals · Lagos &amp; nationwide delivery · WhatsApp +234 703 577 5479
        </div>
      )}

      <header style={{
        position: isHome ? 'fixed' : 'sticky',
        top: 0, left: 0, right: 0,
        zIndex: 100,
        background: transparent ? 'transparent' : scrolled ? 'rgba(42,17,51,.92)' : 'var(--cream)',
        backdropFilter: transparent ? 'none' : 'blur(18px)',
        WebkitBackdropFilter: transparent ? 'none' : 'blur(18px)',
        borderBottom: '1px solid ' + (transparent ? 'transparent' : scrolled ? 'rgba(255,255,255,.10)' : 'var(--line)'),
        transition: 'all .45s ease',
      }}>
        <div className="container wide" style={{ display: 'grid', gridTemplateColumns: '1fr auto 1fr', alignItems: 'center', height: scrolled ? 72 : 88, 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: 13, letterSpacing: '.12em', textTransform: 'uppercase', fontWeight: 400, color: iconColor, transition: 'color .45s' }}>{l.label}</button>
            )}
          </nav>
          {/* mobile menu btn */}
          <button className="show-mob" onClick={() => setMobile(true)} aria-label="Menu" style={{ flex: 1, textAlign: 'left', color: iconColor, transition: 'color .45s' }}><I.menu width={24} height={24} /></button>

          {/* logo */}
          <button onClick={() => nav('home')} style={{ textAlign: 'center', lineHeight: 1, flexShrink: 0, padding: '0 10px' }}>
            <Wordmark size={scrolled ? 28 : 34} onDark={onDark} />
          </button>

          {/* right actions */}
          <div style={{ display: 'flex', gap: 16, alignItems: 'center', flex: 1, justifyContent: 'flex-end', color: iconColor, transition: 'color .45s' }}>
            <div className="hide-mob"><CurrencySwitch transparent={transparent} /></div>
            <button onClick={() => setSearchOpen(true)} aria-label="Search" style={{ color: iconColor }}><I.search width={21} height={21} /></button>
            <button className="hide-mob" onClick={() => nav(user ? 'account' : 'signin')} aria-label="Account" style={{ color: iconColor, position: 'relative' }}>
              {user
                ? <span style={{ width: 30, height: 30, borderRadius: '50%', background: 'linear-gradient(135deg,var(--gold-deep),var(--blush))', display: 'grid', placeItems: 'center', color: '#fff', fontFamily: 'var(--serif)', fontSize: 14, fontWeight: 500 }}>{user.firstName[0]}{user.lastName[0]}</span>
                : <I.user width={21} height={21} />}
            </button>
            <button onClick={() => setDrawer(true)} aria-label="Bag" style={{ position: 'relative', color: iconColor }}>
              <I.bag width={22} height={22} />
              {cartCount > 0 && <span style={{ position: 'absolute', top: -7, right: -8, background: 'var(--blush-deep)', color: '#fff', fontSize: 10, fontWeight: 600, 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(42,17,51,.38)', 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: 36 }}>
          <Wordmark size={28} />
          <button onClick={onClose} aria-label="Close"><I.close width={24} height={24} /></button>
        </div>
        <nav style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
          {NAV_LINKS.map((l) =>
          <button key={l.label} onClick={() => {nav(l.page, l.params || {});onClose();}}
          style={{ fontFamily: 'var(--serif)', fontSize: 30, textAlign: 'left', padding: '8px 0', color: 'var(--ink)' }}>{l.label}</button>
          )}
          <button onClick={() => {nav(user ? 'account' : 'signin');onClose();}} style={{ fontFamily: 'var(--serif)', fontSize: 30, textAlign: 'left', padding: '8px 0' }}>{user ? `Hi, ${user.firstName}` : 'Sign in'}</button>
          <button onClick={() => {nav('booking');onClose();}} style={{ fontFamily: 'var(--serif)', fontSize: 30, textAlign: 'left', padding: '8px 0' }}>Book a call</button>
        </nav>
        <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 results = q.trim() ? BB.products.filter((p) => (p.name + ' ' + p.short).toLowerCase().includes(q.toLowerCase())).slice(0, 6) : [];
  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 170, background: 'rgba(251,247,252,.98)', backdropFilter: 'blur(8px)', animation: 'fade .3s', padding: 'var(--gutter)' }}>
      <div className="container" style={{ maxWidth: 760 }}>
        <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: 24 }}><button 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 for cookies, garlands, journals…"
          style={{ flex: 1, border: 'none', background: 'transparent', fontFamily: 'var(--serif)', fontSize: 'clamp(24px,4vw,40px)', outline: 'none', color: 'var(--ink)' }} />
        </div>
        <div style={{ marginTop: 22, display: 'flex', flexDirection: 'column', gap: 4 }}>
          {results.map((p) =>
          <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: 54, height: 64, borderRadius: 'var(--r-sm)' }} />
              <div><div style={{ fontFamily: 'var(--serif)', fontSize: 21 }}>{p.name}</div><div style={{ fontSize: 13, color: 'var(--ink-soft)' }}>{p.short}</div></div>
            </button>
          )}
          {q.trim() && results.length === 0 && <p className="muted" style={{ padding: 12 }}>No matches — try “bundle”, “cookie” or “balloon”.</p>}
          {!q.trim() && <p className="eyebrow" style={{ padding: '12px' }}>Popular · Bundles · Cookies · Balloon Garland · Journals</p>}
        </div>
      </div>
    </div>);

}

/* ---------- Product card ---------- */
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];
  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: '4/5', borderRadius: 'var(--r-md)', transition: 'transform .6s cubic-bezier(.2,.8,.2,1)', transform: hover ? 'scale(1.03)' : 'none' }} />
        {tag && <span className={`badge badge-${tag}`} style={{ position: 'absolute', top: 12, left: 12 }}>{tag === 'best' ? 'Bestseller' : 'New'}</span>}
        <button onClick={(e) => {e.stopPropagation();toggleWish(p.id);}} aria-label="Wishlist"
        style={{ position: 'absolute', top: 10, right: 10, width: 38, height: 38, borderRadius: 100, background: 'rgba(255,253,255,.85)', backdropFilter: 'blur(4px)', display: 'grid', placeItems: 'center', color: liked ? 'var(--blush-deep)' : 'var(--ink)' }}>
          <I.heart width={18} height={18} style={{ fill: liked ? 'var(--blush-deep)' : '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();addToCart(p);}}>Quick add</button>
        </div>
      </div>
      <div style={{ paddingTop: 14 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', gap: 10, alignItems: 'baseline' }}>
          <h4 onClick={() => nav('product', { id: p.id })} style={{ fontSize: 21, cursor: 'pointer', lineHeight: 1.1 }}>{p.name}</h4>
          <span style={{ fontWeight: 500, whiteSpace: 'nowrap' }}>{money(p.price)}</span>
        </div>
        <p style={{ fontSize: 13.5, color: 'var(--ink-soft)', marginTop: 5, lineHeight: 1.45 }}>{p.short}</p>
      </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('Welcome to the inner circle ✿', 'heart');};
  return (
    <section style={{ background: 'var(--ink)', color: 'var(--cream)' }}>
      <div className="container" style={{ padding: 'clamp(60px,9vw,110px) var(--gutter)', textAlign: 'center', maxWidth: 720 }}>
        <p className="eyebrow" style={{ color: 'var(--gold-soft)' }}>Newsletter</p>
        <h2 style={{ fontSize: 'clamp(32px,5vw,56px)', margin: '14px 0 16px', color: 'var(--cream)' }}>Stay in the <em style={{ fontStyle: 'italic' }}>loop</em></h2>
        <p style={{ color: 'rgba(251,247,252,.78)', fontSize: 16, marginBottom: 30 }}>New collections, custom drops, behind-the-scenes process & inspiration — straight to your inbox.</p>
        {done ?
        <p style={{ fontFamily: 'var(--serif)', fontSize: 26, fontStyle: 'italic', color: 'var(--gold-soft)' }}>Thank you — check your inbox for a little welcome.</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: 100, border: '1px solid rgba(251,247,252,.28)', background: 'rgba(251,247,252,.08)', color: 'var(--cream)' }} />
            <button className="btn btn-gold" type="submit">Subscribe</button>
          </form>
        }
      </div>
    </section>);

}

/* ---------- Footer ---------- */
function Footer() {
  const { nav } = useStore();
  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', whiteSpace: 'nowrap' }} 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={34} />
          <p style={{ fontSize: 14.5, color: 'var(--ink-soft)', marginTop: 14, lineHeight: 1.6 }}>{BB.BRAND.blurb}</p>
          <div style={{ display: 'flex', gap: 12, marginTop: 20 }}>
            <a href="https://www.instagram.com/heportal_nig" target="_blank" rel="noopener noreferrer" aria-label="Instagram" style={{ width: 42, height: 42, borderRadius: 100, display: 'grid', placeItems: 'center', background: 'var(--ivory)', boxShadow: 'inset 0 0 0 1px var(--line)' }}><I.ig width={19} height={19} /></a>
            <a href="#" aria-label="TikTok" style={{ width: 42, height: 42, borderRadius: 100, display: 'grid', placeItems: 'center', background: 'var(--ivory)', boxShadow: 'inset 0 0 0 1px var(--line)' }}><I.tiktok width={17} height={17} /></a>
            <a href="#" aria-label="Pinterest" style={{ width: 42, height: 42, borderRadius: 100, display: 'grid', placeItems: 'center', background: 'var(--ivory)', boxShadow: 'inset 0 0 0 1px var(--line)' }}><I.pin width={19} height={19} /></a>
          </div>
        </div>
        {col('Categories', [['All categories', 'shop'], ['Wedding Florals', 'shop', { cat: 'wedding' }], ['Funeral Tributes', 'shop', { cat: 'funeral' }], ['Event Florals', 'shop', { cat: 'events' }], ['Gift Bouquets', 'shop', { cat: 'gifts' }], ['Groom Accessories', 'shop', { cat: 'groom' }]])}
        {col('Order', [['All packages', 'packages'], ['Boutique', 'packages'], ['Bridal Suite', 'packages'], ['Grand Wedding', 'packages'], ['Bespoke Order', 'custom-order'], ['Book a consultation', 'booking']])}
        {col('Company', [['Our Story', 'about'], ['Services', 'services'], ['Contact', 'contact'], ['My Account', 'account']])}
        {col('Policies', [['Shipping', 'policy', { id: 'shipping' }], ['Privacy', 'policy', { id: 'privacy' }], ['Craft & Care', 'policy', { id: 'care' }]])}
      </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()} {BB.BRAND.name} · All rights reserved</span>
        <span style={{ display: 'flex', gap: 8, alignItems: 'center' }}><I.shield width={15} height={15} /> Secure checkout · {BB.BRAND.currency.primary.code} &amp; {BB.BRAND.currency.secondary.code}</span>
      </div>
    </footer>);

}

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