// ===== flag-and-apply.jsx =====
// Two small focused features:
//   1. AddFlagModal — staff modal launched from the Flags page "Add flag" button
//   2. VolApplyFlow  — in-app volunteer application form (re-uses profile data;
//      identity fields are locked to prevent accidental edits during apply).
//
// Both are exposed on window so the rest of the app can mount them.

const {
  React,
  Card, Btn, IconBtn, StatusChip, Avatar, FlagPill, Kpi, Progress,
  Field, Input, Textarea, Select, Checkbox, Toggle, Tabs, Empty, SectionHead, TopBar,
  IconPlus, IconCheck, IconX, IconArrow, IconArrowL, IconDownload, IconUpload,
  IconBook, IconClock, IconUsers, IconAward, IconShield, IconSearch, IconFilter, IconBell,
  IconStar, IconEdit, IconExternal, IconChevron, IconChevronD, IconEye, IconMore, IconCal,
  IconClipboard, IconMail, IconFlag, IconPin,
  VOLUNTEERS, OPPORTUNITIES,
} = window;
const { useState: useFA, useMemo: useFAM } = React;

const fa_over = { fontSize: 11, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--fg-3)", fontWeight: 500 };
const fa_meta = { fontSize: 11, color: "var(--fg-3)" };

const fa_overlay = { position: "fixed", inset: 0, background: "rgba(31,27,22,0.45)", backdropFilter: "blur(4px)", zIndex: 80, display: "flex", justifyContent: "flex-end" };
const fa_drawer  = { width: "min(720px, 100%)", height: "100%", background: "var(--paper)", display: "flex", flexDirection: "column", boxShadow: "var(--shadow-lg)" };
const fa_head    = { padding: "20px 24px 16px", display: "flex", justifyContent: "space-between", alignItems: "start", gap: 14, borderBottom: "1px solid var(--border-soft)" };
const fa_foot    = { padding: "14px 24px", borderTop: "1px solid var(--border-soft)", display: "flex", alignItems: "center", gap: 8, background: "var(--paper-soft)" };

