// Shared UI primitives for Fussy Finds
const { useState, useEffect, useRef, useMemo, useCallback } = React;

const fmtINR = (n) => '₹' + Number(n).toLocaleString('en-IN', { minimumFractionDigits: 0, maximumFractionDigits: 2 });

// Star row (outline + fill)
function Stars({ value = 5, size = 14 }) {
  const full = Math.round(value);
  return (
    <span className="ff-stars" style={{ ['--s']: size + 'px' }}>
      {[1, 2, 3, 4, 5].map(i => (
        <svg key={i} width={size} height={size} viewBox="0 0 24 24" fill={i <= full ? 'var(--ff-ink)' : 'none'} stroke="var(--ff-ink)" strokeWidth="2">
          <path strokeLinejoin="round" strokeLinecap="round" d="M12 2l2.9 6.3 6.9.7-5.2 4.7 1.5 6.8L12 17l-6.1 3.5 1.5-6.8L2.2 9l6.9-.7z" />
        </svg>
      ))}
    </span>
  );
}

// Placeholder product "image" — striped with a mono label
function ProductArt({ product, ratio = '1 / 1', size = 'md' }) {
  const labelMap = { home: 'home', kitchen: 'kitchen', beauty: 'beauty', tech: 'tech', wellness: 'wellness', desk: 'desk' };
  // Use real image if available
  const imgs = Array.isArray(product.images) ? product.images : [];
  const mainImg = imgs.find(u => u && u.trim()) || null;

  if (mainImg) {
    return (
      <div style={{ aspectRatio: ratio, overflow: 'hidden', position: 'relative', background: product.swatch || '#F4F2EE' }}>
        <img
          src={mainImg}
          alt={product.name}
          style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }}
          onError={e => { e.target.style.display = 'none'; e.target.parentNode.style.background = product.swatch || '#FFC7A8'; }}
        />
      </div>
    );
  }

  // Fallback: coloured placeholder with product name
  return (
    <div className="ff-ph" style={{ aspectRatio: ratio, ['--ph-color']: product.swatch }}>
      <div style={{ position: 'absolute', inset: 0, display: 'grid', placeItems: 'center', pointerEvents: 'none' }}>
        <div style={{
          fontFamily: "'Space Grotesk', sans-serif",
          fontWeight: 700,
          fontSize: size === 'lg' ? 72 : size === 'sm' ? 28 : 44,
          color: 'rgba(26,22,20,.75)',
          letterSpacing: '-0.04em',
          textAlign: 'center',
          padding: '0 16px',
          lineHeight: 1,
        }}>
          {product.name.split(' ').map((w, i) => (<div key={i}>{w}</div>))}
        </div>
      </div>
      <span className="ff-ph__tag">product · {labelMap[product.cat] || product.cat}</span>
    </div>
  );
}

