// Confirmation page — shown after a successful POST /api/signup. Reads
// confirmation details from `ctx` (set by the Waiver step) and the event from
// the events store. Calendar export is generated client-side: Google Calendar
// uses a URL template, Apple gets a blob-URL ICS download.

const Confirm = ({ ctx, setCtx, go, event }) => {
  const fullName = `${ctx.first || 'Candidate'} ${ctx.last || ''}`.trim();
  const careers = Array.isArray(ctx.careers) ? ctx.careers : (ctx.career ? [ctx.career] : []);
  const careerLabel = careers.length === 0
    ? '—'
    : careers.map(code => {
        const c = CAREER_FIELDS.find(cf => cf.code === code);
        return c ? c.code : code;
      }).join(' · ');
  const [resources] = useResources();

  // Build the calendar payload once. Both buttons consume `cal`.
  const cal = buildCalendarPayload(event, ctx, fullName);

  return (
    <div style={{ maxWidth: 980, margin: '0 auto', padding: '8px 32px 64px', position: 'relative' }}>
      <Watermark size={1080} opacity={0.10} style={{ backgroundPosition: 'center 50%' }} />
      {/* Hero confirmation */}
      <div style={{ position: 'relative', marginTop: 12 }}>
        <TerrainSlot h={280}>
          <CornerStamp time="0600 LOCAL" place={`${event.city}, ${event.state}`} />
          <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg, rgba(14,14,16,0.3) 0%, rgba(14,14,16,0.95) 100%)' }} />
          <div style={{ position: 'absolute', inset: 0, padding: '40px 32px 28px', display: 'flex', flexDirection: 'column', justifyContent: 'flex-end' }}>
            <Mono size={11} color={T.gold} style={{ display: 'block' }}>// REGISTRATION CONFIRMED</Mono>
            <Bebas size={96} style={{ marginTop: 10, lineHeight: 0.85, display: 'block' }}>YOU'RE IN.</Bebas>
            <Mono size={12} color={T.bone} style={{ marginTop: 10, display: 'block' }}>{ctx.confirmNum || 'AFSW-XXX-XXXX'}</Mono>
          </div>
        </TerrainSlot>
      </div>

      {/* Dossier grid */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 24, marginTop: 28 }}>
        <div style={{ border: `1px solid ${T.rule}`, padding: 24 }}>
          <Mono size={10} color={T.gold} style={{ display: 'block' }}>// EVENT DOSSIER</Mono>
          <Bebas size={32} style={{ marginTop: 8, display: 'block' }}>{event.city}, {event.state}</Bebas>
          <Mono size={11} color={T.bone} style={{ display: 'block', marginTop: 6 }}>{event.date} · {event.startTime || '0600'} LOCAL</Mono>
          <Mono size={11} color={T.mute} style={{ display: 'block', marginTop: 4 }}>{event.venue}</Mono>
          <Body size={12} color={T.mute} style={{ display: 'block', marginTop: 10 }}>
            Final time and address sent via email when finalized.
          </Body>
          <div style={{ display: 'flex', gap: 10, marginTop: 18, flexWrap: 'wrap' }}>
            {/* Single calendar button — the .ics file works in Apple Calendar
                (auto-imports on iOS / macOS), Google Calendar (download +
                drop into calendar.google.com or open on Android), Outlook,
                and every other major calendar app. */}
            <a
              href={icsUrl(ctx.confirmNum)}
              style={{
                display: 'inline-block',
                padding: '12px 22px',
                background: T.blue2,
                color: T.bone,
                fontFamily: "'Bebas Neue',sans-serif",
                fontSize: 14,
                letterSpacing: 1.2,
                textDecoration: 'none',
                border: `1px solid ${T.blue2}`,
              }}
            >+ Add to calendar</a>
          </div>
        </div>

        <div style={{ border: `1px solid ${T.rule}`, padding: 24 }}>
          <Mono size={10} color={T.mute} style={{ display: 'block' }}>// CANDIDATE</Mono>
          <Bebas size={28} style={{ marginTop: 8, display: 'block' }}>{fullName}</Bebas>
          <div style={{ marginTop: 14, display: 'flex', flexDirection: 'column', gap: 8 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
              <Mono size={10} color={T.mute}>CAREER</Mono>
              <Mono size={11} color={T.gold}>{careerLabel}</Mono>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
              <Mono size={10} color={T.mute}>EMAIL</Mono>
              <Mono size={11} color={T.bone}>{ctx.email}</Mono>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
              <Mono size={10} color={T.mute}>PHONE</Mono>
              <Mono size={11} color={T.bone}>{ctx.phone}</Mono>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
              <Mono size={10} color={T.mute}>WAIVER</Mono>
              <Mono size={11} color={T.gold}>✓ SIGNED</Mono>
            </div>
          </div>
        </div>
      </div>

      {/* Resources */}
      {resources.length > 0 && (
        <div style={{ marginTop: 28, border: `1px solid ${T.rule}`, padding: 24 }}>
          <Mono size={10} color={T.gold} style={{ display: 'block' }}>// RESOURCES</Mono>
          <div style={{ marginTop: 14, display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14 }}>
            {resources.map(f => (
              <a
                key={f.id}
                href={f.downloadUrl}
                target="_blank"
                rel="noopener noreferrer"
                style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: 14, border: `1px solid ${T.rule}`, background: 'transparent', color: T.bone, cursor: 'pointer', textDecoration: 'none' }}
              >
                <div style={{ textAlign: 'left' }}>
                  <Body size={13} color={T.bone}>{f.name}</Body>
                  <Mono size={9} color={T.mute} style={{ display: 'block', marginTop: 2 }}>{(f.type || '').includes('pdf') ? 'PDF' : 'FILE'} · {formatFileSize(f.size)}</Mono>
                </div>
                <Mono size={14} color={T.gold}>↓</Mono>
              </a>
            ))}
          </div>
        </div>
      )}

      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 36 }}>
        <Mono size={11} color={T.mute}>Confirmation sent to {ctx.email}.</Mono>
        <button onClick={() => go('landing')} style={{ background: 'transparent', border: 'none', color: T.bone, fontFamily: "'Bebas Neue',sans-serif", fontSize: 14, letterSpacing: 1, cursor: 'pointer' }}>
          ← Back to events
        </button>
      </div>
    </div>
  );
};

