// ===== m9-gates.jsx =====
// M9 · Onboarding training gates — FR2 (config + reusable failure banner)

const {
  React,
  Card, Btn, IconBtn, StatusChip, Avatar, Kpi, Field, Input, Textarea, Select, Checkbox, Toggle, Tabs, Empty, SectionHead, TopBar, Progress,
  IconPlus, IconCheck, IconX, IconArrow, IconArrowL, IconDownload, IconUpload, IconBook, IconClock, IconUsers,
  IconAward, IconShield, IconSearch, IconFilter, IconBell, IconStar, IconEdit, IconExternal, IconMore, IconMail, IconFlag,
} = window;
const { useState: useG9 } = React;

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

// ============================================================
// GATE RULES
// ============================================================
const GATE_RULES = [
  {
    id: "gate-camphost",
    role: "Camp host",
    program: "State parks",
    requires: [
      { id: "qt-handbook", name: "Volunteer handbook acknowledgment", req: true, completion: "Before activation" },
      { id: "qt-camphost", name: "Camp host orientation",              req: true, completion: "Before activation" },
      { id: "qt-firstaid", name: "First aid / CPR",                      req: true, completion: "Before first shift", renewable: true },
      { id: "wv-liability",name: "Liability waiver",                     req: true, completion: "Before activation" },
      { id: "wv-photo",    name: "Photo / media release",                 req: false, completion: "Optional" },
      { id: "bg-check",    name: "Background check",                      req: true, completion: "Before activation", renewable: true },
    ],
    blocks: ["activation", "shift-signup", "hour-logging"],
    individualOverrides: 2,
  },
  {
    id: "gate-trail",
    role: "Trail crew",
    program: "State parks",
    requires: [
      { id: "qt-handbook", name: "Volunteer handbook acknowledgment", req: true, completion: "Before activation" },
      { id: "qt-trail",    name: "Trail crew safety",                    req: true, completion: "Before first shift", renewable: true },
      { id: "qt-firstaid", name: "First aid / CPR",                      req: false, completion: "Recommended", renewable: true },
      { id: "wv-liability",name: "Liability waiver",                     req: true, completion: "Before activation" },
    ],
    blocks: ["shift-signup", "hour-logging"],
    individualOverrides: 0,
  },
  {
    id: "gate-hunter",
    role: "Hunter ed instructor",
    program: "Hunter Outreach",
    requires: [
      { id: "qt-handbook",    name: "Volunteer handbook acknowledgment", req: true, completion: "Before activation" },
      { id: "qt-hunter-meth", name: "Hunter ed methodology",                req: true, completion: "Before activation" },
      { id: "qt-wingshooter", name: "Wingshooter Instructor cert",          req: true, completion: "Before activation", renewable: true },
      { id: "qt-firstaid",    name: "First aid / CPR",                       req: true, completion: "Before first class", renewable: true },
      { id: "bg-check",       name: "Background check",                       req: true, completion: "Before activation", renewable: true },
    ],
    blocks: ["activation", "shift-signup", "hour-logging"],
    individualOverrides: 0,
  },
  {
    id: "gate-natu",
    role: "Naturalist",
    program: "Education",
    requires: [
      { id: "qt-handbook",     name: "Volunteer handbook acknowledgment", req: true, completion: "Before activation" },
      { id: "qt-rmnaturalist", name: "Rocky Mountain Naturalist cert",       req: true, completion: "Before first program", renewable: true },
      { id: "qt-firstaid",     name: "First aid / CPR",                       req: true, completion: "Before first program", renewable: true },
      { id: "wv-liability",    name: "Liability waiver",                       req: true, completion: "Before activation" },
    ],
    blocks: ["activation", "shift-signup"],
    individualOverrides: 1,
  },
];

