// My Events view. shows user's registrations

function MyEvents({ user, t, onBack, onSelectEvent, onSignOut }) {
  const [regs, setRegs] = React.useState(() => window.Auth.getRegistrationsForUser(user.email));

  const now = new Date();
  const enriched = regs.map(r => {
    const ev = window.EVENTS.find(e => e.id === r.eventId);
    return ev ? { ...r, event: ev, dateObj: new Date(ev.date + 'T00:00:00') } : null;
  }).filter(Boolean);

  const upcoming = enriched.filter(r => r.dateObj >= now && r.status === 'confirmed')
    .sort((a, b) => a.dateObj - b.dateObj);
  const past = enriched.filter(r => r.dateObj < now || r.status === 'cancelled')
    .sort((a, b) => b.dateObj - a.dateObj);

  const cancel = (regId) => {
    if (!window.confirm('Cancel this registration?')) return;
    window.Auth.cancelRegistration(regId);
    setRegs(window.Auth.getRegistrationsForUser(user.email));
  };

  return (
    <div style={{ background: t.bg, color: t.fg, minHeight: '100vh' }}>
      <div style={{ padding: '24px var(--gutter-x)', borderBottom: `1px solid ${t.line}` }}>
        <button onClick={onBack} style={{
          background: 'transparent', border: 'none', color: t.dim,
          fontFamily: 'Barlow, sans-serif', fontWeight: 300, fontSize: 11,
          letterSpacing: '0.2em', cursor: 'pointer', padding: 0,
        }}>◀ BACK TO CALENDAR</button>
      </div>

      <div style={{ padding: '48px var(--gutter-x)', maxWidth: 1200, margin: '0 auto' }}>
        <div style={{
          display: 'flex', justifyContent: 'space-between',
          alignItems: 'flex-end', marginBottom: 48,
          borderBottom: `1px solid ${t.lineStrong}`, paddingBottom: 28,
          flexWrap: 'wrap', gap: 16,
        }}>
          <div>
            <div style={{
              fontFamily: 'Barlow, sans-serif', fontWeight: 300, fontSize: 11,
              letterSpacing: '0.35em', color: t.brass, marginBottom: 10,
            }}>◉ OPERATOR DOSSIER</div>
            <div style={{
              fontFamily: 'Oswald, sans-serif', fontWeight: 700,
              fontSize: 'clamp(40px, 5vw, 64px)', color: t.fg,
              letterSpacing: '0.02em', lineHeight: 0.95, marginBottom: 10,
            }}>{user.name?.toUpperCase() || 'OPERATOR'}</div>
            <div style={{
              fontFamily: 'Barlow, sans-serif', fontWeight: 400, fontSize: 14,
              color: t.dim, letterSpacing: '0.05em',
            }}>{user.email}</div>
          </div>
          <button onClick={onSignOut} style={{
            padding: '10px 18px', background: 'transparent',
            border: `1px solid ${t.lineStrong}`, color: t.fg,
            fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 11,
            letterSpacing: '0.25em', cursor: 'pointer',
          }}>SIGN OUT</button>
        </div>

        {/* Stats */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 0, marginBottom: 56, border: `1px solid ${t.line}` }}>
          <StatCell label="UPCOMING" value={upcoming.length} t={t} />
          <StatCell label="COMPLETED" value={past.filter(r => r.status !== 'cancelled').length} t={t} />
          <StatCell label="TOTAL" value={regs.length} t={t} last />
        </div>

        <Section title="UPCOMING" t={t}>
          {upcoming.length === 0 ? (
            <EmptyState msg="No upcoming registrations. Hit the calendar." t={t} onBack={onBack} />
          ) : upcoming.map(r => (
            <RegCard key={r.id} reg={r} t={t}
              onClick={() => onSelectEvent(r.event)}
              onCancel={() => cancel(r.id)} />
          ))}
        </Section>

        {past.length > 0 && (
          <Section title="HISTORY" t={t}>
            {past.map(r => (
              <RegCard key={r.id} reg={r} t={t} past
                onClick={() => onSelectEvent(r.event)} />
            ))}
          </Section>
        )}
      </div>
    </div>
  );
}

function StatCell({ label, value, t, last }) {
  return (
    <div style={{
      padding: '24px 28px',
      borderRight: last ? 'none' : `1px solid ${t.line}`,
    }}>
      <div style={{
        fontFamily: 'Barlow, sans-serif', fontWeight: 300, fontSize: 10,
        letterSpacing: '0.3em', color: t.dim, marginBottom: 8,
      }}>{label}</div>
      <div style={{
        fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 40,
        color: t.fg, letterSpacing: '0.02em', lineHeight: 1,
      }}>{String(value).padStart(2, '0')}</div>
    </div>
  );
}

function Section({ title, children, t }) {
  return (
    <div style={{ marginBottom: 48 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 20 }}>
        <span style={{
          fontFamily: 'Barlow, sans-serif', fontWeight: 600, fontSize: 11,
          letterSpacing: '0.35em', color: t.brass,
        }}>{title}</span>
        <span style={{ flex: 1, height: 1, background: t.lineStrong }} />
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>{children}</div>
    </div>
  );
}