// Product card (2 styles toggled via CSS class)
function ProductCard({ product, onAdd, onOpen, cardStyle = 'sticker', wishlisted = false, onWishlist }) {
  // Safe guards — API may return null/string for these fields
  const tags = Array.isArray(product.tags) ? product.tags : [];
  const price = parseInt(product.price) || 0;
  const compare = parseInt(product.compare) || 0;
  const reviews = parseInt(product.reviews) || 0;
  const rating = parseFloat(product.rating) || 0;
  const discount = compare > price ? Math.round((1 - price / compare) * 100) : 0;
  const outOfStock = product.stock === 0 || product.stock === '0';
  const tagEl = outOfStock ? <span className="ff-chip" style={{ background: '#F0EDE8', color: '#9A9590', borderColor: '#E0DDD8' }}>OUT OF STOCK</span>
    : tags.includes('viral') ? <span className="ff-chip ff-chip--viral">VIRAL ✦</span>
      : tags.includes('bestseller') ? <span className="ff-chip ff-chip--best">BESTSELLER</span>
        : tags.includes('new') ? <span className="ff-chip ff-chip--new">NEW</span>
          : null;


  const HeartBtn = () => (
    <button
      onClick={e => { e.stopPropagation(); onWishlist && onWishlist(product.id); }}
      title={wishlisted ? 'Remove from wishlist' : 'Save to wishlist'}
      style={{
        position: 'absolute', bottom: 10, right: 10, zIndex: 2,
        width: 30, height: 30, borderRadius: 999,
        background: wishlisted ? 'var(--ff-accent)' : 'rgba(255,255,255,.90)',
        border: wishlisted ? 'none' : '1.5px solid var(--ff-line)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 14, cursor: 'pointer', backdropFilter: 'blur(4px)',
        transition: 'background .18s, transform .15s',
        boxShadow: '0 2px 6px rgba(0,0,0,.12)',
        color: wishlisted ? '#fff' : 'var(--ff-ink)',
      }}
      onMouseOver={e => e.currentTarget.style.transform = 'scale(1.15)'}
      onMouseOut={e => e.currentTarget.style.transform = 'scale(1)'}
    >
      {wishlisted ? '♥' : '♡'}
    </button>
  );
  if (cardStyle === 'minimal') {
    return (
      <div
        onClick={onOpen}
        style={{
          cursor: 'pointer', background: 'transparent', borderRadius: "var(--ff-radius)", overflow: 'hidden',
          transition: 'transform .15s',
        }}
        onMouseOver={e => e.currentTarget.style.transform = 'translateY(-3px)'}
        onMouseOut={e => e.currentTarget.style.transform = 'translateY(0)'}
      >
        <div style={{ position: 'relative', borderRadius: "var(--ff-radius)", overflow: 'hidden', border: 'var(--ff-border)' }}>
          <ProductArt product={product} />
          {tagEl && <div style={{ position: 'absolute', top: 10, left: 10 }}>{tagEl}</div>}
          {discount > 0 && (
            <div style={{ position: 'absolute', top: 10, right: 10, background: 'var(--ff-ink)', color: '#fff', padding: '4px 10px', borderRadius: 999, fontSize: 12, fontFamily: "'Space Grotesk',sans-serif", fontWeight: 700 }}>
              −{discount}%
            </div>
          )}
        </div>
        <div style={{ padding: '12px 2px 0' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 10 }}>
            <h3 style={{ fontSize: 16, fontWeight: 600 }}>{product.name}</h3>
            <div style={{ fontFamily: "'Space Grotesk',sans-serif", fontWeight: 700, fontSize: 15, whiteSpace: 'nowrap' }}>{fmtINR(product.price)}</div>
          </div>
          <div style={{ fontSize: 13, color: 'var(--ff-muted)', display: 'flex', justifyContent: 'space-between', marginTop: 4 }}>
            <span><Stars value={rating} size={12} /> <span style={{ marginLeft: 4 }}>{rating}</span></span>
            {outOfStock
              ? <span style={{ fontSize: 11, color: 'var(--ff-muted)', fontWeight: 600 }}>Out of stock</span>
              : <button className="ff-btn ff-btn--sm ff-btn--ink" onClick={(e) => { e.stopPropagation(); onAdd(product); }} style={{ padding: '4px 10px' }}>Add</button>
            }
          </div>
        </div>
      </div>
    );
  }

  // "sticker" default — bold border + shadow + colored footer
  return (
    <div
      onClick={onOpen}
      className="ff-card"
      style={{ cursor: 'pointer', overflow: 'hidden', display: 'flex', flexDirection: 'column', transition: 'transform .1s, box-shadow .1s' }}
      onMouseOver={e => { e.currentTarget.style.transform = 'translateY(-3px)'; e.currentTarget.style.boxShadow = 'var(--ff-shadow-lg)'; }}
      onMouseOut={e => { e.currentTarget.style.transform = 'translateY(0)'; e.currentTarget.style.boxShadow = 'var(--ff-shadow)'; }}
    >
      <div style={{ position: 'relative', opacity: outOfStock ? 0.6 : 1 }}>
        <ProductArt product={product} />
        {tagEl && <div style={{ position: 'absolute', top: 10, left: 10 }}>{tagEl}</div>}
        <HeartBtn />
        {discount > 0 && (
          <div style={{ position: 'absolute', top: 10, right: 10, background: 'var(--ff-accent)', color: '#fff', padding: '4px 10px', borderRadius: 999, fontSize: 12, fontFamily: "'Space Grotesk',sans-serif", fontWeight: 700, border: 'var(--ff-border)' }}>
            −{discount}%
          </div>
        )}
      </div>
      <div style={{ padding: 14, display: 'flex', flexDirection: 'column', gap: 6, flex: 1 }}>
        <h3 style={{ fontSize: 17 }}>{product.name}</h3>
        <p style={{ fontSize: 13, color: 'var(--ff-ink-2)', margin: 0 }}>{product.tagline}</p>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12 }}>
          <Stars value={rating} size={12} /> <span style={{ color: 'var(--ff-muted)' }}>{rating} · {reviews.toLocaleString()}</span>
        </div>
        <div style={{ marginTop: 'auto', display: 'flex', alignItems: 'center', justifyContent: 'space-between', paddingTop: 8 }}>
          <div>
            <span style={{ fontFamily: "'Space Grotesk',sans-serif", fontWeight: 700, fontSize: 18 }}>{fmtINR(product.price)}</span>
            {compare > price && (
              <span style={{ marginLeft: 6, color: 'var(--ff-muted)', textDecoration: 'line-through', fontSize: 13 }}>{fmtINR(product.compare)}</span>
            )}
          </div>
          {outOfStock
            ? <span style={{ fontSize: 11, color: 'var(--ff-muted)', fontWeight: 600, padding: '5px 0' }}>Out of stock</span>
            : <button className="ff-btn ff-btn--sm ff-btn--primary" onClick={(e) => { e.stopPropagation(); onAdd(product); }}>+ Add</button>
          }
        </div>
      </div>
    </div>
  );
}