// Gates failing for specific volunteers — used to demo gate-failure banner
const GATE_FAILURES_SAMPLE = [
  { vol: "v-arenas",  role: "Camp host", missing: ["First aid / CPR — expired Mar 8"], action: "shift-signup", site: "Boyd Lake SP" },
  { vol: "v-okonkwo", role: "Camp host", missing: ["First aid / CPR — expires May 12"], action: "shift-signup", site: "Boyd Lake SP" },
  { vol: "v-mendez",  role: "Trail crew", missing: ["Trail crew safety — overdue (renew)"], action: "shift-signup", site: "Lake Pueblo SP" },
  { vol: "v-park",    role: "Camp host", missing: ["Camp host orientation"], action: "activation", site: "Boyd Lake SP" },
  { vol: "v-walsh",   role: "Hunter ed instructor", missing: ["Wingshooter Instructor cert", "First aid / CPR"], action: "activation", site: "Boulder" },
];

// ============================================================
// CONFIG SCREEN (lives inside Settings or standalone)
// ============================================================
const OrgGates = ({ go }) => {
  const [tab, setTab] = useG9("rules");
  return (
    <>
      <TopBar title="Onboarding training gates"
        subtitle={`${GATE_RULES.length} gate rules · ${GATE_FAILURES_SAMPLE.length} active gate failures · blocks activation, sign-up, and hour-logging when incomplete`}
        primary={<Btn icon={IconPlus}>New gate rule</Btn>}
        secondary={<Btn kind="secondary" icon={IconDownload}>Export</Btn>} />
      <div style={{ flex: 1, overflow: "auto", padding: "20px 32px 56px" }}>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14, marginBottom: 22 }}>
          <Kpi label="Gate rules" value={GATE_RULES.length} delta={`${GATE_RULES.reduce((a, g) => a + g.requires.length, 0)} requirements`} tone="neutral" icon={IconShield} />
          <Kpi label="Active gate failures" value={GATE_FAILURES_SAMPLE.length} delta="see Gate failures tab" tone="down" icon={IconFlag} />
          <Kpi label="Individual overrides" value={GATE_RULES.reduce((a, g) => a + g.individualOverrides, 0)} delta="audit-trailed" tone="neutral" icon={IconStar} />
          <Kpi label="Time to active (median)" value="4.2 d" delta="from application to activation" tone="up" icon={IconClock} />
        </div>
        <Tabs active={tab} onChange={setTab} tabs={[
          { id: "rules",     label: "Gate rules",            count: GATE_RULES.length },
          { id: "failures",  label: "Active gate failures",   count: GATE_FAILURES_SAMPLE.length },
          { id: "overrides", label: "Individual overrides",   count: GATE_RULES.reduce((a, g) => a + g.individualOverrides, 0) },
        ]} />

        {tab === "rules"     && <RulesTab />}
        {tab === "failures"  && <FailuresTab go={go} />}
        {tab === "overrides" && <OverridesTab />}
      </div>
    </>
  );
};