// ============================================================
// ADD FLAG MODAL
// ============================================================
const AddFlagModal = ({ open, onClose }) => {
  const [step, setStep] = useFA(1);
  const [data, setData] = useFA({
    volunteerId: "",
    kind: "yellow", // red | yellow
    reason: "",
    category: "",
    scope: "all", // all | site | program | role
    expires: "",
    evidence: "",
    notifyVolunteer: false,
    requireMfa: false,
    acknowledged: false,
  });
  const update = (patch) => setData({ ...data, ...patch });
  const [submitted, setSubmitted] = useFA(false);

  if (!open) return null;

  const vol = VOLUNTEERS.find(v => v.id === data.volunteerId);

  if (submitted) {
    return (
      <div style={fa_overlay} onClick={onClose}>
        <div style={fa_drawer} onClick={(e) => e.stopPropagation()}>
          <div style={fa_head}>
            <div>
              <div style={fa_over}>Flag added</div>
              <div style={{ fontSize: 19, fontWeight: 500, color: "var(--ink)", marginTop: 4 }}>
                {data.kind === "red" ? "Red" : "Yellow"} flag on {vol?.name || "volunteer"}
              </div>
            </div>
            <IconBtn icon={IconX} size={32} onClick={onClose} aria-label="Close" />
          </div>
          <div style={{ flex: 1, overflow: "auto", padding: 24 }}>
            <div style={{ textAlign: "center", padding: "20px 0" }}>
              <div style={{ width: 56, height: 56, borderRadius: 999, background: data.kind === "red" ? "var(--crimson-100)" : "var(--amber-100)", color: data.kind === "red" ? "var(--crimson-600)" : "var(--amber-600)", display: "flex", alignItems: "center", justifyContent: "center", margin: "0 auto 16px" }}>
                <IconFlag size={26} />
              </div>
              <div style={{ fontFamily: "var(--font-display)", fontSize: 26, color: "var(--ink)" }}>Flag recorded</div>
              <div style={{ fontSize: 13, color: "var(--fg-2)", marginTop: 6 }}>
                Audit ref <code style={{ background: "var(--paper-deep)", padding: "2px 7px", borderRadius: 4, fontFamily: "var(--font-mono)", fontSize: 12 }}>flag-{new Date().toISOString().slice(0, 10)}-{Math.random().toString(36).slice(2, 5)}</code>
              </div>
            </div>
            <Card style={{ background: "var(--paper-soft)" }}>
              <div style={{ ...fa_over, marginBottom: 10 }}>What happens next</div>
              <ul style={{ margin: 0, paddingLeft: 18, fontSize: 13, color: "var(--fg-1)", lineHeight: 1.7 }}>
                <li>{data.kind === "red"
                  ? "Volunteer is blocked from all role signups immediately. Existing confirmed shifts are NOT auto-cancelled — coordinator decides per shift."
                  : "Volunteer eligibility is limited per the scope you set. Coordinators see the flag on the record; volunteer doesn't see anything different."}</li>
                <li>Audit entry created with your actor, timestamp, reason, evidence note, and scope.</li>
                <li>{data.notifyVolunteer ? "Volunteer will receive the message you wrote." : "No volunteer-facing notification (default for flags)."}</li>
                {data.expires && <li>Auto-clears on <strong>{data.expires}</strong> unless re-affirmed.</li>}
              </ul>
            </Card>
          </div>
          <div style={fa_foot}>
            <Btn kind="ghost" onClick={() => { setSubmitted(false); setStep(1); setData({ volunteerId: "", kind: "yellow", reason: "", category: "", scope: "all", expires: "", evidence: "", notifyVolunteer: false, requireMfa: false, acknowledged: false }); }}>Add another</Btn>
            <div style={{ marginLeft: "auto" }}><Btn icon={IconCheck} onClick={onClose}>Done</Btn></div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div style={fa_overlay} onClick={onClose}>
      <div style={fa_drawer} onClick={(e) => e.stopPropagation()}>
        <div style={fa_head}>
          <div>
            <div style={fa_over}>Add flag · staff-only · never volunteer-visible</div>
            <div style={{ fontSize: 19, fontWeight: 500, color: "var(--ink)", marginTop: 4 }}>
              {step === 1 ? "Step 1 · Volunteer & flag type"
              : step === 2 ? "Step 2 · Reason & evidence"
              : "Step 3 · Scope, expiry & confirm"}
            </div>
          </div>
          <IconBtn icon={IconX} size={32} onClick={onClose} aria-label="Close" />
        </div>
        <div style={{ display: "flex", gap: 4, padding: "12px 24px 0" }}>
          {[1, 2, 3].map(n => (
            <div key={n} style={{ flex: 1, height: 3, borderRadius: 2, background: n <= step ? (data.kind === "red" ? "var(--crimson-500)" : "var(--amber-500)") : "var(--paper-deep)" }} />
          ))}
        </div>

        <div style={{ flex: 1, overflow: "auto", padding: 24 }}>
          {step === 1 && <Step1 data={data} update={update} />}
          {step === 2 && <Step2 data={data} update={update} vol={vol} />}
          {step === 3 && <Step3 data={data} update={update} vol={vol} />}
        </div>

        <div style={fa_foot}>
          {step > 1 && <Btn kind="ghost" icon={IconArrowL} onClick={() => setStep(step - 1)}>Back</Btn>}
          <div style={{ marginLeft: "auto", display: "flex", gap: 8 }}>
            {step < 3 && (
              <Btn iconRight={IconArrow} onClick={() => setStep(step + 1)}
                disabled={(step === 1 && !data.volunteerId) || (step === 2 && !data.reason)}>
                Continue
              </Btn>
            )}
            {step === 3 && (
              <Btn icon={IconFlag} onClick={() => setSubmitted(true)}
                disabled={!data.acknowledged}
                style={{ background: data.kind === "red" ? "var(--crimson-600)" : "var(--amber-600)", borderColor: data.kind === "red" ? "var(--crimson-600)" : "var(--amber-600)" }}>
                Add {data.kind === "red" ? "red" : "yellow"} flag
              </Btn>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

const Step1 = ({ data, update }) => {
  const [q, setQ] = useFA("");
  const filteredVols = VOLUNTEERS.filter(v => {
    if (!q) return true;
    return (v.name + " " + v.email + " " + v.id).toLowerCase().includes(q.toLowerCase());
  }).slice(0, 6);

  return (
    <>
      <Field label="Volunteer" required>
        <div style={{ position: "relative", marginBottom: 8 }}>
          <Input placeholder="Search by name, email, or ID…" value={q} onChange={(e) => setQ(e.target.value)} style={{ width: "100%", paddingLeft: 32 }} />
          <IconSearch size={14} style={{ position: "absolute", left: 12, top: 12, color: "var(--fg-3)" }} />
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 6, maxHeight: 280, overflow: "auto" }}>
          {filteredVols.map(v => {
            const picked = data.volunteerId === v.id;
            return (
              <button key={v.id} onClick={() => update({ volunteerId: v.id })} style={{
                display: "flex", alignItems: "center", gap: 12, padding: "10px 12px", borderRadius: 10,
                background: picked ? "var(--coral-50)" : "var(--paper)",
                border: "1px solid " + (picked ? "var(--coral-500)" : "var(--border-soft)"),
                borderWidth: picked ? 2 : 1, cursor: "pointer", fontFamily: "inherit", textAlign: "left", width: "100%",
              }}>
                <Avatar {...v} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 500, color: "var(--ink)" }}>{v.name}</div>
                  <div style={{ ...fa_meta, marginTop: 2 }}>{v.email} · {v.role} · {v.status}</div>
                </div>
                {v.flag && <FlagPill flag={v.flag} size="sm" />}
                {picked && <IconCheck size={16} style={{ color: "var(--coral-700)" }} />}
              </button>
            );
          })}
        </div>
      </Field>

      <div style={{ ...fa_over, margin: "16px 0 10px" }}>Flag type</div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
        <FlagTypeCard
          picked={data.kind === "yellow"}
          onClick={() => update({ kind: "yellow" })}
          color="var(--amber-600)" bg="var(--amber-100)"
          title="Yellow flag"
          desc="Limits eligibility per the scope. Visible to coordinators only. Volunteer doesn't see anything different."
          examples={["Missed shifts", "Coordinator concern", "Performance issue"]}
        />
        <FlagTypeCard
          picked={data.kind === "red"}
          onClick={() => update({ kind: "red" })}
          color="var(--crimson-600)" bg="var(--crimson-100)"
          title="Red flag"
          desc="Excludes from all roles. Step-up auth required to add. Cannot be self-cleared by the volunteer."
          examples={["Safety incident", "Policy violation", "Pending HR review"]}
        />
      </div>
    </>
  );
};

const FlagTypeCard = ({ picked, onClick, color, bg, title, desc, examples }) => (
  <button onClick={onClick} style={{
    padding: 16, borderRadius: 12, cursor: "pointer", fontFamily: "inherit", textAlign: "left",
    background: picked ? bg : "var(--paper)",
    border: "1px solid " + (picked ? color : "var(--border-soft)"),
    borderWidth: picked ? 2 : 1,
  }}>
    <div style={{ display: "flex", gap: 10, alignItems: "center", marginBottom: 10 }}>
      <div style={{ width: 32, height: 32, borderRadius: 8, background: bg, color, display: "flex", alignItems: "center", justifyContent: "center" }}>
        <IconFlag size={16} />
      </div>
      <div style={{ fontSize: 15, fontWeight: 500, color: "var(--ink)" }}>{title}</div>
    </div>
    <div style={{ fontSize: 12, color: "var(--fg-2)", lineHeight: 1.5, marginBottom: 10 }}>{desc}</div>
    <div style={{ display: "flex", flexWrap: "wrap", gap: 4 }}>
      {examples.map(e => <span key={e} style={{ fontSize: 10, padding: "2px 7px", borderRadius: 999, background: "var(--paper-deep)", color: "var(--fg-2)" }}>{e}</span>)}
    </div>
  </button>
);

const Step2 = ({ data, update, vol }) => (
  <>
    {vol && (
      <Card style={{ background: "var(--paper-soft)", marginBottom: 16 }}>
        <div style={{ display: "flex", gap: 12, alignItems: "center" }}>
          <Avatar {...vol} />
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 14, fontWeight: 500 }}>{vol.name}</div>
            <div style={{ ...fa_meta, marginTop: 2 }}>{vol.role} · {vol.site} · joined {vol.joined}</div>
          </div>
          <FlagPill flag={{ kind: data.kind }} size="sm" />
        </div>
      </Card>
    )}

    <Field label="Reason category" required>
      <Select value={data.category} onChange={(e) => update({ category: e.target.value })}
        options={data.kind === "red" ? [
          { value: "", label: "— select —" },
          { value: "safety", label: "Safety incident" },
          { value: "policy", label: "Policy violation" },
          { value: "criminal", label: "Criminal background — newly disclosed" },
          { value: "hr-review", label: "Pending HR review" },
          { value: "exclusion", label: "Permanent exclusion (executive)" },
        ] : [
          { value: "", label: "— select —" },
          { value: "missed-shifts", label: "Missed shifts without notice" },
          { value: "performance", label: "Performance concern" },
          { value: "behavior", label: "Behavior — needs follow-up" },
          { value: "training-overdue", label: "Training overdue" },
          { value: "other", label: "Other (free text)" },
        ]} />
    </Field>

    <Field label="Reason" required>
      <Textarea rows={3} placeholder="What happened, in your words. Be specific and factual — this becomes part of the audit record." value={data.reason} onChange={(e) => update({ reason: e.target.value })} />
    </Field>

    <Field label="Evidence reference">
      <Input placeholder="Incident report number, email reference, shift ID, etc." value={data.evidence} onChange={(e) => update({ evidence: e.target.value })} />
    </Field>

    <div style={{ marginTop: 6, padding: 12, background: "var(--paper-deep)", borderRadius: 10, fontSize: 12, color: "var(--fg-2)", lineHeight: 1.5 }}>
      <IconShield size={13} style={{ verticalAlign: "middle", marginRight: 6, color: "var(--fg-3)" }} />
      Reason and evidence are stored encrypted, visible only to admins with flag access in the volunteer's scope. Volunteers never see these fields.
    </div>
  </>
);

