// ── JT Atelier — public Collections landing (the rotating drops) ─────────
// Nav item "Collections". Distinct from collection.jsx (shop-all): this surfaces
// the Atelier Backroom drops via the gated /api/collections endpoint —
// public sees in-window drops + "members get early access" teasers; members
// see everything (early + archive).
//
// Two views in one component, switched by `slug` (from /collections/:slug):
//   • list view   — grid of collection cards (hero image, title, blurb)
//   • detail view — catalog grid of that collection's pieces
//
// LATER (owner note): give each drop a scroll-through video intro like the
// home-page deck flow (deck.jsx) — layered on top of this screen. Not built yet.

function CollectionCard({ c, onOpen }) {
  const img = c.hero_image || (c.products && c.products[0] && c.products[0].image) || null;
  const count = c.locked ? null : (c.products || []).length;
  return (
    <div className="fade-up" onClick={onOpen} style={{ cursor: 'pointer' }}>
      <div style={{
        aspectRatio: '4/5', overflow: 'hidden', position: 'relative',
        background: 'var(--surface)', marginBottom: 16,
      }}>
        {img ? (
          <img src={img} alt={c.title} loading="lazy"
            style={{ width: '100%', height: '100%', objectFit: 'cover', transition: 'transform .5s ease' }}
            onMouseEnter={(e) => e.currentTarget.style.transform = 'scale(1.04)'}
            onMouseLeave={(e) => e.currentTarget.style.transform = 'scale(1)'} />
        ) : (
          <div style={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <span className="display" style={{ fontSize: 32, fontStyle: 'italic', color: 'var(--fg-3)' }}>{c.title}</span>
          </div>
        )}
        {c.locked && (
          <div style={{
            position: 'absolute', top: 12, left: 12, padding: '5px 10px',
            background: 'rgba(0,0,0,.55)', backdropFilter: 'blur(6px)',
            fontSize: 9, letterSpacing: '.14em', textTransform: 'uppercase', color: '#c6a86b',
          }}>
            {c.reason === 'coming_soon' ? 'Dropping soon' : 'Members only'}
          </div>
        )}
        {!c.locked && c.member_only_view && (
          <div style={{
            position: 'absolute', top: 12, left: 12, padding: '5px 10px',
            background: 'rgba(0,0,0,.55)', backdropFilter: 'blur(6px)',
            fontSize: 9, letterSpacing: '.14em', textTransform: 'uppercase', color: '#c6a86b',
          }}>
            Member early access
          </div>
        )}
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 10 }}>
        <h2 className="display" style={{ fontSize: 22, fontStyle: 'italic', fontWeight: 400, margin: 0 }}>{c.title}</h2>
        {count != null && <span className="mono" style={{ fontSize: 10, color: 'var(--fg-3)', flexShrink: 0 }}>{count} piece{count === 1 ? '' : 's'}</span>}
      </div>
      {c.description && <p style={{ fontSize: 13, color: 'var(--fg-3)', lineHeight: 1.6, margin: '6px 0 0' }}>{c.description}</p>}
      <div className="mono" style={{ fontSize: 10, letterSpacing: '.12em', textTransform: 'uppercase', color: 'var(--fg-2)', marginTop: 10 }}>
        {c.locked ? (c.reason === 'coming_soon' ? 'Coming soon' : 'Join to view') : 'View collection'} <span className="arrow">→</span>
      </div>
    </div>
  );
}

