// EventsPage.jsx — reads from EventsStore (Google Sheet) with seed fallback
const EventsPage = () => {
  useReveal();
  const store = useEventsStore();

  // Upcoming = not done, sorted by year then date
  const monthOrder = ['JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC'];
  const parseKey = (e) => {
    const m = (e.date || '').trim().slice(0, 3).toUpperCase();
    const d = parseInt((e.date || '').trim().slice(4)) || 0;
    const mi = monthOrder.indexOf(m);
    return (parseInt(e.year) || 0) * 10000 + (mi >= 0 ? mi : 99) * 100 + d;
  };
  const upcoming = store.events
    .filter(e => !e.done)
    .sort((a, b) => parseKey(a) - parseKey(b));

  const past = store.events
    .filter(e => e.done)
    .sort((a, b) => parseKey(b) - parseKey(a));

  const statusColor = (s) => {
    if (s === 'LOCKED IN') return 'var(--wbbq-slime)';
    if (s === 'TENTATIVE') return 'var(--wbbq-blue)';
    return 'var(--wbbq-flame)';
  };

  return (
    <>
      <PageHero eyebrow="Coming Attractions" title={<>The <span style={{ color: 'var(--wbbq-flame)' }}>Calendar.</span></>} subtitle="Where we'll be smoking meat for strangers and judges." mascot="flame.svg" />
      <section className="section">
        <div className="wrap">
          {store.loading && <div style={{ color: 'var(--fg3)', fontSize: 13, marginBottom: 16 }}>Loading…</div>}
          {upcoming.length === 0 && !store.loading && (
            <div style={{ padding: 40, textAlign: 'center', border: '2px dashed var(--border)', background: 'var(--wbbq-ink)', color: 'var(--fg2)' }}>
              No upcoming events. Hit the pit and check back.
            </div>
          )}
          <div style={{ display: 'grid', gap: 18 }}>
            {upcoming.map((e) => {
              const color = statusColor(e.status);
              const Wrap = e.url ? 'a' : 'div';
              const extra = e.url ? { href: e.url, target: '_blank', rel: 'noreferrer' } : {};
              return (
                <Wrap key={e.id} className="reveal event-row" {...extra} style={{
                  display: 'grid', gridTemplateColumns: '140px 1fr auto', gap: 30, alignItems: 'center',
                  background: 'var(--wbbq-ink)', border: '3px solid var(--border)',
                  padding: '22px 26px', textDecoration: 'none', color: 'var(--fg1)',
                  transition: 'all 220ms var(--ease-snap)', cursor: e.url ? 'pointer' : 'default',
                }}
                onMouseEnter={(ev) => { ev.currentTarget.style.borderColor = color; ev.currentTarget.style.transform = 'translate(-3px,-3px)'; ev.currentTarget.style.boxShadow = `6px 6px 0 ${color}`; }}
                onMouseLeave={(ev) => { ev.currentTarget.style.borderColor = 'var(--border)'; ev.currentTarget.style.transform = 'translate(0,0)'; ev.currentTarget.style.boxShadow = 'none'; }}
                >
                  <div style={{ borderRight: '2px solid var(--border)', paddingRight: 20 }}>
                    <div style={{ fontFamily: 'var(--font-display)', fontSize: 32, color, lineHeight: 0.9 }}>{e.date}</div>
                    <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--fg3)', marginTop: 4 }}>{e.year}</div>
                  </div>
                  <div>
                    <div style={{ fontFamily: 'var(--font-display)', fontSize: 22, color: 'var(--wbbq-bone)', letterSpacing: '0.02em' }}>{e.name}</div>
                    <div style={{ fontSize: 13, color: 'var(--fg2)', marginTop: 6, display: 'flex', gap: 16, flexWrap: 'wrap' }}>
                      <span>◉ {e.location}</span>
                      {e.category && <><span style={{ color: 'var(--fg3)' }}>·</span><span>{e.category}</span></>}
                    </div>
                  </div>
                  <div style={{ fontFamily: 'var(--font-display)', fontSize: 11, letterSpacing: '0.14em', padding: '6px 12px', border: `2px solid ${color}`, color }}>
                    {e.status}
                  </div>
                </Wrap>
              );
            })}
          </div>
          <div className="zine-card" style={{ marginTop: 48, padding: 32, textAlign: 'center' }}>
            <div className="eyebrow" style={{ color: 'var(--wbbq-slime)' }}>Want us at yours?</div>
            <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 28, color: 'var(--wbbq-bone)', margin: '10px 0 16px', letterSpacing: '0.02em' }}>Invite us. We bring fire.</h3>
            <a href="#/contact" className="btn btn-primary">Send A Signal →</a>
          </div>

          {past.length > 0 && (
            <div style={{ marginTop: 72 }}>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 20, marginBottom: 20 }}>
                <div className="eyebrow" style={{ color: 'var(--wbbq-slime)', fontSize: 12 }}>◉ The Rearview</div>
                <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 36, color: 'var(--wbbq-bone)', margin: 0, letterSpacing: '0.02em' }}>Past <span style={{ color: 'var(--wbbq-flame)' }}>Comps.</span></h2>
                <div style={{ flex: 1, height: 2, background: 'repeating-linear-gradient(90deg, var(--border) 0 8px, transparent 8px 14px)' }} />
                <a href="#/trophies" style={{ fontFamily: 'var(--font-display)', fontSize: 11, letterSpacing: '0.14em', color: 'var(--wbbq-flame)', textDecoration: 'none', border: '2px solid var(--wbbq-flame)', padding: '8px 14px' }}>See Scores →</a>
              </div>
              <div style={{ display: 'grid', gap: 10 }}>
                {past.map((e) => {
                  const tier = window.tierFor ? window.tierFor(e.place, 'overall') : null;
                  const placeColor = tier ? tier.color : 'var(--fg1)';
                  const hoverColor = tier ? tier.color : 'var(--wbbq-flame)';
                  return (
                    <a key={e.id} href="#/trophies" className="reveal past-row" style={{
                      display: 'grid', gridTemplateColumns: '110px 1fr auto auto', gap: 20, alignItems: 'center',
                      padding: '14px 20px', background: 'var(--wbbq-ink)', border: '1px solid var(--border)',
                      textDecoration: 'none', color: 'var(--fg1)', opacity: 0.88,
                      transition: 'opacity 160ms, border-color 160ms',
                    }}
                    onMouseEnter={(ev) => { ev.currentTarget.style.opacity = 1; ev.currentTarget.style.borderColor = hoverColor; }}
                    onMouseLeave={(ev) => { ev.currentTarget.style.opacity = 0.88; ev.currentTarget.style.borderColor = 'var(--border)'; }}
                    >
                      <div>
                        <div style={{ fontFamily: 'var(--font-display)', fontSize: 18, color: 'var(--fg2)' }}>{e.date}</div>
                        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg3)' }}>{e.year}</div>
                      </div>
                      <div>
                        <div style={{ fontFamily: 'var(--font-display)', fontSize: 16, color: 'var(--wbbq-bone)', letterSpacing: '0.02em' }}>{e.name}</div>
                        <div style={{ fontSize: 12, color: 'var(--fg3)', marginTop: 3 }}>◉ {e.location}{e.category ? ` · ${e.category}` : ''}</div>
                      </div>
                      <div style={{ fontFamily: 'var(--font-display)', fontSize: 18, color: placeColor, whiteSpace: 'nowrap', display: 'inline-flex', alignItems: 'center', gap: 8 }}>
                        {tier && tier.emoji && <span style={{ color: tier.color }}>{tier.emoji}</span>}
                        <span>
                          {window.formatPlace ? window.formatPlace(e.place) : (e.place || '—')}
                          {e.teams && /^\d+$/.test(String(e.place || '').trim()) && (
                            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg3)', marginLeft: 4 }}>/ {e.teams}</span>
                          )}
                        </span>
                        {tier && <window.TierPill tier={tier} />}
                      </div>
                      <div style={{ fontFamily: 'var(--font-mono)', fontSize: 13, color: 'var(--fg2)', minWidth: 56, textAlign: 'right' }}>
                        {e.score || '—'}
                      </div>
                    </a>
                  );
                })}
              </div>
            </div>
          )}
        </div>
      </section>
    </>
  );
};
window.EventsPage = EventsPage;