// ─── Theme Switcher — Myntra-style floating palette ─────────────────────────
const FF_THEMES = {
  warm: { name: 'Warm', sub: 'Fraunces · DM Sans', file: 'theme-warm.css', preview: ['#D4007A', '#FAFAF8', '#181510'] },
  editorial: { name: 'Editorial', sub: 'Cormorant · Inter', file: 'theme-editorial.css', preview: ['#F9F8F5', '#111110', '#9B9590'] },
  bold: { name: 'Bold', sub: 'Space Grotesk · Energetic', file: 'theme-bold.css', preview: ['#FFF8EC', '#E4439C', '#D4FF4D'] },
  mono: { name: 'Mono', sub: 'Grayscale · Minimal', file: 'theme-mono.css', preview: ['#FFFFFF', '#000000', '#888888'] },
  myntra: { name: 'Myntra', sub: 'Indian Commerce · Bold Pink', file: 'theme-myntra.css', preview: ['#F4F4F4', '#FF3F6C', '#282C3F'] },
};

// Resolve base path (works from both root and /pages/ subdirectory)
const _themePath = () => {
  const p = window.location.pathname;
  return p.includes('/pages/') ? '../' : './';
};

function ThemeSwitcher() {
  const [open, setOpen] = React.useState(false);
  const [activeTheme, setActiveTheme] = React.useState(() => localStorage.getItem('ff_theme') || 'warm');

  React.useEffect(() => {
    injectTheme(activeTheme);
  }, []);

  const injectTheme = (key) => {
    const theme = FF_THEMES[key];
    if (!theme) return;
    // Remove existing theme link if any
    const existing = document.getElementById('ff-theme-link');
    if (existing) existing.remove();
    // Inject new theme CSS
    const link = document.createElement('link');
    link.id = 'ff-theme-link';
    link.rel = 'stylesheet';
    link.href = _themePath() + theme.file;
    document.head.appendChild(link);
    localStorage.setItem('ff_theme', key);
    setActiveTheme(key);
  };

  return (
    <div style={{ position: 'fixed', bottom: 24, right: 24, zIndex: 200 }}>
      {open && (
        <div style={{
          position: 'absolute', bottom: 56, right: 0,
          background: 'var(--ff-card,#fff)', border: '1.5px solid var(--ff-line,#eee)',
          borderRadius: 16, padding: 16, boxShadow: '0 8px 32px rgba(0,0,0,.18)',
          width: 240, animation: 'ffPop .18s'
        }}>
          <div style={{ fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.12em', color: 'var(--ff-muted,#999)', marginBottom: 12 }}>Site theme</div>
          <div style={{ display: 'grid', gap: 8 }}>
            {Object.entries(FF_THEMES).map(([key, theme]) => (
              <button key={key} onClick={() => { injectTheme(key); setOpen(false); }} style={{
                padding: '12px 14px', borderRadius: 10, cursor: 'pointer', textAlign: 'left',
                display: 'flex', alignItems: 'center', gap: 12,
                background: activeTheme === key ? 'var(--ff-bg-2,#f5f5f5)' : 'transparent',
                border: activeTheme === key ? '2px solid var(--ff-accent,#E4439C)' : '1.5px solid var(--ff-line,#eee)',
                transition: 'all .15s',
              }}>
                <div style={{ display: 'flex', gap: 3, flexShrink: 0 }}>
                  {theme.preview.map((c, i) => (
                    <div key={i} style={{ width: 18, height: 18, borderRadius: i === 0 ? '6px 2px 2px 6px' : i === 2 ? '2px 6px 6px 2px' : '2px', background: c, border: '1px solid rgba(0,0,0,.08)' }} />
                  ))}
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ff-ink,#111)' }}>{theme.name}</div>
                  <div style={{ fontSize: 11, color: 'var(--ff-muted,#999)', marginTop: 1 }}>{theme.sub}</div>
                </div>
                {activeTheme === key && <div style={{ fontSize: 16 }}>✓</div>}
              </button>
            ))}
          </div>
          <div style={{ fontSize: 10, color: 'var(--ff-muted,#aaa)', marginTop: 12, textAlign: 'center' }}>Saved for your visits</div>
        </div>
      )}
      <button onClick={() => setOpen(o => !o)} style={{
        width: 46, height: 46, borderRadius: 999, cursor: 'pointer',
        background: 'var(--ff-card,#fff)', border: '1.5px solid var(--ff-line,#eee)',
        boxShadow: '0 4px 16px rgba(0,0,0,.12)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 20, transition: 'transform .2s',
        transform: open ? 'rotate(30deg) scale(1.1)' : 'none',
      }} title="Change site theme">🎨</button>
    </div>
  );
}

// Icon helpers
const Icon = {
  Search: (p) => <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" {...p}><circle cx="11" cy="11" r="7" /><path d="M20 20l-3.5-3.5" /></svg>,
  Bag: (p) => <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M5 8h14l-1 12H6z" /><path d="M9 8V6a3 3 0 016 0v2" /></svg>,
  User: (p) => <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" {...p}><circle cx="12" cy="8" r="4" /><path d="M4 21c1.5-4.5 5-6 8-6s6.5 1.5 8 6" /></svg>,
  Close: (p) => <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" {...p}><path d="M6 6l12 12M18 6L6 18" /></svg>,
  Menu: (p) => <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" {...p}><path d="M4 7h16M4 12h16M4 17h16" /></svg>,
  Arrow: (p) => <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M5 12h14M13 5l7 7-7 7" /></svg>,
  Heart: (p) => <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M20.8 5.6a5.5 5.5 0 00-8.8 0 5.5 5.5 0 00-8.8 7l8.8 8.8 8.8-8.8a5.5 5.5 0 000-7z" /></svg>,
  Check: (p) => <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M4 12l5 5L20 6" /></svg>,
  Box: (p) => <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M3 7l9-4 9 4v10l-9 4-9-4z" /><path d="M3 7l9 4 9-4M12 11v10" /></svg>,
  Truck: (p) => <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M3 7h11v10H3zM14 10h4l3 3v4h-7z" /><circle cx="7" cy="18" r="2" /><circle cx="17" cy="18" r="2" /></svg>,
  Tag: (p) => <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M3 12l9-9h9v9l-9 9z" /><circle cx="16" cy="8" r="1.5" fill="currentColor" /></svg>,
  Filter: (p) => <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" {...p}><path d="M4 6h16M7 12h10M10 18h4" /></svg>,
  Plus: (p) => <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" {...p}><path d="M12 5v14M5 12h14" /></svg>,
  Minus: (p) => <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" {...p}><path d="M5 12h14" /></svg>,
  Trash: (p) => <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M4 7h16M9 7V5a2 2 0 012-2h2a2 2 0 012 2v2M6 7l1 13h10l1-13M10 11v6M14 11v6" /></svg>,
  Chart: (p) => <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M4 20V10M10 20V4M16 20v-7M22 20H2" /></svg>,
  Grid: (p) => <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" {...p}><rect x="3" y="3" width="7" height="7" /><rect x="14" y="3" width="7" height="7" /><rect x="3" y="14" width="7" height="7" /><rect x="14" y="14" width="7" height="7" /></svg>,
  Star: (p) => <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor" {...p}><path d="M12 2l3 7 7 .6-5.3 4.7 1.6 7L12 17.7 5.7 21.3l1.6-7L2 9.6 9 9z" /></svg>,
};

// Header
function Header({ route, goto, cart, openCart, user, onLogin, search, setSearch }) {
  const count = (cart || []).reduce((s, i) => s + i.qty, 0);
  const [mopen, setMopen] = useState(false);
  return (
    <header style={{ position: 'sticky', top: 0, zIndex: 50, background: 'var(--ff-bg)', borderBottom: 'var(--ff-border)' }}>
      {/* Announcement bar */}
      <div style={{ background: 'var(--ff-ink)', color: 'var(--ff-bg)', textAlign: 'center', padding: '6px 12px', fontSize: 12, fontFamily: "'Space Grotesk',sans-serif", fontWeight: 600, letterSpacing: '.05em' }}>
        FREE SHIPPING OVER ₹999 ✦ ALL SALES FINAL ✦ COD AVAILABLE
      </div>
      <div style={{ maxWidth: 1320, margin: '0 auto', padding: '14px 24px', display: 'flex', alignItems: 'center', gap: 18 }}>
        <a href={FF_URLS.home} style={{ display: 'flex', alignItems: 'center', gap: 8, textDecoration: 'none', color: 'inherit' }}>
          <span style={{ fontSize: 22, color: 'var(--ff-accent)' }}>✦</span>
          <span className="ff-display" style={{ fontSize: 24, letterSpacing: '-0.03em' }}>Fussy Finds</span>
        </a>

        <nav className="ff-hide-mobile" style={{ display: 'flex', gap: 4, marginLeft: 12 }}>
          <a href={FF_URLS.home} style={{ padding: '8px 12px', fontFamily: "'Space Grotesk',sans-serif", fontWeight: 600, fontSize: 14, borderRadius: 8, textDecoration: 'none', color: 'inherit' }}>Home</a>
          <a href={FF_URLS.shop} style={{ padding: '8px 12px', fontWeight: 600, fontSize: 14, borderRadius: 8, textDecoration: 'none', color: 'inherit' }}>Shop</a>
          <a href={FF_URLS.shop + '?filter=viral'} style={{ padding: '8px 12px', fontWeight: 600, fontSize: 14, borderRadius: 8, textDecoration: 'none', color: 'inherit' }}>Viral ✦</a>
          <a href={FF_URLS.shop + '?filter=new'} style={{ padding: '8px 12px', fontWeight: 600, fontSize: 14, borderRadius: 8, textDecoration: 'none', color: 'inherit' }}>New Drops</a>
          <a href="/blog" style={{ padding: '8px 12px', fontWeight: 600, fontSize: 14, borderRadius: 8, textDecoration: 'none', color: 'inherit' }}>Blog</a>
          <a href="/recipes" style={{ padding: '8px 12px', fontWeight: 600, fontSize: 14, borderRadius: 8, textDecoration: 'none', color: 'inherit' }}>Recipes</a>
          <a href="/spotlight" style={{ padding: '8px 12px', fontWeight: 600, fontSize: 14, borderRadius: 8, textDecoration: 'none', color: 'inherit' }}>✦ Spotlight</a>
        </nav>

        <div className="ff-hide-mobile" style={{ flex: 1, maxWidth: 420, margin: '0 auto', position: 'relative' }}>
          <Icon.Search style={{ position: 'absolute', left: 14, top: '50%', transform: 'translateY(-50%)', color: 'var(--ff-muted)' }} />
          <input
            value={search}
            onChange={e => setSearch(e.target.value)}
            onKeyDown={e => { if (e.key === 'Enter' && search) location.href = FF_URLS.search(search); }}
            placeholder="Search 2,000+ viral finds…"
            className="ff-input"
            style={{ paddingLeft: 42, paddingRight: 16, borderRadius: 999 }}
          />
        </div>

        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginLeft: 'auto' }}>
          {user && (
            <a href="/wishlist"
              className="ff-btn ff-btn--sm ff-btn--ghost"
              style={{ padding: '8px 12px', textDecoration: 'none' }}
              title="Wishlist">
              ♥
            </a>
          )}
          <button
            onClick={() => { if (user) location.href = FF_URLS.account(); else onLogin(); }}
            className="ff-btn ff-btn--sm"
            style={{ padding: '8px 12px' }}
          >
            <Icon.User />
            <span className="ff-hide-mobile">{user ? user.name.split(' ')[0] : 'Log in'}</span>
          </button>
          <button
            onClick={openCart}
            className="ff-btn ff-btn--sm ff-btn--primary"
            style={{ position: 'relative', padding: '8px 14px' }}
          >
            <Icon.Bag />
            <span>{fmtINR((cart || []).reduce((s, i) => s + i.price * i.qty, 0))}</span>
            {count > 0 && (
              <span style={{
                position: 'absolute', top: -6, right: -6,
                background: 'var(--ff-ink)', color: '#fff', fontSize: 11, fontWeight: 700,
                minWidth: 20, height: 20, borderRadius: 999, display: 'grid', placeItems: 'center',
                border: '2px solid #fff',
              }}>{count}</span>
            )}
          </button>
          <button className="ff-show-mobile ff-btn ff-btn--sm ff-btn--ghost" onClick={() => setMopen(!mopen)}>
            {mopen ? <Icon.Close /> : <Icon.Menu />}
          </button>
        </div>
      </div>

      {mopen && (
        <div className="ff-show-mobile" style={{ borderTop: 'var(--ff-border)', padding: 16, display: 'grid', gap: 8, background: 'var(--ff-bg)' }}>
          <div style={{ position: 'relative' }}>
            <Icon.Search style={{ position: 'absolute', left: 14, top: '50%', transform: 'translateY(-50%)', color: 'var(--ff-muted)' }} />
            <input value={search} onChange={e => setSearch(e.target.value)} onKeyDown={e => { if (e.key === 'Enter' && search) location.href = FF_URLS.search(search); }} placeholder="Search…" className="ff-input" style={{ paddingLeft: 42, borderRadius: 999 }} />
          </div>
          <a href={FF_URLS.shop} className="ff-btn">Shop</a>
          <a href={FF_URLS.shop + '?filter=viral'} className="ff-btn">Viral ✦</a>
          <a href={FF_URLS.shop + '?filter=new'} className="ff-btn">New Drops</a>
          <a href="/blog" className="ff-btn">Blog</a>
          <a href="/recipes" className="ff-btn">Recipes</a>
          <a href="/spotlight" className="ff-btn">✦ Spotlight</a>
        </div>
      )}
    </header>
  );
}

// Footer
function Footer() {
  const base = (() => { const p = location.pathname; return p.includes('/pages/') ? '../' : './'; })();
  const [email, setEmail] = React.useState('');
  const [joined, setJoined] = React.useState(false);

  const [subLoading, setSubLoading] = React.useState(false);
  const [subError, setSubError] = React.useState('');

  const handleJoin = async () => {
    if (!email || !email.includes('@')) { setSubError('Enter a valid email'); return; }
    setSubLoading(true); setSubError('');
    try {
      // Get referral code from URL if present
      const ref = new URLSearchParams(location.search).get('ref') || '';
      const res = await fetch('/api/newsletter.php?action=subscribe', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, ref }),
      });
      const data = await res.json();
      if (data.ok) {
        setJoined(true);
      } else {
        setSubError(data.error || 'Something went wrong');
      }
    } catch (e) {
      setSubError('Could not subscribe. Try again.');
    } finally {
      setSubLoading(false);
    }
  };

  const SHOP_LINKS = [
    { l: 'All Finds', href: base + '/shop' },
    { l: 'Viral ✦', href: base + '/shop?filter=viral' },
    { l: 'New Drops', href: base + '/shop?filter=new' },
    { l: 'Bestsellers', href: base + '/shop?filter=bestseller' },
    { l: 'Blog', href: base + '/blog' },
    { l: 'Recipes', href: base + '/recipes' },
    { l: 'Under ₹999', href: base + '/shop?sort=price_asc' },
  ];

  const HELP_LINKS = [
    { l: 'Shipping Info', href: base + '/shipping-info' },
    { l: 'Track Order', href: base + '/account?tab=orders' },
    { l: 'Contact Us', href: 'mailto:hello@fussyfind.com' },
    { l: 'FAQs', href: base + '/faq' },
  ];

  const BRAND_LINKS = [
    { l: 'Our Story', href: base + '/about' },
    { l: 'Journal', href: '/about' },
    { l: 'Creator Program', href: 'mailto:collab@fussyfind.com' },
    { l: 'Press', href: 'mailto:press@fussyfind.com' },
  ];

  const LinkCol = ({ title, links }) => (
    <div>
      <h4 style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '.12em', marginBottom: 14, opacity: .5, fontWeight: 700 }}>{title}</h4>
      <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'grid', gap: 10 }}>
        {links.map(({ l, href }) => (
          <li key={l}>
            <a href={href} style={{ fontSize: 14, opacity: .85, textDecoration: 'none', color: 'inherit', transition: 'opacity .15s' }}
              onMouseOver={e => e.target.style.opacity = 1} onMouseOut={e => e.target.style.opacity = .85}>{l}</a>
          </li>
        ))}
      </ul>
    </div>
  );

  return (
    <footer style={{ background: 'var(--ff-ink)', color: 'var(--ff-bg)', marginTop: 60 }}>
      <div style={{ maxWidth: 1320, margin: '0 auto', padding: '52px 24px 32px', display: 'grid', gridTemplateColumns: '2fr 1fr 1fr 1fr', gap: 40 }} className="ff-footer-grid">

        {/* Brand col */}
        <div>
          <a href={base + 'index.html'} style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 14, textDecoration: 'none', color: 'inherit' }}>
            <span style={{ fontSize: 26, color: 'var(--ff-accent)' }}>✦</span>
            <span className="ff-display" style={{ fontSize: 28 }}>Fussy Finds</span>
          </a>
          <p style={{ opacity: .65, maxWidth: 320, fontSize: 14, lineHeight: 1.6 }}>The internet's favourite things, curated and shipped in 48h. No algorithms — just the stuff we'd actually keep.</p>

          {/* Newsletter */}
          <div style={{ marginTop: 20 }}>
            <div style={{ fontSize: 12, textTransform: 'uppercase', letterSpacing: '.1em', opacity: .5, marginBottom: 8 }}>Get early access to new drops</div>
            {joined ? (
              <div>
                <div style={{ fontSize: 14, color: 'var(--ff-lime)', fontWeight: 600, marginBottom: 6 }}>✦ You're in! Check your inbox.</div>
                <div style={{ fontSize: 12, opacity: .7 }}>Use code <strong>WELCOME10</strong> for 10% off your first order.</div>
              </div>
            ) : (
              <div>
                <div style={{ display: 'flex', gap: 8 }}>
                  <input
                    value={email} onChange={e => setEmail(e.target.value)}
                    onKeyDown={e => e.key === 'Enter' && handleJoin()}
                    placeholder="your@email.com"
                    className="ff-input"
                    style={{ background: 'rgba(255,255,255,.07)', color: '#fff', border: '1.5px solid rgba(255,255,255,.15)', boxShadow: 'none', flex: 1 }}
                  />
                  <button className="ff-btn ff-btn--primary" onClick={handleJoin}
                    disabled={subLoading} style={{ boxShadow: 'none', flexShrink: 0 }}>
                    {subLoading ? '…' : 'Join'}
                  </button>
                </div>
                {subError && <div style={{ fontSize: 12, color: '#FF9A9A', marginTop: 6 }}>{subError}</div>}
              </div>
            )}
          </div>

          {/* Socials */}
          <div style={{ display: 'flex', gap: 10, marginTop: 20 }}>
            {[
              { n: 'Instagram', href: 'https://instagram.com/fussyfinds', icon: '📸' },
              { n: 'YouTube', href: 'https://youtube.com/@fussyfinds', icon: '▶' },
            ].map(s => (
              <a key={s.n} href={s.href} target="_blank" rel="noopener noreferrer" style={{
                width: 36, height: 36, borderRadius: 10, border: '1.5px solid rgba(255,255,255,.2)',
                display: 'grid', placeItems: 'center', fontSize: 15, textDecoration: 'none',
                transition: 'border-color .15s',
              }} onMouseOver={e => e.currentTarget.style.borderColor = 'var(--ff-accent)'}
                onMouseOut={e => e.currentTarget.style.borderColor = 'rgba(255,255,255,.2)'}>
                {s.icon}
              </a>
            ))}
          </div>
        </div>

        <LinkCol title="Shop" links={SHOP_LINKS} />
        <LinkCol title="Help" links={HELP_LINKS} />
        <LinkCol title="Fussy" links={BRAND_LINKS} />
      </div>

      {/* Bottom bar */}
      <div style={{ borderTop: '1px solid rgba(255,255,255,.1)', padding: '14px 24px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 8 }}>
        <div style={{ fontSize: 12, opacity: .45 }}>© 2026 Fussy Finds · Made in India 🇮🇳 · GSTIN 27AABCF1234Z1Z5</div>
        <div style={{ display: 'flex', gap: 16, fontSize: 12, opacity: .45 }}>
          <a href={base + '/privacy'} style={{ color: 'inherit', textDecoration: 'none' }}>Privacy Policy</a>
          <a href={base + '/terms'} style={{ color: 'inherit', textDecoration: 'none' }}>Terms of Use</a>
          <a href={base + '/shipping-info'} style={{ color: 'inherit', textDecoration: 'none' }}>Shipping Policy</a>
        </div>
      </div>
    </footer>
  );
}

// Toast system
function Toast({ toast, onDismiss }) {
  useEffect(() => {
    if (!toast) return;
    const t = setTimeout(onDismiss, 2800);
    return () => clearTimeout(t);
  }, [toast]);
  if (!toast) return null;
  return (
    <div className="ff-toast" style={{
      position: 'fixed', bottom: 24, left: '50%', transform: 'translateX(-50%)',
      background: 'var(--ff-ink)', color: 'var(--ff-bg)', padding: '14px 20px',
      borderRadius: 999, border: '2px solid var(--ff-accent)', boxShadow: 'var(--ff-shadow)',
      fontFamily: "'Space Grotesk',sans-serif", fontWeight: 600, fontSize: 14,
      display: 'flex', alignItems: 'center', gap: 10, zIndex: 200,
    }}>
      <span style={{ color: 'var(--ff-lime)' }}>✦</span> {toast}
    </div>
  );
}

Object.assign(window, { Stars, ProductArt, ProductCard, Icon, Header, Footer, Toast, fmtINR, ThemeSwitcher, FF_THEMES });