function RegCard({ reg, t, past, onClick, onCancel }) {
  const ev = reg.event;
  const date = reg.dateObj.toLocaleDateString('en-US', {
    weekday: 'short', month: 'short', day: 'numeric',
  }).toUpperCase();
  const cancelled = reg.status === 'cancelled';

  // Track viewport width so we can restack the card on phones where the
  // default 3-column grid pushes the CANCEL button off-screen.
  const [narrow, setNarrow] = React.useState(
    typeof window !== 'undefined' && window.matchMedia('(max-width: 768px)').matches
  );
  React.useEffect(() => {
    const mq = window.matchMedia('(max-width: 768px)');
    const handler = (e) => setNarrow(e.matches);
    if (mq.addEventListener) mq.addEventListener('change', handler);
    else mq.addListener(handler);
    return () => {
      if (mq.removeEventListener) mq.removeEventListener('change', handler);
      else mq.removeListener(handler);
    };
  }, []);

  return (
    <div style={{
      display: narrow ? 'flex' : 'grid',
      flexDirection: narrow ? 'column' : undefined,
      gridTemplateColumns: narrow ? undefined : '100px 1fr auto',
      gap: narrow ? 14 : 24,
      alignItems: narrow ? 'stretch' : 'center',
      padding: narrow ? '18px 18px' : '22px 24px',
      background: t.cellBg, border: `1px solid ${t.line}`,
      opacity: past || cancelled ? 0.6 : 1,
      cursor: 'pointer', transition: 'border-color 0.15s, background 0.15s',
    }}
      onClick={onClick}
      onMouseEnter={(e) => { e.currentTarget.style.borderColor = t.brass; }}
      onMouseLeave={(e) => { e.currentTarget.style.borderColor = t.line; }}
    >
      <div>
        <div style={{
          fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 18,
          color: t.brass, letterSpacing: '0.05em', lineHeight: 1,
        }}>{date}</div>
        <div style={{
          fontFamily: 'Barlow, sans-serif', fontWeight: 400, fontSize: 11,
          color: t.dim, letterSpacing: '0.1em', marginTop: 4,
        }}>{ev.time}</div>
      </div>
      <div>
        <div style={{
          fontFamily: 'Barlow, sans-serif', fontWeight: 300, fontSize: 10,
          letterSpacing: '0.3em', color: t.dim, marginBottom: 4,
        }}>{ev.tag} · {ev.type.toUpperCase()}</div>
        <div style={{
          fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 20,
          color: t.fg, letterSpacing: '0.02em', lineHeight: 1.15,
          textDecoration: cancelled ? 'line-through' : 'none',
        }}>{ev.title}</div>
        <div style={{
          fontFamily: 'Barlow, sans-serif', fontWeight: 400, fontSize: 13,
          color: t.dim, marginTop: 4,
        }}>{ev.location}</div>
      </div>
      <div style={{
        display: 'flex',
        alignItems: 'center',
        gap: 14,
        justifyContent: narrow ? 'space-between' : 'flex-end',
        paddingTop: narrow ? 10 : 0,
        borderTop: narrow ? `1px solid ${t.line}` : 'none',
      }}>
        <div style={{
          fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 10,
          letterSpacing: '0.3em',
          color: cancelled ? '#d06a4a' : (past ? t.dim : t.brass),
          padding: '6px 10px',
          border: `1px solid ${cancelled ? '#d06a4a' : (past ? t.lineStrong : t.brass)}`,
        }}>{cancelled ? 'CANCELLED' : (past ? 'ATTENDED' : 'CONFIRMED')}</div>
        {!past && !cancelled && (
          <button
            onClick={(e) => { e.stopPropagation(); onCancel(); }}
            style={{
              background: 'transparent', border: 'none', color: '#d06a4a',
              fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 11,
              letterSpacing: '0.25em', cursor: 'pointer', padding: 6,
            }}>CANCEL</button>
        )}
      </div>
    </div>
  );
}

function EmptyState({ msg, t, onBack }) {
  return (
    <div style={{
      padding: '48px 24px', textAlign: 'center',
      border: `1px dashed ${t.lineStrong}`, background: t.cellBg,
    }}>
      <div style={{
        fontFamily: 'Barlow, sans-serif', fontWeight: 400, fontSize: 14,
        color: t.dim, marginBottom: 18, letterSpacing: '0.05em',
      }}>{msg}</div>
      <button onClick={onBack} style={{
        padding: '10px 22px', background: t.brass, color: '#0F1114',
        border: 'none', fontFamily: 'Oswald, sans-serif', fontWeight: 700,
        fontSize: 11, letterSpacing: '0.3em', cursor: 'pointer',
      }}>VIEW CALENDAR</button>
    </div>
  );
}

window.MyEvents = MyEvents;
