---
import AppLayout from '../layouts/AppLayout.astro';
import AvatarPile from '../components/AvatarPile.astro';
import {
  getUpcomingEvents, getPastEvents, getEventBySlug, getEventAttendees,
  getEventRsvpCount, getUserRsvp, setEventRsvp, recordActivity,
} from '../lib/db';
import { eventKindLabel, defaultActionLabel, pigmentForId } from '../lib/format';

const user = Astro.locals.user;

// ── POST: RSVP ──────────────────────────────────────────────────────
if (Astro.request.method === 'POST') {
  const data = await Astro.request.formData();
  const action = String(data.get('action') ?? '');
  if (action === 'rsvp') {
    const slug = String(data.get('event_slug') ?? '');
    const status = String(data.get('status') ?? '') as 'yes' | 'no' | 'interested';
    if (slug && ['yes', 'no', 'interested'].includes(status)) {
      const ev = getEventBySlug(slug);
      if (ev) {
        setEventRsvp(user.id, slug, status);
        recordActivity(user.id, 'rsvped', 'event', ev.id);
      }
    }
    return Astro.redirect('/events');
  }
}

// ── Data ───────────────────────────────────────────────────────────
const upcoming = getUpcomingEvents(20);
const hero = upcoming.find(e => e.kind !== 'office_hours') ?? null;
const alsoUpcoming = upcoming.filter(e => e.id !== hero?.id);
const past = getPastEvents(8);

function parseUtc(s: string): Date {
  if (/T.*[Zz]$/.test(s) || /[+-]\d{2}:?\d{2}$/.test(s)) return new Date(s);
  return new Date(s.replace(' ', 'T') + 'Z');
}

function fmt(part: Intl.DateTimeFormatOptions, iso: string): string {
  return new Intl.DateTimeFormat('en-GB', { ...part, timeZone: 'Europe/Copenhagen' }).format(parseUtc(iso));
}
function dayNum(iso: string)  { return fmt({ day: 'numeric' }, iso); }
function weekday(iso: string) { return fmt({ weekday: 'short' }, iso).toUpperCase(); }
function monthShort(iso: string) { return fmt({ month: 'short' }, iso).toUpperCase(); }
function timeStr(iso: string) { return fmt({ hour: '2-digit', minute: '2-digit', hour12: false }, iso); }