// ---------- TrophiesPage ----------
const TrophiesPage = () => {
  useReveal();
  const store = useEventsStore();

  // Trophies = done events, grouped by year desc, sorted within year by date desc
  const monthOrder = ['JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC'];
  const done = store.events.filter(e => e.done);

  const byYear = {};
  done.forEach(e => {
    const y = String(e.year || '—');
    (byYear[y] = byYear[y] || []).push(e);
  });
  const years = Object.keys(byYear).sort((a, b) => Number(b) - Number(a));
  years.forEach(y => {
    byYear[y].sort((a, b) => {
      const ma = monthOrder.indexOf((a.date || '').slice(0, 3).toUpperCase());
      const mb = monthOrder.indexOf((b.date || '').slice(0, 3).toUpperCase());
      return mb - ma;
    });
  });

  const totalComps = done.length;
  const gcCount = done.filter(e => {
    const t = window.tierFor && window.tierFor(e.place, 'overall');
    return t && (t.tier === 'gc' || t.tier === 'rookie');
  }).length;
  const rookieCount = done.filter(e => /rookie of/i.test(e.place || '')).length;
  const rgcCount = done.filter(e => {
    const t = window.tierFor && window.tierFor(e.place, 'overall');
    return t && t.tier === 'rgc';
  }).length;
  const meats = ['chicken','ribs','pork','brisket'];
  let callsCount = 0;
  done.forEach(e => {
    const t = window.tierFor && window.tierFor(e.place, 'overall');
    if (t && t.tier === 'call') callsCount++;
    if (e.results) {
      meats.forEach(m => {
        const r = e.results[m];
        if (!r) return;
        const mt = window.tierFor && window.tierFor(r.place, 'meat');
        if (mt && mt.tier === 'call') callsCount++;
      });
    }
  });

  return (
    <>
      <PageHero eyebrow="The Shelf" title={<>Trophy <span style={{ color: 'var(--wbbq-flame)' }}>Case.</span></>} subtitle="Objective proof that we are not, in fact, just shouting into the void." mascot="robot-cat-fish.svg" />
      <section className="section">
        <div className="wrap">
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: 20, marginBottom: 56 }}>
            {[
              { big: totalComps, small: 'Comps Cooked',        color: 'var(--wbbq-bone)',  sub: null },
              { big: gcCount,    small: 'Grand Champion',       color: 'var(--wbbq-flame)', sub: rookieCount ? `incl. ${rookieCount} rookie` : null },
              { big: rgcCount,   small: 'Reserve Grand Champion', color: 'var(--wbbq-slime)', sub: null },
              { big: callsCount, small: 'Calls',                 color: 'var(--wbbq-blue)',  sub: 'overall 3–10 + per-meat' },
            ].map((s) => (
              <div key={s.small} className="reveal" style={{
                background: 'var(--wbbq-ink)', border: `3px solid ${s.color}`,
                padding: '28px 24px', textAlign: 'center',
                boxShadow: '6px 6px 0 var(--wbbq-blue)',
              }}>
                <div style={{ fontFamily: 'var(--font-display)', fontSize: 64, color: s.color, lineHeight: 0.95 }}>{s.big}</div>
                <div style={{ fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--fg2)', fontWeight: 800, marginTop: 8 }}>{s.small}</div>
                {s.sub && <div style={{ fontSize: 10, letterSpacing: '0.1em', color: 'var(--fg3)', marginTop: 4, textTransform: 'uppercase' }}>{s.sub}</div>}
              </div>
            ))}
          </div>

          {years.length === 0 && (
            <div style={{ padding: 40, textAlign: 'center', border: '2px dashed var(--border)', background: 'var(--wbbq-ink)', color: 'var(--fg2)' }}>
              The case is empty. Go win something.
            </div>
          )}

          {years.map((y) => (
            <div key={y} className="reveal" style={{ marginBottom: 40 }}>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 20, marginBottom: 16 }}>
                <div style={{ fontFamily: 'var(--font-display)', fontSize: 56, color: 'var(--wbbq-blue)', lineHeight: 0.9 }}>{y}</div>
                <div style={{ flex: 1, height: 3, background: 'repeating-linear-gradient(90deg, var(--wbbq-flame) 0 10px, transparent 10px 18px)' }} />
              </div>
              {/* Column headers */}
              <div className="trophy-header" style={{
                display: 'grid', gridTemplateColumns: '150px 1fr 160px 140px', gap: 20,
                padding: '8px 20px 10px', fontFamily: 'var(--font-display)', fontSize: 10,
                letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--fg3)',
                borderBottom: '1px solid var(--border)',
              }}>
                <div>Finish</div>
                <div>Event</div>
                <div style={{ textAlign: 'right' }}>Category</div>
                <div style={{ textAlign: 'right' }}>Overall Score</div>
              </div>
              <div style={{ display: 'grid', gap: 10, marginTop: 10 }}>
                {byYear[y].map((w) => (
                  <TrophyRow key={w.id} w={w} />
                ))}
              </div>
            </div>
          ))}
        </div>
      </section>
    </>
  );
};
window.TrophiesPage = TrophiesPage;