// ── Calendar helpers ─────────────────────────────────────────────────────
//
// We build both formats off the same payload: the event date is a string
// like "11 JUL 2026" and the start time is "0600". Duration defaults to 8 h
// since training day is a full-day event. End time is computed in local
// time — the user's calendar app will treat it as floating local.

const MONTHS = { JAN:0, FEB:1, MAR:2, APR:3, MAY:4, JUN:5, JUL:6, AUG:7, SEP:8, OCT:9, NOV:10, DEC:11 };

function parseEventStart(event) {
  const m = (event.date || '').trim().split(/\s+/);                  // ["11","JUL","2026"]
  const day = parseInt(m[0], 10);
  const month = MONTHS[(m[1] || '').toUpperCase()];
  const year = parseInt(m[2], 10);
  if (!Number.isFinite(day) || month === undefined || !Number.isFinite(year)) return null;
  const t = (event.startTime || '0600').padStart(4, '0');
  const hh = parseInt(t.slice(0, 2), 10) || 6;
  const mm = parseInt(t.slice(2, 4), 10) || 0;
  return new Date(year, month, day, hh, mm, 0);
}

function buildCalendarPayload(event, ctx, fullName) {
  const start = parseEventStart(event) || new Date();
  const end = new Date(start.getTime() + 8 * 60 * 60 * 1000);          // +8h
  const title = `SW Training Day · ${event.city}, ${event.state}`;
  const location = [event.venue, event.address].filter(Boolean).join(', ');
  const details = [
    `Confirmation: ${ctx.confirmNum || 'AFSW-XXXX'}`,
    `Candidate: ${fullName}`,
    '',
    'Final logistics will be emailed before the event. Reply to the confirmation email if anything changes.',
  ].join('\\n');

  const fmtUtc = (d) => d.toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '');
  const dates = `${fmtUtc(start)}/${fmtUtc(end)}`;

  const params = new URLSearchParams({
    action: 'TEMPLATE',
    text: title,
    dates,
    details: details.replace(/\\n/g, '\n'),
    location,
  });

  return {
    title,
    location,
    details,
    start,
    end,
    googleUrl: `https://www.google.com/calendar/render?${params.toString()}`,
    confirmNum: ctx.confirmNum || 'AFSW-XXXX',
  };
}

// Backend serves the ICS with Content-Type: text/calendar so iOS Safari
// opens the Calendar import sheet directly (Blob URLs save to Files
// instead, which is the bug we hit on phones). Desktop browsers download
// the file and offer to open with the user's calendar app, same UX.
function icsUrl(confirmNum) {
  if (!confirmNum) return '#';
  return `${window.api.API_BASE_URL}/api/ical/${encodeURIComponent(confirmNum)}.ics`;
}

window.Confirm = Confirm;
window.buildCalendarPayload = buildCalendarPayload;
window.icsUrl = icsUrl;