const Step3 = ({ data, update, vol }) => (
  <>
    <Field label="Scope">
      <Select value={data.scope} onChange={(e) => update({ scope: e.target.value })}
        options={[
          { value: "all", label: "All programs (default)" },
          { value: "program", label: "Specific program(s)" },
          { value: "site", label: "Specific site(s)" },
          { value: "role", label: "Specific role(s)" },
        ]} />
    </Field>
    {data.scope !== "all" && (
      <Field label={data.scope === "program" ? "Programs" : data.scope === "site" ? "Sites" : "Roles"}>
        <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
          {(data.scope === "program" ? ["State parks", "Wildlife", "Education", "Hunter Outreach"]
          : data.scope === "site"    ? ["Cherry Creek SP", "Boyd Lake SP", "Lory SP"]
          :                              ["Trail crew", "Camp host", "Hunter ed instructor"]).map(o => (
            <span key={o} style={{ fontSize: 12, padding: "5px 10px", borderRadius: 999, background: "var(--paper-deep)", color: "var(--fg-1)", cursor: "pointer" }}>{o}</span>
          ))}
          <Btn size="sm" kind="ghost" icon={IconPlus}>Add</Btn>
        </div>
      </Field>
    )}

    <Field label="Expiry">
      <Select value={data.expires ? "set" : "none"} onChange={(e) => update({ expires: e.target.value === "set" ? "Jun 23, 2026 (30 days)" : "" })}
        options={[
          { value: "none", label: "No expiry — review on demand" },
          { value: "set", label: "Auto-clear in 30 days" },
        ]} />
    </Field>
    {data.expires && <div style={{ ...fa_meta, marginTop: -8, marginBottom: 14 }}>Will auto-clear on {data.expires} unless re-affirmed by a coordinator.</div>}

    <div style={{ ...fa_over, margin: "16px 0 10px" }}>Volunteer-facing</div>
    <Card style={{ background: "var(--paper)" }}>
      <Checkbox checked={data.notifyVolunteer} onChange={(on) => update({ notifyVolunteer: on })} label="Send volunteer a message (optional)" />
      {data.notifyVolunteer && (
        <Field label="Message to volunteer" style={{ marginTop: 10 }}>
          <Textarea rows={3} placeholder="e.g. 'We need to talk about your last two shifts — can you give me a call this week?'" />
          <div style={{ ...fa_meta, marginTop: 6 }}>The flag itself is never disclosed. Volunteer sees only the message you write.</div>
        </Field>
      )}
    </Card>

    {data.kind === "red" && (
      <div style={{ marginTop: 16, padding: 14, background: "var(--crimson-100)", borderRadius: 10 }}>
        <div style={{ ...fa_over, color: "var(--crimson-600)", marginBottom: 10 }}>Step-up authentication required</div>
        <div style={{ fontSize: 12, color: "var(--ink)", lineHeight: 1.5, marginBottom: 10 }}>
          Red flags require MFA re-verification. You'll be prompted after confirming.
        </div>
        <Checkbox checked={data.requireMfa} onChange={(on) => update({ requireMfa: on })} label="I understand MFA will be required" />
      </div>
    )}

    <div style={{ marginTop: 16, padding: 14, background: data.kind === "red" ? "var(--crimson-100)" : "var(--amber-100)", borderRadius: 10 }}>
      <Checkbox checked={data.acknowledged} onChange={(on) => update({ acknowledged: on })}
        label={
          data.kind === "red"
            ? "I confirm this is a serious action. The volunteer will be blocked from all roles. Audit log will record this action."
            : "I confirm this flag is recorded for staff use. Audit log will record this action."
        } />
    </div>
  </>
);