const heroAttendees = hero ? getEventAttendees(hero.slug, 'yes') : [];
const heroConfirmedCount = heroAttendees.length;
const heroMyRsvp = hero ? getUserRsvp(user.id, hero.slug) : null;
const heroAudience = hero?.audience ?? 'Members only';
---
<AppLayout title="Events" user={user}>
  <div class="page">

    <header class="head">
      <h1 class="head-title">Where the council gathers.</h1>
      <p class="head-sub">Dinners, working sessions, the occasional summit. Always small, always off the record.</p>
    </header>

    <!-- ── Hero invitation ─────────────────────────────────────── -->
    {hero ? (
      <article class="hero" aria-label={`Next up: ${hero.title}`}>
        <div class="hero-body">
          <div class="hero-date">
            <span class="hero-weekday">{weekday(hero.starts_at)}</span>
            <span class="hero-day">{dayNum(hero.starts_at)}</span>
            <span class="hero-month">{monthShort(hero.starts_at)}</span>
          </div>

          <div class="hero-detail">
            <h2 class="hero-title">{hero.title}</h2>
            <p class="hero-desc">{hero.description}</p>
            <p class="hero-meta">{hero.location}{hero.location && ' · '}{timeStr(hero.starts_at)}{hero.duration_label ? ` · ${hero.duration_label}` : ''}</p>
          </div>
        </div>

        <footer class="hero-foot">
          <div class="hero-foot-left">
            <span class="hero-foot-stat">
              {hero.capacity ? `${hero.capacity} seats · ` : ''}{heroConfirmedCount} confirmed
            </span>
            {heroAttendees.length > 0 && (
              <AvatarPile users={heroAttendees} max={5} size={22} borderColor="var(--ink)" />
            )}
          </div>

          <form method="POST" class="hero-foot-right">
            <input type="hidden" name="action" value="rsvp" />
            <input type="hidden" name="event_slug" value={hero.slug} />
            {heroMyRsvp === 'yes' ? (
              <>
                <span class="hero-confirmed">You're confirmed ✓</span>
                <button type="submit" name="status" value="no" class="hero-change">Change</button>
              </>
            ) : (
              <button type="submit" name="status" value="yes" class="hero-cta">Save your seat →</button>
            )}
          </form>
        </footer>
      </article>
    ) : (
      <article class="hero hero--empty">
        <p class="hero-empty-line">
          Nothing scheduled yet — when we have something, you'll be the first to know.
        </p>
      </article>
    )}

    <!-- ── Also coming up ──────────────────────────────────────── -->
    {alsoUpcoming.length > 0 && (
      <section class="also">
        <ul class="also-list">
          {alsoUpcoming.map(ev => (
            <li class="also-row">
              <div class="also-date">
                <span class="also-day">{dayNum(ev.starts_at)}</span>
                <span class="also-month">{monthShort(ev.starts_at)}</span>
              </div>
              <div class="also-body">
                <h3 class="also-title">{ev.title}</h3>
                <p class="also-meta">
                  {[ev.duration_label, ev.audience, ev.location].filter(Boolean).join(' · ')
                    || eventKindLabel(ev.kind)}
                </p>
              </div>
              <form method="POST" class="also-action-form">
                <input type="hidden" name="action" value="rsvp" />
                <input type="hidden" name="event_slug" value={ev.slug} />
                <button type="submit" name="status" value="yes" class="also-action">
                  {ev.action_label ?? defaultActionLabel(ev.kind)}
                </button>
              </form>
            </li>
          ))}
        </ul>
      </section>
    )}

    <!-- ── Past gatherings ─────────────────────────────────────── -->
    {past.length > 0 && (
      <section class="past">
        <ul class="past-grid">
          {past.map(ev => {
            const monthCode = monthShort(ev.starts_at);
            const attended = getEventRsvpCount(ev.slug).going;
            const hasNotes = !!ev.notes_url;
            const pigA = pigmentForId(ev.id);
            const pigB = pigmentForId(ev.id + 1);
            return (
              <li class="past-card">
                {ev.photo_url ? (
                  <img class="past-thumb" src={ev.photo_url} alt="" loading="lazy" />
                ) : hasNotes ? (
                  <a href={ev.notes_url!} class="past-thumb past-thumb--notes" aria-label="Read the notes">
                    <span class="past-thumb-month">{monthCode}</span>
                  </a>
                ) : (
                  <div
                    class="past-thumb past-thumb--gradient"
                    style={`background: linear-gradient(135deg, ${pigA.hex}, ${pigB.hex});`}
                    aria-hidden="true"
                  >
                    <span class="past-thumb-month">{monthCode}</span>
                  </div>
                )}
                <div class="past-text">
                  <h3 class="past-title">{ev.title}</h3>
                  <p class="past-meta">{fmt({ day: 'numeric', month: 'long', year: 'numeric' }, ev.starts_at)}{ev.location && ` · ${ev.location}`}</p>
                  <p class="past-foot label-sm">
                    {attended} attended · {hasNotes ? 'Notes shared' : 'No notes'}
                  </p>
                </div>
              </li>
            );
          })}
        </ul>
        <a href="/events/past" class="section-link">View all past gatherings →</a>
      </section>
    )}

  </div>
</AppLayout>

