// StockPage — full catalogue subpage.
// Big gallery (4 cols desktop / 2 cols mobile), brand + availability
// filters, model-name click → channel picker modal that copies the
// model name to clipboard and opens Discord / WhatsApp.
//
// Reuses primitives from variant-a.jsx via window.* — those components
// are registered there when the file loads.

function StockPage() {
  const [lang, setLang] = React.useState('pl');
  const [avail, setAvail] = React.useState('all');   // 'all' | 'available' | 'oos'
  const [query, setQuery] = React.useState('');
  const [picker, setPicker] = React.useState(null);  // selected item or null
  const { items, ready } = useStock();
  const t = I18N[lang];

  const a = {
    bg: '#f1ede4',
    ink: '#16110d',
    line: '#16110d',
    accent: '#ff4413',
    whatsapp: '#25D366',
    mute: '#7d736a',
  };
  const rule = `2px solid ${a.line}`;

  // — Filtered list —
  const filtered = items.filter(s => {
    if (avail === 'available' && s.availability === 'oos') return false;
    if (avail === 'oos' && s.availability !== 'oos') return false;
    if (query.trim()) {
      const q = query.trim().toLowerCase();
      const hay = ((s.model || '') + ' ' + (s.code || '')).toLowerCase();
      if (!hay.includes(q)) return false;
    }
    return true;
  });

  // — Topbar markup mirrors the homepage so the chrome feels identical —
  const Topbar = (
    <div className="va-topbar" style={{ display: 'flex', alignItems: 'stretch', borderBottom: rule, fontSize: 12, textTransform: 'uppercase', letterSpacing: '.06em', fontWeight: 600 }}>
      <a className="va-topbar-brand" href="index.html" style={{ padding: '14px 18px', borderRight: rule, fontFamily: "'Archivo Black', sans-serif", letterSpacing: '.04em', fontSize: 14, color: a.ink, textDecoration: 'none', display: 'flex', alignItems: 'center', gap: 10 }}>
        <ISTLogo size={26} bg={a.ink} fg={a.bg} />
        INSTOCK · TRADE™
      </a>
      <div className="va-topbar-tagline" style={{ padding: '14px 22px', borderRight: rule, color: a.mute, fontFamily: "'JetBrains Mono', monospace", textTransform: 'none', letterSpacing: 0, display: 'flex', alignItems: 'center' }}>
        B2B Sneakers · PL
      </div>
      <div className="va-topbar-spacer" style={{ flex: 1 }} />
      {[
        { href: 'stock.html',           label: t.nav_stock,    active: true },
        { href: 'index.html#wtb',       label: t.nav_wtb,      active: false },
        { href: 'index.html#faq',       label: t.nav_faq,      active: false },
        { href: 'index.html#contact',   label: t.nav_contact,  active: false },
      ].map((n) => (
        <a className="va-topbar-link" key={n.href} href={n.href} style={{
          padding: '14px 16px', borderLeft: rule, color: n.active ? a.bg : a.ink,
          background: n.active ? a.ink : 'transparent',
          textDecoration: 'none', display: 'flex', alignItems: 'center',
        }}>{n.label}</a>
      ))}
      <button className="va-topbar-lang" onClick={() => setLang(lang === 'pl' ? 'en' : 'pl')}
        style={{ padding: '14px 18px', borderLeft: rule, background: a.ink, color: a.bg, font: 'inherit', cursor: 'pointer', fontWeight: 700, letterSpacing: '.08em', textTransform: 'uppercase' }}>
        {lang === 'pl' ? 'EN' : 'PL'}
      </button>
    </div>
  );

  return (
    <div style={{
      width: '100%', minHeight: '100%',
      background: a.bg, color: a.ink,
      fontFamily: "'Archivo', system-ui, sans-serif",
      display: 'flex', flexDirection: 'column',
    }}>
      {Topbar}

      {/* Header — title + animated catalogue counter */}
      <div style={{ borderBottom: rule, padding: '28px 24px 24px' }}>
        <div className="va-eyebrow" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontFamily: "'JetBrains Mono', monospace", fontSize: 11, color: a.mute, textTransform: 'uppercase', letterSpacing: '.16em', marginBottom: 14 }}>
          <span><a href="index.html" style={{ color: a.mute, textDecoration: 'none' }}>← {lang === 'pl' ? 'Strona główna' : 'Home'}</a></span>
          <span style={{ height: 1, background: a.line, flex: 1, margin: '0 16px', opacity: .25 }}></span>
          <span>{lang === 'pl' ? 'Pełny katalog · live' : 'Full catalogue · live'}</span>
        </div>
        <div className="sp-headrow" style={{ display: 'grid', gridTemplateColumns: '1fr auto', alignItems: 'center', gap: 24 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 24, minWidth: 0 }}>
            <h1 className="sp-h1" style={{
              fontFamily: "'Archivo Black', sans-serif",
              fontSize: 'clamp(48px, 7vw, 96px)',
              lineHeight: .88, margin: 0,
              letterSpacing: '-0.04em', textTransform: 'uppercase',
              whiteSpace: 'nowrap',
            }}>
              {lang === 'pl' ? 'Pełny stock' : 'Full stock'}
            </h1>
            <SneakerMark size={64} color={a.ink} accent={a.accent} bg={a.bg} />
          </div>
          {/* Animated counter — ticks when filters change */}
          <CatalogCounter visible={ready ? filtered.length : 0} total={ready ? items.length : 0} lang={lang} colors={a} />
        </div>
      </div>

      {/* Filters bar — availability + search */}
      <div className="sp-filters" style={{
        display: 'grid', gridTemplateColumns: '1.4fr 1fr', borderBottom: rule,
      }}>
        <div style={{ padding: '14px 24px', borderRight: rule }}>
          <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10, color: a.mute, textTransform: 'uppercase', letterSpacing: '.12em', marginBottom: 8 }}>
            {lang === 'pl' ? 'Dostępność' : 'Availability'}
          </div>
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {[
              { v: 'all',       l_pl: 'Wszystko',           l_en: 'All' },
              { v: 'available', l_pl: 'Możliwe do zamówienia', l_en: 'Available to order' },
              { v: 'oos',       l_pl: 'Chwilowy brak',      l_en: 'Currently out' },
            ].map(opt => (
              <button key={opt.v} onClick={() => setAvail(opt.v)} style={{
                font: 'inherit', fontWeight: 700, fontSize: 13, letterSpacing: '.04em',
                padding: '7px 14px', cursor: 'pointer', textTransform: 'uppercase',
                border: rule, background: avail === opt.v ? a.ink : 'transparent',
                color: avail === opt.v ? a.bg : a.ink,
              }}>{lang === 'pl' ? opt.l_pl : opt.l_en}</button>
            ))}
          </div>
        </div>
        <div style={{ padding: '14px 24px' }}>
          <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10, color: a.mute, textTransform: 'uppercase', letterSpacing: '.12em', marginBottom: 8 }}>
            {lang === 'pl' ? 'Szukaj' : 'Search'}
          </div>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 8,
            border: rule, padding: '6px 12px', background: a.bg,
          }}>
            <SearchGlyph color={a.mute} />
            <input
              type="text"
              value={query}
              onChange={e => setQuery(e.target.value)}
              placeholder={lang === 'pl' ? 'Nazwa lub SKU…' : 'Name or SKU…'}
              style={{
                flex: 1, border: 'none', background: 'transparent',
                font: 'inherit', fontFamily: "'JetBrains Mono', monospace",
                fontSize: 13, outline: 'none', padding: '4px 0', color: a.ink,
                minWidth: 0,
              }}
            />
            {query && (
              <button onClick={() => setQuery('')} aria-label="clear" style={{
                all: 'unset', cursor: 'pointer', color: a.mute, fontSize: 14,
                padding: '0 4px', lineHeight: 1,
              }}>✕</button>
            )}
          </div>
        </div>
      </div>

      {/* Grid */}
      <div className="sp-grid" style={{
        display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', borderBottom: rule,
      }}>
        {!ready ? (
          // First visit — sheet loading. Render 15 skeleton cards so
          // the user never sees stale embedded fallback content flash.
          Array.from({ length: 15 }, (_, i) => {
            const col = i % 5;
            const lastRow = i >= 10;
            return (
              <div key={i} style={{
                borderRight: col === 4 ? 'none' : rule,
                borderBottom: lastRow ? 'none' : rule,
              }}>
                <SkeletonCard rule={rule} bg={a.bg} />
              </div>
            );
          })
        ) : filtered.length === 0 ? (
          <div style={{ gridColumn: '1 / -1', padding: '80px 24px', textAlign: 'center', color: a.mute, fontFamily: "'JetBrains Mono', monospace", letterSpacing: '.08em', textTransform: 'uppercase' }}>
            {lang === 'pl' ? 'Brak pasujących modeli' : 'No matching models'}
          </div>
        ) : filtered.map((s, i) => {
          const col = i % 5;
          const row = Math.floor(i / 5);
          const lastRow = row === Math.floor((filtered.length - 1) / 5);
          const isOut = s.availability === 'oos';
          return (
            <button key={s.code} className="sp-card" onClick={() => setPicker(s)} style={{
              all: 'unset', display: 'block', cursor: 'pointer', position: 'relative',
              borderRight: col === 4 ? 'none' : rule,
              borderBottom: lastRow ? 'none' : rule,
              background: a.bg,
            }}>
              <div style={{ aspectRatio: '4 / 3', borderBottom: rule, position: 'relative' }}>
                <PatternedSneakerSlot item={s} />
                {isOut && (
                  <div style={{
                    position: 'absolute', inset: 0,
                    background: 'rgba(241,237,228,.55)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    pointerEvents: 'none',
                  }}>
                    <span style={{
                      background: a.ink, color: a.bg, padding: '6px 14px',
                      fontFamily: "'JetBrains Mono', monospace", fontSize: 11,
                      letterSpacing: '.14em', textTransform: 'uppercase', fontWeight: 700,
                    }}>{t.stock_oos}</span>
                  </div>
                )}
              </div>
              <div style={{ padding: '14px 14px 16px', display: 'flex', flexDirection: 'column', gap: 6 }}>
                <div style={{ fontWeight: 700, fontSize: 17, lineHeight: 1.2 }}>{s.model}</div>
                {s.code && (
                  <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 11, color: a.mute, letterSpacing: '.08em' }}>
                    SKU · {s.code}
                  </div>
                )}
                <div style={{
                  display: 'inline-flex', alignItems: 'center', gap: 7,
                  fontFamily: "'JetBrains Mono', monospace", fontSize: 11,
                  textTransform: 'uppercase', letterSpacing: '.1em', fontWeight: 700,
                  color: isOut ? a.mute : a.ink, marginTop: 2,
                }}>
                  <span style={{ width: 7, height: 7, background: isOut ? a.mute : a.ink, borderRadius: '50%' }}></span>
                  {isOut ? t.stock_oos : t.stock_available}
                </div>
              </div>
            </button>
          );
        })}
      </div>

      {/* Footer */}
      <div className="va-footer" id="contact" style={{ background: a.ink, color: a.bg, padding: '28px 24px', display: 'grid', gridTemplateColumns: 'auto 1fr 1fr 1fr', gap: 24, alignItems: 'start', marginTop: 'auto' }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <ISTLogo size={120} bg={a.bg} fg={a.ink} />
          <div style={{ fontFamily: "'Archivo Black', sans-serif", fontSize: 28, lineHeight: .9, letterSpacing: '-.02em', textTransform: 'uppercase' }}>InStock<br/>Trade™</div>
        </div>
        <div>
          <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10, opacity: .5, textTransform: 'uppercase', letterSpacing: '.12em', marginBottom: 8 }}>{lang === 'pl' ? 'Kontakt' : 'Contact'}</div>
          <div style={{ fontSize: 14, lineHeight: 1.7 }}>
            <a href={DISCORD_URL} target="_blank" rel="noopener noreferrer" style={{ color: a.bg, textDecoration: 'underline', textUnderlineOffset: 3 }}>Discord</a><br/>
            <a href={WHATSAPP_URL} target="_blank" rel="noopener noreferrer" style={{ color: a.bg, textDecoration: 'underline', textUnderlineOffset: 3 }}>WhatsApp — grupa</a><br/>
            <a href="mailto:kontakt@instocktrade.pl" style={{ color: a.bg, textDecoration: 'underline', textUnderlineOffset: 3 }}>kontakt@instocktrade.pl</a>
          </div>
        </div>
        <div>
          <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10, opacity: .5, textTransform: 'uppercase', letterSpacing: '.12em', marginBottom: 8 }}>{lang === 'pl' ? 'Adres' : 'Address'}</div>
          <div style={{ fontSize: 14, lineHeight: 1.7 }}>
            ul. Józefa Chełmońskiego 6/47<br/>
            75-900 Koszalin<br/>
            NIP PL: xxxxxxxxxx
          </div>
        </div>
        <div>
          <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10, opacity: .5, textTransform: 'uppercase', letterSpacing: '.12em', marginBottom: 8 }}>{lang === 'pl' ? 'Godziny' : 'Hours'}</div>
          <div style={{ fontSize: 14, lineHeight: 1.7 }}>
            {lang === 'pl' ? 'Kontakt' : 'Contact'} · 24/7<br/>
            © 2026 · {t.foot_rights}
          </div>
        </div>
      </div>

      {/* Channel picker modal */}
      {picker && <ChannelPicker item={picker} lang={lang} onClose={() => setPicker(null)} colors={a} />}
    </div>
  );
}