// ============================================================
// VOLUNTEER APPLY FLOW (in-app)
// ============================================================
//
// Renders inside the volunteer surface. Distinct from PublicApply (public-facing).
// Identity fields are LOCKED to prevent accidents; volunteer is sent to profile
// to update them if they're wrong.

const VolApplyFlow = ({ oppId, go }) => {
  const opp = OPPORTUNITIES.find(o => o.id === oppId) || OPPORTUNITIES[0];
  const me = VOLUNTEERS.find(v => v.id === "v-arenas"); // the logged-in volunteer

  const [step, setStep] = useFA(1);
  const [data, setData] = useFA({
    motivation: "",
    availability: [],
    experience: "",
    references: [{ name: "", relation: "", contact: "" }, { name: "", relation: "", contact: "" }],
    waivers: { liability: false, photo: false },
    submitted: false,
  });
  const update = (patch) => setData({ ...data, ...patch });

  const steps = ["Confirm your details", "About the role", "References", "Agreements", "Review"];

  if (data.submitted) return <ApplySuccess me={me} opp={opp} go={go} />;

  return (
    <>
      <TopBar
        title={`Apply: ${opp.title}`}
        breadcrumb={["Find opportunities", opp.title, "Apply"]}
        onBack={() => go("v-opportunity/" + opp.id)}
        subtitle={`Step ${step} of ${steps.length} · ${steps[step - 1]}`}
        secondary={<Btn kind="ghost" onClick={() => go("v-opportunity/" + opp.id)}>Save & exit</Btn>}
      />
      <div style={{ flex: 1, overflow: "auto", padding: "20px 32px 56px" }}>
        <div style={{ maxWidth: 760, margin: "0 auto" }}>
          {/* Stepper */}
          <div style={{ display: "flex", gap: 4, marginBottom: 24, padding: "8px 12px", background: "var(--paper-soft)", borderRadius: 12, border: "1px solid var(--border-soft)" }}>
            {steps.map((label, i) => {
              const n = i + 1;
              const done = n < step;
              const active = n === step;
              return (
                <button key={label} onClick={() => setStep(n)} style={{
                  flex: 1, padding: "10px 8px", border: "none", background: "transparent",
                  textAlign: "left", cursor: "pointer", fontFamily: "inherit",
                  borderBottom: "2px solid " + (active ? "var(--coral-600)" : "transparent"),
                  opacity: active || done ? 1 : 0.55,
                }}>
                  <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
                    <span style={{
                      width: 22, height: 22, borderRadius: 999, display: "flex", alignItems: "center", justifyContent: "center",
                      background: done ? "var(--sage-700)" : active ? "var(--coral-600)" : "var(--paper-deep)",
                      color: done || active ? "#FFFFFF" : "var(--fg-3)",
                      fontSize: 11, fontWeight: 600,
                    }}>{done ? "✓" : n}</span>
                    <span style={{ fontSize: 11, fontWeight: 500, color: "var(--ink)" }}>{label}</span>
                  </div>
                </button>
              );
            })}
          </div>

          {/* Steps */}
          {step === 1 && <ConfirmDetails me={me} opp={opp} go={go} />}
          {step === 2 && <AboutRole       opp={opp} data={data} update={update} />}
          {step === 3 && <References      data={data} update={update} me={me} />}
          {step === 4 && <Agreements      data={data} update={update} />}
          {step === 5 && <ReviewStep      me={me} opp={opp} data={data} />}

          {/* Footer */}
          <div style={{ display: "flex", gap: 10, marginTop: 28, paddingTop: 18, borderTop: "1px solid var(--border-soft)" }}>
            {step > 1 && <Btn kind="ghost" icon={IconArrowL} onClick={() => setStep(step - 1)}>Back</Btn>}
            <div style={{ marginLeft: "auto", display: "flex", gap: 8 }}>
              {step < 5 && <Btn iconRight={IconArrow} onClick={() => setStep(step + 1)}>Continue</Btn>}
              {step === 5 && (
                <Btn icon={IconCheck} onClick={() => update({ submitted: true })}
                  disabled={!data.waivers.liability}>
                  Submit application
                </Btn>
              )}
            </div>
          </div>
        </div>
      </div>
    </>
  );
};