<style>
  .page {
    padding: var(--space-12) var(--space-20) var(--space-16);
    max-width: var(--content-max);
    margin: 0 auto;
    display: flex;
    flex-direction: column;
    gap: var(--space-10);
  }

  /* ── Head ─────────────────────────────────────────────────────── */
  .head { max-width: 46rem; }
  .head-eyebrow {
    letter-spacing: var(--tracking-wider);
    text-transform: uppercase;
    color: var(--on-surface-variant);
    margin-bottom: var(--space-3);
  }
  .head-title {
    font-family: var(--font-serif);
    font-weight: 400;
    font-size: var(--text-display-md);
    letter-spacing: var(--tracking-tight);
    line-height: var(--leading-tight);
    color: var(--on-surface);
    margin: 0;
  }

  .head-sub {
    color: var(--on-surface-variant);
    margin-top: var(--space-3);
    max-width: 32rem;
  }

  /* ── Hero ─────────────────────────────────────────────────────── */
  .hero {
    background: var(--ink);
    color: var(--on-ink);
    border-radius: var(--radius-lg);
    padding: 1.75rem;
    display: flex;
    flex-direction: column;
    gap: var(--space-5);
  }

  .hero-top {
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: var(--on-ink-muted);
  }
  .hero-eyebrow {
    font-family: var(--font-sans);
    font-size: var(--text-label-sm);
    letter-spacing: var(--tracking-wider);
    text-transform: uppercase;
  }

  .hero-body {
    display: grid;
    grid-template-columns: 100px 1fr;
    gap: var(--space-6);
    padding: var(--space-4) 0;
    border-left: 0 solid transparent;
    position: relative;
  }
  .hero-body::after {
    content: '';
    position: absolute;
    left: 100px;
    top: 0; bottom: 0;
    width: 0.5px;
    background: var(--ink-divider);
  }

  .hero-date { display: flex; flex-direction: column; gap: 2px; }
  .hero-weekday, .hero-month {
    font-family: var(--font-sans);
    font-size: var(--text-label-sm);
    letter-spacing: var(--tracking-wider);
    text-transform: uppercase;
    color: var(--on-ink);
  }
  .hero-day {
    font-family: var(--font-serif);
    font-size: 2.75rem;
    line-height: 1;
    color: var(--on-ink);
  }

  .hero-detail { padding-left: var(--space-5); }
  .hero-title {
    font-family: var(--font-serif);
    font-weight: 400;
    font-size: 1.75rem;
    line-height: 1.2;
    color: var(--on-ink);
    margin: 0 0 var(--space-3);
  }
  .hero-desc {
    color: var(--on-ink-body);
    margin: 0 0 var(--space-3);
    max-width: 40rem;
  }
  .hero-meta {
    color: var(--on-ink-muted);
    font-size: var(--text-body-sm);
    margin: 0;
  }

  .hero-foot {
    border-top: 0.5px solid var(--ink-divider);
    padding-top: var(--space-4);
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: var(--space-4);
    flex-wrap: wrap;
  }
  .hero-foot-left { display: flex; align-items: center; gap: var(--space-4); }
  .hero-foot-stat {
    color: var(--on-ink-muted);
    font-family: var(--font-sans);
    font-size: var(--text-label-sm);
    letter-spacing: var(--tracking-wider);
    text-transform: uppercase;
  }
  .hero-foot-right { display: flex; align-items: center; gap: var(--space-3); }

  .hero-cta {
    background: var(--on-ink);
    color: var(--ink);
    border: none;
    padding: 10px 20px;
    border-radius: 999px;
    font-family: var(--font-sans);
    font-size: var(--text-label-md);
    font-weight: 600;
    letter-spacing: var(--tracking-wide);
    text-transform: uppercase;
    cursor: pointer;
    transition: opacity var(--duration-fast) var(--ease-standard);
  }
  .hero-cta:hover { opacity: 0.85; }

  .hero-confirmed {
    color: var(--on-ink);
    font-family: var(--font-sans);
    font-size: var(--text-label-md);
    font-weight: 600;
    letter-spacing: var(--tracking-wide);
    text-transform: uppercase;
    padding: 10px 16px;
    border: 0.5px solid rgba(255, 252, 247, 0.4);
    border-radius: 999px;
  }
  .hero-change {
    background: transparent;
    border: none;
    color: var(--on-ink-muted);
    font-family: var(--font-sans);
    font-size: var(--text-label-sm);
    letter-spacing: var(--tracking-wide);
    text-transform: uppercase;
    cursor: pointer;
    text-decoration: underline;
  }

  .hero--empty {
    align-items: stretch;
    justify-content: center;
    text-align: center;
    min-height: 200px;
    display: flex;
  }
  .hero-empty-line {
    color: var(--on-ink);
    font-family: var(--font-serif);
    font-size: 1.25rem;
    margin: auto;
    max-width: 32rem;
  }

  /* ── Section eyebrow shared ──────────────────────────────────── */
  .section-eyebrow {
    letter-spacing: var(--tracking-wider);
    text-transform: uppercase;
    color: var(--on-surface-variant);
    margin-bottom: var(--space-4);
  }

  /* ── Also coming up ──────────────────────────────────────────── */
  .also-list { list-style: none; padding: 0; margin: 0; }
  .also-row {
    display: grid;
    grid-template-columns: 70px 1fr 110px;
    gap: var(--space-4);
    align-items: center;
    padding: var(--space-4) 0;
    border-bottom: 0.5px solid var(--surface-card-border);
  }
  .also-row:last-child { border-bottom: none; }

  .also-date {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
  }
  .also-day {
    font-family: var(--font-serif);
    font-size: 1.5rem;
    line-height: 1;
    color: var(--on-surface);
  }
  .also-month {
    font-family: var(--font-sans);
    font-size: var(--text-label-sm);
    letter-spacing: var(--tracking-wider);
    text-transform: uppercase;
    color: var(--on-surface-muted);
    margin-top: 4px;
  }

  .also-body { display: flex; flex-direction: column; gap: 4px; }
  .also-title {
    font-family: var(--font-serif);
    font-weight: 400;
    font-size: 1.0625rem;
    color: var(--on-surface);
    margin: 0;
  }
  .also-meta { font-size: 0.75rem; color: var(--on-surface-variant); margin: 0; }

  .also-action-form { justify-self: end; }
  .also-action {
    background: none;
    border: none;
    color: var(--pigment-terracotta);
    font-family: var(--font-sans);
    font-size: var(--text-label-md);
    font-weight: 500;
    letter-spacing: var(--tracking-wide);
    text-transform: uppercase;
    cursor: pointer;
    padding: 0;
  }
  .also-action:hover { opacity: 0.85; }

  /* ── Past gatherings ─────────────────────────────────────────── */
  .past-head {
    display: flex;
    justify-content: space-between;
    align-items: baseline;
    gap: var(--space-3);
  }
  .past-all {
    font-family: var(--font-sans);
    font-size: var(--text-label-sm);
    letter-spacing: var(--tracking-wide);
    text-transform: uppercase;
    color: var(--pigment-terracotta);
    text-decoration: none;
    border-bottom: none;
  }
  .past-all:hover { opacity: 0.85; border-bottom: none; }

  .past-grid {
    list-style: none;
    padding: 0;
    margin: 0;
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: var(--space-5);
  }
  .past-card {
    display: grid;
    grid-template-columns: 56px 1fr;
    gap: var(--space-4);
    align-items: start;
  }
  .past-thumb {
    width: 56px;
    height: 56px;
    border-radius: var(--radius-md);
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
    text-decoration: none;
    border: none;
  }
  .past-thumb--notes {
    background: color-mix(in oklab, var(--pigment-copper) 18%, transparent);
    color: var(--pigment-copper);
  }
  .past-thumb-month {
    font-family: var(--font-sans);
    font-size: var(--text-label-sm);
    letter-spacing: var(--tracking-wider);
    text-transform: uppercase;
    font-weight: 600;
    color: rgba(250, 246, 238, 0.6);
  }
  .past-thumb--notes .past-thumb-month { color: var(--pigment-copper); }

  .past-text { display: flex; flex-direction: column; gap: 4px; min-width: 0; }
  .past-title {
    font-family: var(--font-serif);
    font-weight: 400;
    font-size: 1.0625rem;
    color: var(--on-surface);
    margin: 0;
  }
  .past-meta { font-size: 0.75rem; color: var(--on-surface-variant); margin: 0; }
  .past-foot {
    color: var(--on-surface-muted);
    letter-spacing: var(--tracking-wide);
    margin: 0;
  }

  @media (max-width: 720px) {
    .page { padding: var(--space-8) var(--space-5) var(--space-12); }
    .hero-body { grid-template-columns: 1fr; }
    .hero-body::after { display: none; }
    .past-grid { grid-template-columns: 1fr; }
    .also-row { grid-template-columns: 60px 1fr; }
    .also-action-form { grid-column: 1 / -1; justify-self: start; padding-top: var(--space-2); }
  }
</style>