// ---- RULES ----
const RulesTab = () => (
  <div style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 14 }}>
    {GATE_RULES.map(g => (
      <Card key={g.id}>
        <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 6 }}>
          <span style={{ ...g_over }}>{g.program}</span>
          <StatusChip status="confirmed" size="sm" label="Active" />
        </div>
        <div style={{ fontSize: 17, fontWeight: 500, marginBottom: 12 }}>{g.role}</div>
        <div style={{ ...g_over, marginBottom: 8 }}>Requires</div>
        <div style={{ display: "flex", flexDirection: "column", gap: 6, marginBottom: 14 }}>
          {g.requires.map(r => (
            <div key={r.id} style={{ display: "grid", gridTemplateColumns: "20px 1fr 160px", gap: 8, padding: "6px 10px", borderRadius: 8, background: r.req ? "var(--paper)" : "var(--paper-deep)", alignItems: "center", border: "1px solid var(--border-soft)" }}>
              <span style={{ width: 14, height: 14, borderRadius: 4, background: r.req ? "var(--coral-600)" : "var(--paper-deep)", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center" }}>
                {r.req && <IconCheck size={9} />}
              </span>
              <span style={{ fontSize: 12 }}>{r.name}</span>
              <span style={{ ...g_meta, textAlign: "right" }}>{r.completion}</span>
            </div>
          ))}
        </div>
        <div style={{ ...g_over, marginBottom: 6 }}>Blocks if incomplete</div>
        <div style={{ display: "flex", gap: 4, marginBottom: 10 }}>
          {g.blocks.map(b => <span key={b} style={{ fontSize: 11, padding: "3px 9px", borderRadius: 999, background: "var(--crimson-100)", color: "var(--crimson-600)", fontWeight: 500 }}>{b === "activation" ? "Activation" : b === "shift-signup" ? "Shift signup" : "Hour logging"}</span>)}
        </div>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <span style={{ ...g_meta }}>{g.individualOverrides} individual override{g.individualOverrides === 1 ? "" : "s"}</span>
          <Btn size="sm" kind="ghost" icon={IconEdit}>Edit</Btn>
        </div>
      </Card>
    ))}
  </div>
);