// ---- Step 1: Confirm details (all locked) ----
const ConfirmDetails = ({ me, opp, go }) => (
  <>
    <Card style={{ background: "var(--paper-soft)", marginBottom: 18 }}>
      <div style={{ display: "flex", gap: 12, alignItems: "center" }}>
        <div style={{ width: 48, height: 48, borderRadius: 10, background: "var(--coral-100)", color: "var(--coral-700)", display: "flex", alignItems: "center", justifyContent: "center" }}>
          <IconClipboard size={20} />
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ ...fa_over, marginBottom: 4 }}>Applying for</div>
          <div style={{ fontSize: 16, fontWeight: 500, color: "var(--ink)" }}>{opp.title}</div>
          <div style={{ ...fa_meta, marginTop: 2 }}>{opp.location || opp.site} · {opp.when || "Ongoing role"}</div>
        </div>
      </div>
    </Card>

    <div style={{ ...fa_over, marginBottom: 10 }}>Your details · from your profile</div>
    <Card style={{ marginBottom: 14 }}>
      <LockedRow label="Legal name"  value={me.name} />
      <LockedRow label="Pronouns"    value={me.pronouns} />
      <LockedRow label="Email"        value={me.email} />
      <LockedRow label="Phone"        value={me.phone} />
      <LockedRow label="Address"      value={`${me.city}, CO`} />
      <LockedRow label="Languages"    value={(me.languages || ["English"]).join(", ")} />
      <LockedRow label="Joined CPW"   value={me.joined} />
    </Card>

    <div style={{ padding: 14, background: "var(--iris-100)", color: "var(--iris-600)", borderRadius: 12, display: "flex", gap: 14, alignItems: "center" }}>
      <IconShield size={18} />
      <div style={{ flex: 1, fontSize: 12, lineHeight: 1.5, color: "var(--ink)" }}>
        These are locked here so they don't get accidentally changed during an apply.
        If something is wrong, fix it in your profile and it'll be used everywhere.
      </div>
      <Btn size="sm" kind="secondary" iconRight={IconArrow} onClick={() => go("v-profile")}>Update profile</Btn>
    </div>
  </>
);

