// Confirmation screen. tactical receipt style

const { useState: useStateC, useEffect: useEffectC } = React;

function Confirmation({ event, form, status, t, onBackToCalendar, waiverStatus, cancelToken }) {
  const [now] = useStateC(() => new Date());
  const [stamped, setStamped] = useStateC(false);

  // status comes from the backend: 'confirmed' (default) or 'waitlist'.
  // Waitlist means capacity was hit — candidate gets no OPORD, different copy.
  const isWaitlist = status === 'waitlist';

  useEffectC(() => {
    const tm = setTimeout(() => setStamped(true), 400);
    return () => clearTimeout(tm);
  }, []);

  const confNum = form._confNum || `PA-${event.id.slice(3).toUpperCase()}-${String(event.signed + 1).padStart(4, '0')}`;
  const tsStr = (form._registeredAt ? new Date(form._registeredAt) : now)
    .toISOString().replace('T', ' ').slice(0, 19) + ' UTC';
  const dateObj = new Date(event.date + 'T00:00:00');
  const dateStr = dateObj.toLocaleDateString('en-US', {
    weekday: 'long', month: 'long', day: 'numeric', year: 'numeric'
  }).toUpperCase();

  const bannerLabel = isWaitlist ? 'WAITLISTED' : 'CONFIRMED';
  const headline = isWaitlist ? "YOU'RE ON THE WAITLIST." : "YOU'RE IN.";
  const subline = isWaitlist
    ? <>The roster is full. If a slot opens we'll reach out. Keep training.<br />Waitlist notice sent to <strong style={{ color: t.brass }}>{form.email}</strong>.</>
    : <>Your spot is locked. Show up on time, show up ready.<br />A confirmation was sent to <strong style={{ color: t.brass }}>{form.email}</strong>.</>;
  const stampText = isWaitlist ? 'WAIT' : 'LOCKED';
  const stampSub = isWaitlist ? 'LIST' : 'IN';

  return (
    <div style={{ background: t.bg, color: t.fg, minHeight: '100vh', padding: '48px var(--gutter-x)' }}>
      <div style={{ maxWidth: 680, margin: '0 auto' }}>
        {/* ── Waiver status panel — intentionally first, before the banner.
            Three possible states:
            1. Waitlist — skip entirely (no event-day, no check-in gate)
            2. Confirmed + valid waiver on file — quiet green confirmation
            3. Confirmed + no valid waiver — action-required prompt on top
               so the candidate can't miss it while celebrating the signup
        ────────────────────────────────────────────────────────────── */}
        {!isWaitlist && waiverStatus && waiverStatus.valid && (
          <div style={{
            marginBottom: 32, padding: '16px 18px',
            background: 'rgba(122, 168, 107, 0.08)', border: '1px solid #7aa86b',
            display: 'flex', alignItems: 'center', gap: 12,
          }}>
            <div style={{
              fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 18,
              color: '#7aa86b', lineHeight: 1,
            }}>✓</div>
            <div style={{ flex: 1 }}>
              <div style={{
                fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 13,
                letterSpacing: '0.15em', color: t.fg,
              }}>LIABILITY WAIVER ON FILE</div>
              <div style={{
                fontFamily: 'Barlow, sans-serif', fontSize: 12, color: t.dim,
                marginTop: 4, lineHeight: 1.5,
              }}>
                You signed a waiver within the past 6 months, so you're
                pre-cleared for check-in. No action needed.
              </div>
            </div>
          </div>
        )}

        {!isWaitlist && waiverStatus && !waiverStatus.valid && cancelToken && (
          <div style={{
            marginBottom: 32, padding: '18px 20px',
            background: 'rgba(201, 169, 78, 0.08)', border: `1px solid ${t.brass}`,
          }}>
            <div style={{
              fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 14,
              letterSpacing: '0.15em', color: t.brass, marginBottom: 8,
            }}>⚠ ACTION REQUIRED — LIABILITY WAIVER</div>
            <div style={{
              fontFamily: 'Barlow, sans-serif', fontSize: 13, color: t.fg,
              lineHeight: 1.55, marginBottom: 14,
            }}>
              {waiverStatus.reason === 'expired'
                ? "Your previous waiver is more than 6 months old. Please sign the current version to speed up check-in."
                : waiverStatus.reason === 'version_changed'
                ? "The waiver has been updated since your last signing. Please sign the current version."
                : "Please sign your liability waiver. It takes about 90 seconds and covers you for all AFSW events for the next 6 months."}
              <br /><br />
              <span style={{ color: t.dim, fontSize: 12 }}>
                If you don't sign now, you'll need to complete it at the event before we can check you in.
              </span>
            </div>
            <button
              onClick={() => { window.location.hash = '#waiver=' + encodeURIComponent(cancelToken); }}
              style={{
                padding: '14px 28px',
                background: t.brass, color: '#0F1114', border: 'none',
                fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 13,
                letterSpacing: '0.25em', cursor: 'pointer',
              }}
            >SIGN WAIVER NOW</button>
          </div>
        )}

        <div style={{ textAlign: 'center', marginBottom: 40 }}>
          <div style={{
            fontFamily: 'Barlow, sans-serif', fontWeight: 300, fontSize: 11,
            letterSpacing: '0.35em', color: t.brass, marginBottom: 16,
          }}>{isWaitlist ? '◷' : '✓'} {bannerLabel} · {tsStr}</div>
          <h1 style={{
            fontFamily: 'Oswald, sans-serif', fontWeight: 700,
            fontSize: 'clamp(48px, 6vw, 72px)',
            color: t.fg, margin: 0, letterSpacing: '0.02em', lineHeight: 0.95,
          }}>{headline}</h1>
          <p style={{
            fontFamily: 'Barlow, sans-serif', fontWeight: 400, fontSize: 17,
            color: t.fg, opacity: 0.75, margin: '18px 0 0', lineHeight: 1.5,
          }}>
            {subline}
          </p>
        </div>

        <div style={{
          background: t.cellBg, border: `1px solid ${t.line}`,
          position: 'relative', overflow: 'hidden',
        }}>
          <div style={{
            position: 'absolute', top: 32, right: 32,
            transform: `rotate(-12deg) scale(${stamped ? 1 : 0.5})`,
            opacity: stamped ? 1 : 0,
            transition: 'all 0.35s cubic-bezier(0.34, 1.56, 0.64, 1)',
            border: `3px solid ${t.brass}`, padding: '8px 18px',
            fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 18,
            letterSpacing: '0.2em', color: t.brass,
            pointerEvents: 'none', textAlign: 'center',
          }}>
            {stampText}<br />
            <span style={{ fontSize: 9, letterSpacing: '0.25em', fontWeight: 400 }}>{stampSub}</span>
          </div>

          <div style={{
            padding: '24px 32px', borderBottom: `1px solid ${t.line}`,
            background: t.accentBg,
          }}>
            <div style={{
              fontFamily: 'Barlow, sans-serif', fontWeight: 300, fontSize: 10,
              letterSpacing: '0.3em', color: t.dim, marginBottom: 4,
            }}>CONFIRMATION NO.</div>
            <div style={{
              fontFamily: 'ui-monospace, Menlo, monospace', fontWeight: 600,
              fontSize: 22, color: t.fg, letterSpacing: '0.1em',
            }}>{confNum}</div>
          </div>

          <div style={{ padding: '28px 32px', borderBottom: `1px solid ${t.line}` }}>
            <div style={{
              fontFamily: 'Barlow, sans-serif', fontWeight: 300, fontSize: 10,
              letterSpacing: '0.3em', color: t.brass, marginBottom: 10,
            }}>EVENT</div>
            <h2 style={{
              fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 28,
              color: t.fg, margin: '0 0 20px', letterSpacing: '0.02em', lineHeight: 1.1,
            }}>{event.title}</h2>
            <DetailRow label="DATE" value={dateStr} t={t} />
            <DetailRow label="TIME" value={`${event.time} – ${event.endTime} (arrive 15 min early)`} t={t} />
            <DetailRow label="LOCATION" value={event.location} t={t} />
            <DetailRow label="TYPE" value={`${event.type.toUpperCase()} · ${event.tag}`} t={t} last />
          </div>

          <div style={{ padding: '28px 32px', borderBottom: `1px solid ${t.line}` }}>
            <div style={{
              fontFamily: 'Barlow, sans-serif', fontWeight: 300, fontSize: 10,
              letterSpacing: '0.3em', color: t.brass, marginBottom: 16,
            }}>ATTENDEE</div>
            <DetailRow label="NAME" value={form.name} t={t} />
            <DetailRow label="EMAIL" value={form.email} t={t} />
            <DetailRow label="PHONE" value={form.phone} t={t} last />
          </div>

          {event.opord && !isWaitlist && (
            <div style={{ padding: '24px 32px' }}>
              <div style={{
                fontFamily: 'Barlow, sans-serif', fontWeight: 600, fontSize: 11,
                letterSpacing: '0.3em', color: t.brass, marginBottom: 14,
              }}>OPERATIONS ORDER</div>
              <a
                href={event.opord.url}
                download={event.opord.filename}
                target="_blank"
                rel="noreferrer"
                style={{
                  display: 'flex', alignItems: 'center', gap: 16,
                  padding: '16px 18px',
                  background: t.bg,
                  border: `1px solid ${t.lineStrong}`,
                  textDecoration: 'none', color: t.fg,
                  transition: 'background 0.15s, border-color 0.15s',
                }}
                onMouseEnter={(e) => {
                  e.currentTarget.style.background = t.accentBg;
                  e.currentTarget.style.borderColor = t.brass;
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.background = t.bg;
                  e.currentTarget.style.borderColor = t.lineStrong;
                }}
              >
                <div style={{
                  width: 40, height: 48, position: 'relative', flexShrink: 0,
                  border: `1.5px solid ${t.brass}`,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>
                  <span style={{
                    fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 10,
                    letterSpacing: '0.1em', color: t.brass,
                  }}>PDF</span>
                  <div style={{
                    position: 'absolute', top: -1, right: -1,
                    width: 8, height: 8,
                    background: t.cellBg,
                    borderLeft: `1.5px solid ${t.brass}`,
                    borderBottom: `1.5px solid ${t.brass}`,
                  }} />
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{
                    fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 14,
                    color: t.fg, letterSpacing: '0.02em',
                    whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
                    marginBottom: 3,
                  }}>
                    {event.opord.filename}
                  </div>
                  <div style={{
                    fontFamily: 'Barlow, sans-serif', fontWeight: 400, fontSize: 12,
                    color: t.dim, lineHeight: 1.3,
                  }}>
                    Full brief, gear list, and contingencies
                  </div>
                </div>
                <div style={{
                  fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 18,
                  color: t.brass, flexShrink: 0, lineHeight: 1,
                }}>
                  ↓
                </div>
              </a>
            </div>
          )}
        </div>

        {/* Waiver panel moved to top of card — see above the CONFIRMED banner */}

        <div style={{ display: 'flex', gap: 12, marginTop: 28, justifyContent: 'center' }}>
          <button onClick={onBackToCalendar} style={{
            padding: '14px 28px', background: t.brass, color: '#0F1114', border: 'none',
            fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 13,
            letterSpacing: '0.3em', cursor: 'pointer',
          }}>BACK TO CALENDAR</button>
          <button onClick={() => window.print()} style={{
            padding: '14px 28px', background: 'transparent', color: t.fg,
            border: `1px solid ${t.lineStrong}`,
            fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 13,
            letterSpacing: '0.3em', cursor: 'pointer',
          }}>SAVE / PRINT</button>
        </div>

        <div style={{
          textAlign: 'center', marginTop: 40,
          fontFamily: 'Barlow, sans-serif', fontWeight: 300, fontSize: 11,
          letterSpacing: '0.3em', color: t.dim,
        }}>@PACIFIC.AFSWS · THE WORK SPEAKS FOR ITSELF</div>
      </div>
    </div>
  );
}

function DetailRow({ label, value, t, last }) {
  return (
    <div style={{
      display: 'grid', gridTemplateColumns: '120px 1fr', padding: '10px 0',
      borderBottom: last ? 'none' : `1px dashed ${t.line}`, gap: 16,
    }}>
      <div style={{
        fontFamily: 'Barlow, sans-serif', fontWeight: 300, fontSize: 10,
        letterSpacing: '0.25em', color: t.dim, paddingTop: 3,
      }}>{label}</div>
      <div style={{
        fontFamily: 'Barlow, sans-serif', fontWeight: 400, fontSize: 14,
        color: t.fg, lineHeight: 1.4,
      }}>{value}</div>
    </div>
  );
}

window.Confirmation = Confirmation;