// — ChannelPicker —
// Tap-on-product → modal that asks: "Zapytaj na Discord lub WhatsApp?"
// Group invites (chat.whatsapp.com/..., discord.gg/...) cannot pre-fill
// a message via URL, so we put the model name on the clipboard right
// before opening the invite — user pastes it in chat manually.
function ChannelPicker({ item, lang, onClose, colors }) {
  const [copiedKey, setCopiedKey] = React.useState(null);
  const message = lang === 'pl'
    ? `Cześć! Pytam o: ${item.model}`
    : `Hi! Asking about: ${item.model}`;

  const handleOpen = async (channel) => {
    try { await navigator.clipboard.writeText(message); } catch (_) { /* fallback below */ }
    setCopiedKey(channel);
    const url = channel === 'discord' ? DISCORD_URL : WHATSAPP_URL;
    setTimeout(() => { window.open(url, '_blank', 'noopener,noreferrer'); }, 400);
    setTimeout(() => { onClose(); }, 1100);
  };

  return (
    <div onClick={onClose} role="dialog" aria-modal="true"
      style={{
        position: 'fixed', inset: 0, zIndex: 100,
        background: 'rgba(22, 17, 13, 0.55)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 20,
      }}>
      <div onClick={e => e.stopPropagation()} style={{
        background: colors.bg, color: colors.ink,
        border: `2px solid ${colors.ink}`,
        maxWidth: 520, width: '100%',
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', borderBottom: `2px solid ${colors.ink}`, padding: '12px 18px' }}>
          <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 11, letterSpacing: '.12em', textTransform: 'uppercase', color: colors.mute }}>
            {lang === 'pl' ? 'Zapytaj o ten model' : 'Ask about this model'}
          </span>
          <button onClick={onClose} aria-label="close" style={{
            all: 'unset', cursor: 'pointer', padding: '4px 10px',
            fontFamily: "'JetBrains Mono', monospace", fontSize: 14, fontWeight: 700,
          }}>✕</button>
        </div>
        <div style={{ padding: '22px 22px 8px' }}>
          <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 11, color: colors.mute, letterSpacing: '.1em', textTransform: 'uppercase', marginBottom: 4 }}>
            {item.brand || '—'}
          </div>
          <div style={{ fontFamily: "'Archivo Black', sans-serif", fontSize: 30, lineHeight: 1, letterSpacing: '-.02em', textTransform: 'uppercase' }}>
            {item.model}
          </div>
        </div>
        <div style={{ padding: '14px 22px 4px', fontSize: 14, color: colors.mute, lineHeight: 1.5 }}>
          {lang === 'pl'
            ? 'Po kliknięciu kopiujemy nazwę modelu do schowka i otwieramy wybrany kanał — wystarczy wkleić wiadomość.'
            : 'On click we copy the model name to your clipboard and open the chosen channel — just paste the message.'}
        </div>
        <div style={{ padding: 22, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          <button onClick={() => handleOpen('discord')} style={{
            all: 'unset', cursor: 'pointer',
            padding: '18px 16px', background: '#5865F2', color: '#fff',
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            fontWeight: 800, fontSize: 17, textTransform: 'uppercase', letterSpacing: '.02em',
          }}>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 10 }}>
              <DiscordGlyph />
              Discord
            </span>
            <span style={{ fontSize: 20 }}>{copiedKey === 'discord' ? '✓' : '→'}</span>
          </button>
          <button onClick={() => handleOpen('whatsapp')} style={{
            all: 'unset', cursor: 'pointer',
            padding: '18px 16px', background: colors.whatsapp, color: '#fff',
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            fontWeight: 800, fontSize: 17, textTransform: 'uppercase', letterSpacing: '.02em',
          }}>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 10 }}>
              <WhatsappGlyph />
              WhatsApp
            </span>
            <span style={{ fontSize: 20 }}>{copiedKey === 'whatsapp' ? '✓' : '→'}</span>
          </button>
        </div>
        {copiedKey && (
          <div style={{ padding: '0 22px 18px', fontFamily: "'JetBrains Mono', monospace", fontSize: 12, color: colors.accent, letterSpacing: '.06em', textTransform: 'uppercase' }}>
            ✓ {lang === 'pl' ? 'Skopiowano:' : 'Copied:'} „{message}"
          </div>
        )}
      </div>
    </div>
  );
}