const LockedRow = ({ label, value }) => (
  <div style={{ display: "grid", gridTemplateColumns: "140px 1fr auto", gap: 12, padding: "10px 0", borderBottom: "1px dashed var(--border-soft)", alignItems: "center" }}>
    <span style={{ ...fa_meta }}>{label}</span>
    <span style={{ fontSize: 13, color: "var(--ink)" }}>{value || "—"}</span>
    <span style={{ display: "inline-flex", alignItems: "center", gap: 4, fontSize: 10, color: "var(--fg-3)", padding: "2px 7px", borderRadius: 999, background: "var(--paper-deep)", textTransform: "uppercase", letterSpacing: "0.08em", fontWeight: 500 }}>
      <IconShield size={10} /> Locked
    </span>
  </div>
);

// ---- Step 2: About this role ----
const AboutRole = ({ opp, data, update }) => {
  const DAYS = ["Mon mornings", "Mon evenings", "Tue mornings", "Tue evenings", "Wed", "Thu", "Fri", "Sat mornings", "Sat afternoons", "Sun mornings", "Sun afternoons"];
  return (
    <>
      <Field label="What draws you to this role?">
        <Textarea rows={4} value={data.motivation} onChange={(e) => update({ motivation: e.target.value })}
          placeholder="Tell us in a few sentences. Reviewers read every application." />
      </Field>

      <Field label="When are you available?">
        <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
          {DAYS.map(d => {
            const picked = data.availability.includes(d);
            return (
              <button key={d} onClick={() => update({ availability: picked ? data.availability.filter(x => x !== d) : [...data.availability, d] })} style={{
                fontFamily: "inherit", fontSize: 12, padding: "6px 12px", borderRadius: 999, cursor: "pointer",
                background: picked ? "var(--coral-100)" : "var(--paper)",
                color: picked ? "var(--coral-700)" : "var(--fg-1)",
                border: "1px solid " + (picked ? "var(--coral-500)" : "var(--border-soft)"),
              }}>{d}</button>
            );
          })}
        </div>
      </Field>

      <Field label="Relevant experience (optional)">
        <Textarea rows={3} value={data.experience} onChange={(e) => update({ experience: e.target.value })}
          placeholder="Trail-building, first aid, prior volunteering, etc. Not required." />
      </Field>

      <div style={{ marginTop: 14, padding: 12, background: "var(--paper-deep)", borderRadius: 10, fontSize: 12, color: "var(--fg-2)", lineHeight: 1.5 }}>
        Based on your past activity ({(VOLUNTEERS.find(v => v.id === "v-arenas")?.ytdHours || 0)} hr YTD), your application will likely be reviewed within 3 business days.
      </div>
    </>
  );
};