// ---- FAILURES (also used on volunteer detail to surface gate failure) ----
const FailuresTab = ({ go }) => (
  <>
    <p style={{ fontSize: 13, color: "var(--fg-2)", marginBottom: 14, maxWidth: 720 }}>
      Volunteers currently blocked by a gate. Each row is what they (and coordinators) see surfaced on signups, day-of rosters, and hour logging.
    </p>
    <Card padded={false}>
      <div style={{ display: "grid", gridTemplateColumns: "minmax(180px, 1.4fr) minmax(160px, 1.2fr) minmax(220px, 2fr) 130px 130px 36px", gap: 14, padding: "12px 18px", fontSize: 11, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--fg-3)", borderBottom: "1px solid var(--border)" }}>
        <span>Volunteer</span><span>Role</span><span>Missing requirement</span><span>Blocks</span><span>Site</span><span />
      </div>
      {GATE_FAILURES_SAMPLE.map((f, i, arr) => {
        const v = (window.VOLUNTEERS || []).find(x => x.id === f.vol);
        if (!v) return null;
        return (
          <div key={i} onClick={() => go("volunteer/" + v.id)} style={{ display: "grid", gridTemplateColumns: "minmax(180px, 1.4fr) minmax(160px, 1.2fr) minmax(220px, 2fr) 130px 130px 36px", gap: 14, padding: "13px 18px", alignItems: "center", borderBottom: i === arr.length - 1 ? "none" : "1px solid var(--border-soft)", cursor: "pointer", fontSize: 13 }}>
            <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
              <Avatar {...v} />
              <span style={{ fontWeight: 500 }}>{v.name}</span>
            </div>
            <span>{f.role}</span>
            <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
              {f.missing.map(m => <span key={m} style={{ fontSize: 11, padding: "3px 9px", borderRadius: 6, background: "var(--crimson-100)", color: "var(--crimson-600)", fontWeight: 500, alignSelf: "flex-start" }}>{m}</span>)}
            </div>
            <span style={{ fontSize: 11, color: "var(--crimson-600)", fontWeight: 500 }}>{f.action === "activation" ? "Activation" : f.action === "shift-signup" ? "Sign-up" : "Hour log"}</span>
            <span style={{ ...g_meta }}>{f.site}</span>
            <IconBtn icon={IconExternal} size={28} />
          </div>
        );
      })}
    </Card>
  </>
);

// ---- OVERRIDES ----
const OverridesTab = () => (
  <>
    <p style={{ fontSize: 13, color: "var(--fg-2)", marginBottom: 14, maxWidth: 720 }}>
      Individual gate overrides bypass a specific gate requirement for a specific volunteer. Used sparingly; every override carries a reason and audit trail.
    </p>
    <Card padded={false}>
      <div style={{ display: "grid", gridTemplateColumns: "minmax(180px, 1.2fr) minmax(180px, 1.4fr) minmax(220px, 1.8fr) 140px 130px", gap: 14, padding: "12px 18px", fontSize: 11, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--fg-3)", borderBottom: "1px solid var(--border)" }}>
        <span>Volunteer</span><span>Gate · skipped</span><span>Reason</span><span>Approved by</span><span>Expires</span>
      </div>
      {[
        { vol: "v-walsh",   gate: "Camp host · First aid", reason: "Acting as fill-in for one weekend; renewal scheduled within 30 days.", by: "Aliyah Chen", expires: "Jun 22, 2026" },
        { vol: "v-okonkwo", gate: "Hunter ed instructor · Background check", reason: "Active CPW staff — already screened through state HR. Documented offline.", by: "Marcus Chen", expires: "Lifetime" },
        { vol: "v-mendez",  gate: "Naturalist · RMN cert", reason: "Substituting a CSU graduate certificate equivalent — to be reviewed at end of year.", by: "Aliyah Chen", expires: "Dec 31, 2026" },
      ].map((o, i, arr) => {
        const v = (window.VOLUNTEERS || []).find(x => x.id === o.vol);
        if (!v) return null;
        return (
          <div key={i} style={{ display: "grid", gridTemplateColumns: "minmax(180px, 1.2fr) minmax(180px, 1.4fr) minmax(220px, 1.8fr) 140px 130px", gap: 14, padding: "13px 18px", alignItems: "center", borderBottom: i === arr.length - 1 ? "none" : "1px solid var(--border-soft)", fontSize: 13 }}>
            <div style={{ display: "flex", gap: 10, alignItems: "center" }}><Avatar {...v} /><span style={{ fontWeight: 500 }}>{v.name}</span></div>
            <span>{o.gate}</span>
            <span style={{ fontSize: 12, color: "var(--fg-2)", lineHeight: 1.4 }}>{o.reason}</span>
            <span style={{ ...g_meta }}>{o.by}</span>
            <span style={{ ...g_meta }}>{o.expires}</span>
          </div>
        );
      })}
    </Card>
    <div style={{ marginTop: 14, padding: 14, background: "var(--amber-100)", color: "var(--amber-600)", borderRadius: 12, fontSize: 12, lineHeight: 1.5 }}>
      <IconShield size={14} style={{ verticalAlign: "middle", marginRight: 6 }} />
      Each override creates an immutable audit entry and a calendar reminder for the approver before expiry. Overrides cannot be granted by the same person who requested them.
    </div>
  </>
);

// ============================================================
// REUSABLE GATE-FAILURE BANNER
// (Surfaced on signup, account overview, day-of roster, hour log)
// ============================================================
const GateFailureBanner = ({ missing, action, onResolve }) => (
  <div style={{ display: "grid", gridTemplateColumns: "auto 1fr auto", gap: 14, padding: "14px 16px", background: "var(--crimson-100)", color: "var(--crimson-600)", borderRadius: 12, alignItems: "center", marginBottom: 14 }}>
    <div style={{ width: 36, height: 36, borderRadius: 999, background: "var(--crimson-500)", color: "#FFFFFF", display: "flex", alignItems: "center", justifyContent: "center" }}>
      <IconShield size={18} />
    </div>
    <div>
      <div style={{ fontSize: 14, fontWeight: 500, color: "var(--ink)" }}>Can't proceed — {action === "activation" ? "activation" : action === "shift-signup" ? "shift signup" : "hour logging"} is blocked</div>
      <div style={{ fontSize: 12, color: "var(--ink)", lineHeight: 1.5, marginTop: 4 }}>
        Missing: {missing.join(", ")}.
      </div>
    </div>
    {onResolve && <Btn size="sm" kind="primary" onClick={onResolve}>Resolve now</Btn>}
  </div>
);

// ============================================================
Object.assign(window, { OrgGates, GateFailureBanner });