// ---------- Trophy Row with expandable breakdown ----------
const TrophyRow = ({ w }) => {
  const [open, setOpen] = useState(false);
  const results = w.results || {};
  const ancillary = (w.ancillary || []).filter(a => a && (a.name || a.place || a.score));
  const meats = ['chicken','ribs','pork','brisket'];
  const hasMeatData = meats.some(m => results[m] && (results[m].place || results[m].score));
  const hasDetail = hasMeatData || ancillary.length > 0;

  const tier = window.tierFor ? window.tierFor(w.place, 'overall') : null;
  const placeColor = tier ? tier.color : 'var(--wbbq-bone)';

  return (
    <div style={{ background: 'var(--wbbq-ink)', border: '1px solid var(--border)' }}>
      <button
        type="button"
        onClick={() => hasDetail && setOpen(!open)}
        disabled={!hasDetail}
        className="trophy-row"
        style={{
          width: '100%', textAlign: 'left', cursor: hasDetail ? 'pointer' : 'default',
          background: 'transparent', border: 0, color: 'inherit',
          display: 'grid', gridTemplateColumns: '150px 1fr 160px 140px', gap: 20, alignItems: 'center',
          padding: '16px 20px',
          transition: 'background 120ms',
        }}
        onMouseEnter={(e) => { if (hasDetail) e.currentTarget.style.background = 'rgba(255,255,255,0.03)'; }}
        onMouseLeave={(e) => { e.currentTarget.style.background = 'transparent'; }}
      >
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
          {tier && tier.emoji && <span style={{ color: tier.color }}>{tier.emoji}</span>}
          <span style={{ fontFamily: 'var(--font-display)', fontSize: 20, color: placeColor, lineHeight: 1 }}>
            {formatPlace(w.place) || '—'}
          </span>
          {w.teams && (
            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg3)', marginLeft: 4 }}>
              / {w.teams} Teams
            </span>
          )}
          {tier && <window.TierPill tier={tier} />}
        </div>
        <div className="trophy-event" style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <span style={{ fontSize: 15, color: 'var(--fg1)' }}>{w.name}</span>
          {hasDetail && (
            <span style={{
              fontFamily: 'var(--font-display)', fontSize: 10, letterSpacing: '0.14em',
              color: 'var(--wbbq-slime)', border: '1px solid var(--wbbq-slime)',
              padding: '2px 6px', textTransform: 'uppercase',
            }}>
              {open ? '− Details' : '+ Details'}
            </span>
          )}
        </div>
        <div className="trophy-cat" style={{ textAlign: 'right', fontFamily: 'var(--font-body)', fontSize: 12, color: 'var(--wbbq-slime)', fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase' }}>
          {w.category || '—'}
        </div>
        <div className="trophy-score" style={{ textAlign: 'right', fontFamily: 'var(--font-mono)', fontSize: 16, color: 'var(--fg1)' }}>
          {w.score || '—'}
        </div>
      </button>

      {open && hasDetail && (
        <div style={{
          padding: '18px 22px 22px', borderTop: '1px dashed var(--border)',
          background: 'var(--wbbq-black)',
        }}>
          {hasMeatData && (
            <>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 11, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--wbbq-flame)', marginBottom: 10 }}>
                The Four Meat Masters
              </div>
              <div style={{ display: 'grid', gap: 6 }}>
                {meats.map(meat => {
                  const r = results[meat];
                  if (!r || (!r.place && !r.score)) {
                    return (
                      <div key={meat} className="trophy-detail-row" style={rowStyle()}>
                        <div style={meatLabel()}>{meat}</div>
                        <div style={{ color: 'var(--fg3)', fontStyle: 'italic', fontSize: 12 }}>—</div>
                        <div />
                      </div>
                    );
                  }
                  const pn = parseInt(String(r.place).trim(), 10);
                  const meatTier = window.tierFor ? window.tierFor(r.place, 'meat') : null;
                  const meatColor = (Number.isFinite(pn) && pn <= 3) ? 'var(--wbbq-flame)' : (meatTier ? meatTier.color : 'var(--wbbq-bone)');
                  return (
                    <div key={meat} className="trophy-detail-row" style={rowStyle()}>
                      <div style={meatLabel()}>{meat}</div>
                      <div style={{ fontFamily: 'var(--font-display)', fontSize: 18, color: meatColor, display: 'inline-flex', alignItems: 'center', gap: 8 }}>
                        <span>
                          {formatPlace(r.place) || '—'}
                          {w.teams && r.place && /^\d+$/.test(String(r.place).trim()) && (
                            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg3)', marginLeft: 6 }}>/ {w.teams}</span>
                          )}
                        </span>
                        {meatTier && <window.TierPill tier={meatTier} />}
                      </div>
                      <div style={{ textAlign: 'right', fontFamily: 'var(--font-mono)', fontSize: 14, color: 'var(--fg1)' }}>
                        {r.score || '—'}
                      </div>
                    </div>
                  );
                })}
              </div>
            </>
          )}

          {ancillary.length > 0 && (
            <>
              <div style={{
                fontFamily: 'var(--font-display)', fontSize: 11, letterSpacing: '0.16em', textTransform: 'uppercase',
                color: 'var(--wbbq-blue)', marginBottom: 10,
                marginTop: hasMeatData ? 24 : 0,
                paddingTop: hasMeatData ? 20 : 0,
                borderTop: hasMeatData ? '1px dashed var(--border)' : 'none',
              }}>
                Ancillary
              </div>
              <div style={{ display: 'grid', gap: 6 }}>
                {ancillary.map((a, i) => {
                  const apn = parseInt(String(a.place).trim(), 10);
                  const ancTier = window.tierFor ? window.tierFor(a.place, 'meat') : null;
                  const ancColor = (Number.isFinite(apn) && apn <= 3) ? 'var(--wbbq-flame)' : (ancTier ? ancTier.color : 'var(--wbbq-bone)');
                  return (
                    <div key={i} className="trophy-detail-row" style={rowStyle()}>
                      <div style={meatLabel()}>{a.name || '—'}</div>
                      <div style={{ fontFamily: 'var(--font-display)', fontSize: 18, color: ancColor, display: 'inline-flex', alignItems: 'center', gap: 8 }}>
                        <span>
                          {formatPlace(a.place) || '—'}
                          {a.teams && a.place && /^\d+$/.test(String(a.place).trim()) && (
                            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg3)', marginLeft: 6 }}>/ {a.teams}</span>
                          )}
                        </span>
                        {ancTier && <window.TierPill tier={ancTier} />}
                      </div>
                      <div style={{ textAlign: 'right', fontFamily: 'var(--font-mono)', fontSize: 14, color: 'var(--fg1)' }}>
                        {a.score || '—'}
                      </div>
                    </div>
                  );
                })}
              </div>
            </>
          )}
        </div>
      )}
    </div>
  );
};

const rowStyle = () => ({
  display: 'grid', gridTemplateColumns: '120px 1fr 100px', gap: 14, alignItems: 'baseline',
  padding: '6px 0',
});
const meatLabel = () => ({
  fontFamily: 'var(--font-display)', fontSize: 13, letterSpacing: '0.1em',
  textTransform: 'uppercase', color: 'var(--wbbq-slime)',
});

window.TrophyRow = TrophyRow;