window.StockPage = StockPage;
window.ChannelPicker = ChannelPicker;

// — SneakerMark —
// Animated brutalist sneaker silhouette — the creative replacement
// for the flame on the stock subpage header. Side-view sneaker drawn
// with a chunky outline (no real brand cues), with a subtle "walking"
// rock animation and a few motion-line dashes behind it.
function SneakerMark({ size = 96, color = '#16110d', accent = '#ff4413', bg = '#f1ede4' }) {
  return (
    <svg width={size * 1.6} height={size} viewBox="0 0 160 100" fill="none" aria-hidden="true"
         style={{ display: 'block', overflow: 'visible' }}>
      {/* Motion lines — independent pulse */}
      <g className="sm-lines">
        <line x1="4"  y1="62" x2="20" y2="62" stroke={accent} strokeWidth="3" strokeLinecap="round" />
        <line x1="0"  y1="74" x2="14" y2="74" stroke={accent} strokeWidth="3" strokeLinecap="round" opacity=".7" />
        <line x1="6"  y1="86" x2="22" y2="86" stroke={accent} strokeWidth="3" strokeLinecap="round" opacity=".5" />
      </g>

      {/* Sneaker rocks subtly — translateY + tiny tilt */}
      <g className="sm-body" style={{ transformOrigin: '90px 90px' }}>
        {/* Sole (dark chunky band under) */}
        <rect x="30" y="80" width="124" height="14" fill={color} />
        <rect x="30" y="86" width="124" height="2" fill={bg} opacity=".4" />
        {/* Body — paper-cut silhouette */}
        <path d="
          M 30 80
          L 30 64
          Q 30 56 40 54
          L 56 50
          L 64 38
          Q 68 32 78 32
          L 102 32
          Q 108 32 114 38
          L 124 52
          L 144 60
          Q 154 62 154 72
          L 154 80
          Z"
          fill={bg} stroke={color} strokeWidth="3" strokeLinejoin="miter" />

        {/* Swoosh-like stripe (own shape — sweeping curve, not a logo) */}
        <path d="M 50 76 Q 80 84 130 64 L 138 60"
          fill="none" stroke={color} strokeWidth="6" strokeLinecap="butt" />

        {/* Laces — three small dashes */}
        <line x1="74" y1="44" x2="92" y2="44" stroke={color} strokeWidth="2.5" />
        <line x1="76" y1="50" x2="94" y2="50" stroke={color} strokeWidth="2.5" />
        <line x1="78" y1="56" x2="96" y2="56" stroke={color} strokeWidth="2.5" />

        {/* Heel detail */}
        <rect x="30" y="68" width="6" height="12" fill={color} />
      </g>

      <style>{`
        @keyframes smRock { 0%,100% { transform: translateY(0) rotate(-1.2deg); } 50% { transform: translateY(-3px) rotate(1.4deg); } }
        @keyframes smLines { 0% { transform: translateX(-4px); opacity: 0; } 30% { opacity: 1; } 100% { transform: translateX(8px); opacity: 0; } }
        .sm-body  { animation: smRock  1.6s ease-in-out infinite; }
        .sm-lines line { animation: smLines 1.2s ease-out infinite; }
        .sm-lines line:nth-child(2) { animation-delay: .25s; }
        .sm-lines line:nth-child(3) { animation-delay: .5s; }
      `}</style>
    </svg>
  );
}
// The creative replacement for the flame on the stock subpage. A chunky
// 2-digit catalog index that animates when filters change (counts up or
// down with an easing curve). Underneath, a small "INDEX 26.18" stamp
// gives it the catalog/inventory feel. Reads as the live tally of what
// the user is currently filtering down to.
function CatalogCounter({ visible, total, lang, colors }) {
  const [shown, setShown] = React.useState(visible);
  const fromRef = React.useRef(visible);
  React.useEffect(() => {
    const from = fromRef.current;
    const to = visible;
    if (from === to) return;
    const duration = 380;
    const start = performance.now();
    let raf;
    const tick = (t) => {
      const p = Math.min(1, (t - start) / duration);
      const eased = 1 - Math.pow(1 - p, 3);
      setShown(Math.round(from + (to - from) * eased));
      if (p < 1) raf = requestAnimationFrame(tick);
      else fromRef.current = to;
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [visible]);

  const pad = (n) => n.toString().padStart(2, '0');
  return (
    <div style={{
      border: `2px solid ${colors.ink}`,
      padding: '10px 18px',
      display: 'flex', alignItems: 'baseline', gap: 8,
      fontFamily: "'Archivo Black', sans-serif",
      lineHeight: .9, letterSpacing: '-0.04em',
      fontVariantNumeric: 'tabular-nums',
    }}>
      <span style={{ fontSize: 76, color: colors.ink }}>{pad(shown)}</span>
      <span style={{ fontSize: 60, color: colors.mute }}>/{pad(total)}</span>
    </div>
  );
}

// — SearchGlyph —
// Minimal magnifying-glass icon used in the search input.
function SearchGlyph({ color = '#16110d' }) {
  return (
    <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
      <circle cx="7" cy="7" r="5" stroke={color} strokeWidth="1.6" />
      <line x1="11" y1="11" x2="14.5" y2="14.5" stroke={color} strokeWidth="1.8" strokeLinecap="round" />
    </svg>
  );
}