// ---- Step 3: References ----
const References = ({ data, update, me }) => {
  const updateRef = (i, patch) => {
    const next = data.references.map((r, ix) => ix === i ? { ...r, ...patch } : r);
    update({ references: next });
  };
  return (
    <>
      <p style={{ fontSize: 13, color: "var(--fg-2)", marginBottom: 16, maxWidth: 520 }}>
        Two references who can speak to your reliability. Not coworkers from CPW. We'll reach out by email.
      </p>
      {data.references.map((r, i) => (
        <Card key={i} style={{ marginBottom: 12 }}>
          <div style={{ ...fa_over, marginBottom: 12 }}>Reference {i + 1}</div>
          <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr", gap: 12 }}>
            <Field label="Full name"><Input value={r.name} onChange={(e) => updateRef(i, { name: e.target.value })} /></Field>
            <Field label="Relationship">
              <Select value={r.relation} onChange={(e) => updateRef(i, { relation: e.target.value })}
                options={["", "Manager / employer", "Coach / instructor", "Friend (non-family)", "Community leader", "Other"]} />
            </Field>
          </div>
          <Field label="Email or phone">
            <Input value={r.contact} onChange={(e) => updateRef(i, { contact: e.target.value })}
              placeholder="e.g. j.smith@example.com or (303) 555-…" />
          </Field>
        </Card>
      ))}
      <div style={{ marginTop: 4, padding: 10, background: "var(--paper-deep)", borderRadius: 8, fontSize: 11, color: "var(--fg-2)", lineHeight: 1.5 }}>
        We won't contact references without telling you first. They'll only receive a short verification email — never your application contents.
      </div>
    </>
  );
};

// ---- Step 4: Agreements ----
const Agreements = ({ data, update }) => (
  <>
    <Card style={{ marginBottom: 12 }}>
      <Checkbox
        checked={data.waivers.liability}
        onChange={(on) => update({ waivers: { ...data.waivers, liability: on } })}
        label="I agree to the CPW Volunteer Liability Waiver" />
      <div style={{ ...fa_meta, marginTop: 6, marginLeft: 26 }}>Required. Covers field activities, transportation, and the inherent risks of outdoor work. <a style={{ color: "var(--coral-700)" }} href="#">Read the waiver</a></div>
    </Card>
    <Card style={{ marginBottom: 12 }}>
      <Checkbox
        checked={data.waivers.photo}
        onChange={(on) => update({ waivers: { ...data.waivers, photo: on } })}
        label="I agree to the Photo / Media Release (optional)" />
      <div style={{ ...fa_meta, marginTop: 6, marginLeft: 26 }}>Optional. Lets CPW use photos taken during events in newsletters and on the public site. You can revoke this later.</div>
    </Card>
    <Card>
      <Checkbox checked={true} onChange={() => {}}
        label="I authorize a background check if required for the role" />
      <div style={{ ...fa_meta, marginTop: 6, marginLeft: 26 }}>If this role needs one, you'll be guided through a separate consent form. Background checks are not run without that explicit step.</div>
    </Card>
  </>
);