function CollectionDetail({ c, isMember, goTo, onBack, fmtUsd, makeBespoke, openProduct }) {
  return (
    <div>
      <button onClick={onBack} className="mono" style={{ fontSize: 11, letterSpacing: '.1em', color: 'var(--fg-3)', marginBottom: 28 }}>
        ← All collections
      </button>
      <div className="mono" style={{ fontSize: 10, letterSpacing: '.2em', color: 'var(--fg-3)', marginBottom: 12 }}>JT Atelier · Collection</div>
      <h1 className="display" style={{ fontSize: 'clamp(28px,5vw,52px)', fontStyle: 'italic', fontWeight: 400, lineHeight: 1.05, marginBottom: 14 }}>{c.title}.</h1>
      {c.description && <p style={{ fontSize: 14, color: 'var(--fg-3)', lineHeight: 1.7, maxWidth: 560, marginBottom: 20 }}>{c.description}</p>}
      {c.member_only_view && (
        <div className="mono" style={{ fontSize: 10, letterSpacing: '.14em', textTransform: 'uppercase', color: '#c6a86b', marginBottom: 30 }}>
          Member early access
        </div>
      )}

      {c.locked ? (
        <div style={{ border: '.5px solid var(--line-2)', padding: '56px 24px', textAlign: 'center', background: 'var(--surface)' }}>
          <div style={{ fontSize: 24, marginBottom: 12 }}>🔒</div>
          <p style={{ fontSize: 14, color: 'var(--fg-2)', margin: '0 0 20px' }}>
            {c.reason === 'coming_soon' ? 'Dropping soon — members get first access.' : 'Exclusive to Salon Privé members.'}
          </p>
          {c.reason !== 'coming_soon' && <button className="btn" onClick={() => goTo('account', { tab: 'membership' })} style={{ fontSize: 12 }}>Become a member →</button>}
        </div>
      ) : (c.products || []).length === 0 ? (
        <div style={{ padding: '60px 24px', border: '.5px solid var(--line-2)', textAlign: 'center' }}>
          <p style={{ fontSize: 14, color: 'var(--fg-3)', margin: 0 }}>No pieces in this collection yet. Check back soon.</p>
        </div>
      ) : (
        <div style={{
          display: 'grid', gridTemplateColumns: 'repeat(auto-fill,minmax(220px,1fr))', gap: 32,
        }}>
          {c.products.map((p) => (
            <div key={p.id}>
              <div onClick={() => openProduct(p)} style={{ cursor: 'pointer' }}>
                <div style={{ width: '100%', aspectRatio: '3/4', overflow: 'hidden', marginBottom: 12, background: 'var(--surface)' }}>
                  {p.image && <img src={p.image} alt={p.name} loading="lazy" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />}
                </div>
                <div style={{ fontSize: 13, color: 'var(--fg)', marginBottom: 4, lineHeight: 1.4 }}>{p.name}{p.exclusive ? <span style={{ color: '#c6a86b' }}> · exclusive</span> : null}</div>
                <div style={{ fontSize: 13, color: 'var(--fg-3)' }}>
                  {p.member_price != null && isMember
                    ? <><span style={{ color: '#c6a86b' }}>{fmtUsd(p.member_price)}</span> <span style={{ textDecoration: 'line-through', opacity: .6 }}>{fmtUsd(p.price)}</span></>
                    : fmtUsd(p.price)}
                </div>
              </div>
              <button onClick={() => makeBespoke(p)} style={{ marginTop: 10, width: '100%', background: 'none', border: '.5px solid var(--line-2)', color: 'var(--fg-2)', padding: '8px 0', fontSize: 10, letterSpacing: '.1em', textTransform: 'uppercase', cursor: 'pointer' }}>Make it bespoke</button>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

function SalonPriveModal({ open, onClose, goTo }) {
  return (
    <div className={`modal ${open ? 'on' : ''}`} onClick={onClose}>
      <div className="modal-card" onClick={(e) => e.stopPropagation()}>
        <button className="close-x" onClick={onClose}
          style={{ position: 'absolute', top: 12, right: 12 }} aria-label="Close">
          <svg width="18" height="18" viewBox="0 0 18 18" fill="none" stroke="currentColor" strokeWidth="1.3">
            <line x1="3" y1="3" x2="15" y2="15" />
            <line x1="15" y1="3" x2="3" y2="15" />
          </svg>
        </button>
        <div className="eyebrow" style={{ marginBottom: 18 }}>◇ &nbsp; Salon Privé</div>
        <h2 className="display" style={{ fontSize: 44, margin: 0, fontStyle: 'italic', fontWeight: 400 }}>
          Early access, <em>year-round.</em>
        </h2>
        <p style={{ fontSize: 14, lineHeight: 1.65, color: 'var(--fg-2)', marginTop: 18, marginBottom: 28, maxWidth: 420 }}>
          Members see every collection before the public window opens, and keep buying from the full archive year-round — long after a drop leaves the public site. $5/mo, cancel anytime.
        </p>
        <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
          <button className="btn" onClick={() => { onClose(); goTo('account', { tab: 'membership' }); }}>Join Salon Privé →</button>
          <button className="btn ghost" onClick={onClose}>Maybe later</button>
        </div>
      </div>
    </div>
  );
}

function CollectionsPage({ goTo, slug }) {
  useFadeUp();
  const [phase, setPhase]   = React.useState('loading');
  const [cols, setCols]     = React.useState([]);
  const [isMember, setMember] = React.useState(false);
  const [pitchOpen, setPitchOpen] = React.useState(false);

  React.useEffect(() => {
    (async () => {
      let headers = {};
      try { if (window.sb) { const { data } = await window.sb.auth.getSession(); if (data && data.session) headers.Authorization = 'Bearer ' + data.session.access_token; } } catch { /* anon */ }
      try {
        const r = await fetch('/api/collections?a=list', { headers });
        const d = await r.json();
        if (d && d.ok) { setCols(d.collections || []); setMember(!!d.member); }
      } catch { /* leave empty */ }
      setPhase('ready');
    })();
  }, []);

  // Pitch Salon Privé once per session, only on the collections list (not a
  // specific drop) and never to an existing member.
  React.useEffect(() => {
    if (phase !== 'ready' || slug || isMember) return;
    let seen = false;
    try { seen = sessionStorage.getItem('jta_salon_pitch_seen') === '1'; } catch { /* ignore */ }
    if (seen) return;
    const t = setTimeout(() => {
      setPitchOpen(true);
      try { sessionStorage.setItem('jta_salon_pitch_seen', '1'); } catch { /* ignore */ }
    }, 700);
    return () => clearTimeout(t);
  }, [phase, slug, isMember]);

  const fmtUsd = n => '$' + Number(n || 0).toLocaleString('en-US');
  const makeBespoke = (p) => {
    const full = ((window.PRODUCTS || window.products || []).find(x => x.id === p.id)) || p;
    if (typeof window.openBespoke === 'function') window.openBespoke({ product: full, category: p.category });
  };
  const openProduct = (p) => {
    const full = (window.PRODUCTS || window.products || []).find(x => x.id === p.id);
    if (full) goTo('product', { product: full });
  };

  if (phase === 'loading') {
    return <div style={{ minHeight: '60vh', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
      <span style={{ color: 'var(--fg-3)', fontSize: 12, letterSpacing: '.12em', textTransform: 'uppercase' }}>Loading…</span>
    </div>;
  }

  const active = slug ? cols.find(c => c.slug === slug) : null;

  return (
    <div style={{ maxWidth: 1100, margin: '0 auto', padding: 'clamp(60px,8vw,110px) 24px' }}>
      {active ? (
        <CollectionDetail c={active} isMember={isMember} goTo={goTo}
          onBack={() => goTo('collections')}
          fmtUsd={fmtUsd} makeBespoke={makeBespoke} openProduct={openProduct} />
      ) : slug ? (
        <div style={{ padding: '60px 24px', border: '.5px solid var(--line-2)', textAlign: 'center' }}>
          <p style={{ fontSize: 14, color: 'var(--fg-3)', margin: '0 0 20px' }}>That collection couldn't be found.</p>
          <button className="btn ghost sm" onClick={() => goTo('collections')}>← All collections</button>
        </div>
      ) : (
        <>
          <div className="mono" style={{ fontSize: 10, letterSpacing: '.2em', color: 'var(--fg-3)', marginBottom: 12 }}>JT Atelier</div>
          <h1 className="display" style={{ fontSize: 'clamp(28px,5vw,52px)', fontStyle: 'italic', fontWeight: 400, lineHeight: 1.05, marginBottom: 14 }}>Collections.</h1>
          <p style={{ fontSize: 14, color: 'var(--fg-3)', lineHeight: 1.7, maxWidth: 560, marginBottom: 44 }}>
            Limited collections, released through the year. {isMember
              ? 'As a Salon Privé member you have early and year-round access to everything below.'
              : 'Members of Salon Privé see each collection early — and keep access to the full archive year-round.'}
          </p>

          {!isMember && (
            <div style={{ border: '.5px solid var(--line-2)', padding: '20px 24px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 14, marginBottom: 44 }}>
              <div style={{ fontSize: 14, color: 'var(--fg-2)' }}>Get early + year-round access to every collection — $5/mo.</div>
              <button className="btn" onClick={() => goTo('account', { tab: 'membership' })} style={{ fontSize: 12 }}>Join Salon Privé →</button>
            </div>
          )}

          {cols.length === 0 ? (
            <div style={{ padding: '60px 24px', border: '.5px solid var(--line-2)', textAlign: 'center' }}>
              <p style={{ fontSize: 14, color: 'var(--fg-3)', margin: 0 }}>No collections are live right now. Check back soon.</p>
            </div>
          ) : (
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill,minmax(260px,1fr))', gap: '48px 32px' }}>
              {cols.map((c) => (
                <CollectionCard key={c.slug} c={c} onOpen={() => goTo('collections', { collectionSlug: c.slug })} />
              ))}
            </div>
          )}
        </>
      )}

      <SalonPriveModal open={pitchOpen} onClose={() => setPitchOpen(false)} goTo={goTo} />
    </div>
  );
}