// ---- Step 5: Review ----
const ReviewStep = ({ me, opp, data }) => (
  <>
    <Card style={{ marginBottom: 14 }}>
      <div style={{ ...fa_over, marginBottom: 12 }}>Applying for</div>
      <div style={{ fontSize: 16, fontWeight: 500 }}>{opp.title}</div>
      <div style={{ ...fa_meta, marginTop: 4 }}>{opp.location || opp.site} · {opp.when || "Ongoing"}</div>
    </Card>
    <Card style={{ marginBottom: 14 }}>
      <div style={{ ...fa_over, marginBottom: 12 }}>Your details · locked</div>
      <ReviewRow label="Name" v={me.name} />
      <ReviewRow label="Email" v={me.email} />
      <ReviewRow label="Phone" v={me.phone} />
    </Card>
    <Card style={{ marginBottom: 14 }}>
      <div style={{ ...fa_over, marginBottom: 12 }}>Your answers</div>
      <ReviewRow label="What draws you" v={data.motivation || "—"} multiline />
      <ReviewRow label="Availability" v={data.availability.join(", ") || "—"} />
      <ReviewRow label="Experience" v={data.experience || "—"} multiline />
      <ReviewRow label="References" v={data.references.filter(r => r.name).map(r => `${r.name} (${r.relation})`).join(" · ") || "—"} />
    </Card>
    <Card>
      <div style={{ ...fa_over, marginBottom: 12 }}>What happens after you submit</div>
      <ul style={{ margin: 0, paddingLeft: 18, fontSize: 13, color: "var(--fg-1)", lineHeight: 1.7 }}>
        <li>You'll get a confirmation email within a few minutes.</li>
        <li>A coordinator reviews your application within ~3 business days.</li>
        <li>If anything's missing or unclear, they'll email you directly.</li>
        <li>You'll see decision status under <strong>Your application</strong> in the menu.</li>
      </ul>
    </Card>
  </>
);

const ReviewRow = ({ label, v, multiline }) => (
  <div style={{ display: "grid", gridTemplateColumns: multiline ? "1fr" : "140px 1fr", gap: 8, padding: "8px 0", borderBottom: "1px dashed var(--border-soft)" }}>
    <span style={{ ...fa_meta }}>{label}</span>
    <span style={{ fontSize: 13, color: "var(--ink)", lineHeight: 1.5 }}>{v}</span>
  </div>
);

// ---- Success page ----
const ApplySuccess = ({ me, opp, go }) => (
  <>
    <TopBar title="Application received" subtitle={`We'll follow up within 3 business days.`} />
    <div style={{ flex: 1, overflow: "auto", padding: "32px 32px 56px" }}>
      <div style={{ maxWidth: 580, margin: "0 auto", textAlign: "center" }}>
        <div style={{ width: 64, height: 64, borderRadius: 999, background: "var(--sage-100)", color: "var(--sage-700)", display: "flex", alignItems: "center", justifyContent: "center", margin: "20px auto 22px" }}>
          <IconCheck size={32} />
        </div>
        <div style={{ fontFamily: "var(--font-display)", fontSize: 36, color: "var(--ink)", lineHeight: 1.15, marginBottom: 12 }}>Thanks, {me.name.split(" ")[0]}.</div>
        <div style={{ fontSize: 15, color: "var(--fg-2)", lineHeight: 1.6, marginBottom: 22 }}>
          Your application for <strong style={{ color: "var(--ink)" }}>{opp.title}</strong> is in. A confirmation email is on the way to <strong style={{ color: "var(--ink)" }}>{me.email}</strong>.
        </div>
        <Card style={{ textAlign: "left", marginBottom: 22 }}>
          <div style={{ ...fa_over, marginBottom: 10 }}>What's next</div>
          <ul style={{ margin: 0, paddingLeft: 18, fontSize: 13, color: "var(--fg-1)", lineHeight: 1.7 }}>
            <li>A coordinator reviews within ~3 business days.</li>
            <li>You'll see live status under <strong>Your application</strong>.</li>
            <li>If we need anything else, you'll get an email.</li>
          </ul>
        </Card>
        <div style={{ display: "flex", gap: 8, justifyContent: "center" }}>
          <Btn kind="secondary" onClick={() => go("v-find")}>Find more opportunities</Btn>
          <Btn icon={IconArrow} onClick={() => go("v-app-status")}>See application status</Btn>
        </div>
      </div>
    </div>
  </>
);

// ============================================================
Object.assign(window, { AddFlagModal, VolApplyFlow });
