// ===== org-lms-deep.jsx =====
// Staff-side LMS — replaces window.OrgTraining with a deeper module.
// Adds:
//   - Course detail screen (enrollments, completion funnel, quiz analytics, modules)
//   - Quiz analytics view (per-question accuracy + time)
//   - Assignment rules tab (auto-enroll by role, due dates, escalation)
//   - Keeps existing surfaces (catalog, certs, behind, builder, external LMS)

const {
  React,
  Card, Btn, IconBtn, StatusChip, Avatar, 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,
  VOLUNTEERS,
} = window;
const { useState: useOL, useMemo: useOLM, useEffect: useOLE } = React;

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

// ============================================================
// DATA
// ============================================================
const STAFF_COURSES = [
  { id: "co-1", title: "Camp host orientation",          program: "State parks",     time: "45 min", modules: 6, enrolled: 124, completion: 92, avgScore: 88,  required: true,  format: "video+quiz",   thumbColor: "var(--coral-700)", state: "published" },
  { id: "co-2", title: "Trail crew safety",              program: "State parks",     time: "30 min", modules: 4, enrolled: 86,  completion: 88, avgScore: 91,  required: true,  format: "video+quiz",   thumbColor: "var(--sage-700)",  state: "published" },
  { id: "co-3", title: "First aid refresher",            program: "All programs",    time: "30 min", modules: 5, enrolled: 186, completion: 72, avgScore: 85,  required: true,  format: "video+exam",   thumbColor: "var(--crimson-500)", state: "published" },
  { id: "co-4", title: "Wildlife encounter protocols",   program: "All programs",    time: "15 min", modules: 4, enrolled: 142, completion: 81, avgScore: 92,  required: false, format: "video+quiz",   thumbColor: "var(--sage-500)",  state: "published" },
  { id: "co-5", title: "Reservation system basics",      program: "State parks",     time: "20 min", modules: 4, enrolled: 124, completion: 96, avgScore: 94,  required: true,  format: "video+quiz",   thumbColor: "var(--iris-600)",  state: "published" },
  { id: "co-6", title: "Naturalist program",             program: "Education",       time: "60 min", modules: 8, enrolled: 38,  completion: 64, avgScore: 87,  required: false, format: "video+quiz",   thumbColor: "var(--amber-600)", state: "published" },
  { id: "co-7", title: "Hunter ed methodology",          program: "Hunter Outreach", time: "75 min", modules: 9, enrolled: 22,  completion: 86, avgScore: 90,  required: true,  format: "video+exam",   thumbColor: "var(--coral-600)", state: "published" },
  { id: "co-8", title: "Leave No Trace for volunteers",  program: "All programs",    time: "20 min", modules: 3, enrolled: 84,  completion: 78, avgScore: 89,  required: false, format: "video+quiz",   thumbColor: "var(--stone-700)", state: "published" },
];

const CERTS = [
  { id: "ce-1", name: "CPR / First Aid (Red Cross)",      validYears: 2, holders: 186, expiringSoon: 12, expired: 4, kind: "external" },
  { id: "ce-2", name: "Hunter Ed Instructor (Kalkomey)",  validYears: 3, holders: 22,  expiringSoon: 3,  expired: 1, kind: "external" },
  { id: "ce-3", name: "Camp Host (CPW internal)",          validYears: 1, holders: 124, expiringSoon: 18, expired: 0, kind: "internal" },
  { id: "ce-4", name: "Trail Crew Safety (CPW)",           validYears: 1, holders: 86,  expiringSoon: 8,  expired: 2, kind: "internal" },
  { id: "ce-5", name: "Wilderness First Responder",        validYears: 3, holders: 18,  expiringSoon: 2,  expired: 0, kind: "external" },
];

// ============================================================
// ROOT
// ============================================================
const OrgTraining = ({ go }) => {
  const [view, setView] = useOL("list");
  const [tab, setTab] = useOL("courses");
  const [activeCourseId, setActiveCourseId] = useOL(null);

  if (view === "course-detail") {
    const course = STAFF_COURSES.find(c => c.id === activeCourseId);
    if (course) return <CourseDetail course={course} onBack={() => setView("list")} go={go} />;
  }

  return (
    <>
      <TopBar title="Training &amp; LMS" subtitle={`${STAFF_COURSES.length} courses · 5 certifications tracked · ${STAFF_COURSES.reduce((a, c) => a + c.enrolled, 0).toLocaleString()} active enrollments`}
        primary={<Btn icon={IconPlus} onClick={() => setTab("builder")}>New course</Btn>}
        secondary={<Btn kind="secondary" icon={IconUpload}>Upload SCORM</Btn>} />
      <div style={{ flex: 1, overflow: "auto", padding: "20px 32px 56px" }}>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14, marginBottom: 24 }}>
          <Kpi label="Courses" value={STAFF_COURSES.length} delta={`${STAFF_COURSES.filter(c => c.required).length} required`} tone="neutral" icon={IconBook} />
          <Kpi label="Active enrollments" value="806" delta="+86 this month" tone="up" icon={IconUsers} />
          <Kpi label="Avg completion" value="81%" delta="across all required" tone="up" icon={IconCheck} />
          <Kpi label="Behind on required" value="14" delta="auto-paused signups" tone="down" icon={IconShield} />
        </div>

        <Tabs active={tab} onChange={setTab} tabs={[
          { id: "courses",     label: "Courses",        count: STAFF_COURSES.length },
          { id: "certs",       label: "Certifications", count: CERTS.length },
          { id: "behind",      label: "Behind on required", count: 14 },
          { id: "rules",       label: "Assignment rules", count: 6 },
          { id: "builder",     label: "Course builder" },
          { id: "lms",         label: "External LMS" },
        ]} />

        {tab === "courses" && (
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 14 }}>
            {STAFF_COURSES.map(c => (
              <StaffCourseCard key={c.id} c={c} onOpen={() => { setActiveCourseId(c.id); setView("course-detail"); }} />
            ))}
          </div>
        )}
        {tab === "certs"   && <CertsTable />}
        {tab === "behind"  && <BehindTable go={go} />}
        {tab === "rules"   && <AssignmentRules />}
        {tab === "builder" && <CourseBuilder />}
        {tab === "lms"     && <ExternalLMS />}
      </div>
    </>
  );
};

// ============================================================
// COURSE CARD (catalog)
// ============================================================
const StaffCourseCard = ({ c, onOpen }) => (
  <Card padded={false} style={{ cursor: "pointer" }} onClick={onOpen}>
    <div style={{ aspectRatio: "16/9", background: c.thumbColor, display: "flex", alignItems: "flex-end", padding: 14, position: "relative" }}>
      <div style={{ position: "absolute", top: 10, right: 10, display: "flex", gap: 6 }}>
        {c.required && <span style={{ fontSize: 10, padding: "2px 7px", borderRadius: 999, background: "rgba(0,0,0,0.4)", color: "#fff", fontWeight: 500 }}>Required</span>}
      </div>
      <div style={{ color: "#fff" }}>
        <div style={{ fontSize: 10, letterSpacing: "0.14em", textTransform: "uppercase", opacity: 0.85, marginBottom: 4 }}>{c.program}</div>
        <div style={{ fontFamily: "var(--font-display)", fontSize: 22, lineHeight: 1.1 }}>{c.title}</div>
      </div>
    </div>
    <div style={{ padding: 16 }}>
      <div style={{ display: "flex", gap: 14, fontSize: 11, color: "var(--fg-3)", marginBottom: 12, flexWrap: "wrap" }}>
        <span>{c.time}</span><span>{c.modules} modules</span><span>{c.format}</span>
      </div>
      <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, marginBottom: 5 }}>
        <span style={{ color: "var(--fg-2)" }}>{c.enrolled} enrolled · {c.completion}% complete</span>
      </div>
      <Progress value={c.completion} max={100} />
      <div style={{ display: "flex", gap: 6, marginTop: 12 }}>
        <Btn size="sm" kind="secondary" full>Open analytics</Btn>
      </div>
    </div>
  </Card>
);

// ============================================================
// COURSE DETAIL — deepest view
// ============================================================
const CourseDetail = ({ course, onBack, go }) => {
  const [tab, setTab] = useOL("overview");
  const c = course;

  return (
    <>
      <TopBar title={c.title}
        breadcrumb={["Training & LMS", c.title]} onBack={onBack}
        subtitle={`${c.program} · ${c.time} · ${c.format} · ${c.enrolled} enrolled · ${c.completion}% avg completion`}
        primary={<Btn icon={IconEdit}>Edit course</Btn>}
        secondary={<Btn kind="secondary" icon={IconMail}>Nudge non-starters</Btn>} />
      <div style={{ flex: 1, overflow: "auto", padding: "20px 32px 56px" }}>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14, marginBottom: 24 }}>
          <Kpi label="Enrolled" value={c.enrolled} delta="+12 this week" tone="up" icon={IconUsers} />
          <Kpi label="Completion" value={`${c.completion}%`} delta="across all enrolled" tone="up" icon={IconCheck} />
          <Kpi label="Avg score" value={`${c.avgScore}%`} delta="passing 80%" tone="up" icon={IconAward} />
          <Kpi label="Avg time-to-complete" value="3.2 d" delta="across all enrolled" tone="neutral" icon={IconClock} />
        </div>

        <Tabs active={tab} onChange={setTab} tabs={[
          { id: "overview",    label: "Overview" },
          { id: "modules",     label: "Modules", count: c.modules },
          { id: "enrollments", label: "Enrollments", count: c.enrolled },
          { id: "quiz",        label: "Quiz analytics" },
          { id: "rules",       label: "Assignment rules" },
          { id: "settings",    label: "Settings" },
        ]} />

        {tab === "overview"    && <CourseOverview c={c} />}
        {tab === "modules"     && <CourseModules c={c} />}
        {tab === "enrollments" && <CourseEnrollments c={c} go={go} />}
        {tab === "quiz"        && <QuizAnalytics c={c} />}
        {tab === "rules"       && <CourseAssignmentRules c={c} />}
        {tab === "settings"    && <CourseSettings c={c} />}
      </div>
    </>
  );
};

// ---- Course overview ----
const CourseOverview = ({ c }) => (
  <>
    <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1.6fr) minmax(280px, 1fr)", gap: 14 }}>
      <Card>
        <div style={{ ...ol_over, marginBottom: 14 }}>Completion funnel · last 30 days</div>
        {[
          { l: "Assigned", n: 138, pct: 100 },
          { l: "Started",  n: 124, pct: 90 },
          { l: "Hit quiz", n: 118, pct: 86 },
          { l: "Passed",   n: 108, pct: 78 },
          { l: "Cert issued (if applicable)", n: 104, pct: 75 },
        ].map(s => (
          <div key={s.l} style={{ marginBottom: 12 }}>
            <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, marginBottom: 4 }}>
              <span style={{ color: "var(--fg-1)" }}>{s.l}</span>
              <span style={{ color: "var(--fg-3)", fontVariantNumeric: "tabular-nums" }}>{s.n} · {s.pct}%</span>
            </div>
            <div style={{ height: 8, background: "var(--paper-deep)", borderRadius: 4, overflow: "hidden" }}>
              <div style={{ width: `${s.pct}%`, height: "100%", background: "var(--coral-600)" }} />
            </div>
          </div>
        ))}
        <div style={{ ...ol_over, margin: "20px 0 10px" }}>Where people drop off</div>
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          <DropoffRow label="Module 3 · CPR positioning" count={4} note="Avg watched 41% — likely too long" />
          <DropoffRow label="Module 4 · Wildlife scenarios" count={2} note="Most who reach here finish" />
          <DropoffRow label="Exam · Q14 'hardest question'" count={6} note="62% miss · review explanation copy" />
        </div>
      </Card>
      <Card>
        <div style={{ ...ol_over, marginBottom: 12 }}>About this course</div>
        <p style={{ fontSize: 13, color: "var(--fg-1)", lineHeight: 1.6, marginBottom: 16 }}>
          Recertify CPW field first-aid skills. Bleeding control, CPR positioning, when to call 911 vs. radio. Renewal valid 1 year. Issues the First Aid certification.
        </p>
        <RR label="Owner" v="Aliyah Chen" />
        <RR label="Last edited" v="May 14, 2026 (v4)" />
        <RR label="Auto-enrolled roles" v="Camp host · Trail crew · Naturalist" />
        <RR label="Linked certification" v="First aid / CPR · 1 yr" />
        <RR label="Passing score" v="80% · 3 attempts" />
        <RR label="Renewal trigger" v="11 months after issue · email volunteer" />
      </Card>
    </div>
  </>
);

const RR = ({ label, v }) => (
  <div style={{ display: "grid", gridTemplateColumns: "140px 1fr", gap: 10, padding: "8px 0", borderBottom: "1px dashed var(--border-soft)", fontSize: 12 }}>
    <span style={{ color: "var(--fg-3)" }}>{label}</span>
    <span style={{ color: "var(--ink)" }}>{v}</span>
  </div>
);
const DropoffRow = ({ label, count, note }) => (
  <div style={{ display: "grid", gridTemplateColumns: "1fr 60px", gap: 8, alignItems: "start", padding: "10px 12px", background: "var(--paper-deep)", borderRadius: 8 }}>
    <div>
      <div style={{ fontSize: 13, fontWeight: 500, color: "var(--ink)" }}>{label}</div>
      <div style={{ ...ol_meta, marginTop: 2 }}>{note}</div>
    </div>
    <div style={{ fontFamily: "var(--font-display)", fontSize: 20, color: "var(--crimson-600)", textAlign: "right", fontVariantNumeric: "tabular-nums" }}>{count}</div>
  </div>
);

// ---- Modules ----
const CourseModules = ({ c }) => {
  const mods = [
    { id: "m1", n: 1, type: "video", title: "When to step in (and when not to)", time: 6, completion: 96, drops: 0 },
    { id: "m2", n: 2, type: "video", title: "Bleeding control + tourniquets",    time: 7, completion: 92, drops: 1 },
    { id: "m3", n: 3, type: "video", title: "CPR positioning",                    time: 8, completion: 78, drops: 4 },
    { id: "m4", n: 4, type: "video", title: "Wildlife-specific scenarios",        time: 5, completion: 84, drops: 2 },
    { id: "m5", n: 5, type: "exam",  title: "Exam (20 questions · 80% to pass)",  time: 15, completion: 72, drops: 6, passRate: 86 },
  ];
  return (
    <Card padded={false}>
      <div style={{ display: "grid", gridTemplateColumns: "40px 36px 1fr 110px 130px 100px 36px", gap: 14, padding: "12px 18px", fontSize: 11, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--fg-3)", borderBottom: "1px solid var(--border)" }}>
        <span>#</span><span /><span>Module</span><span>Time</span><span>Completion</span><span>Drops</span><span />
      </div>
      {mods.map((m, i) => (
        <div key={m.id} style={{ display: "grid", gridTemplateColumns: "40px 36px 1fr 110px 130px 100px 36px", gap: 14, padding: "13px 18px", alignItems: "center", borderBottom: i === mods.length - 1 ? "none" : "1px solid var(--border-soft)" }}>
          <span style={{ fontFamily: "var(--font-display)", fontSize: 18, color: "var(--fg-3)" }}>{m.n}</span>
          <div style={{ width: 30, height: 30, borderRadius: 6, background: "var(--paper-deep)", color: "var(--fg-2)", display: "flex", alignItems: "center", justifyContent: "center" }}>
            {m.type === "video" ? <IconEye size={13} /> : m.type === "exam" ? <IconShield size={13} /> : <IconClipboard size={13} />}
          </div>
          <div>
            <div style={{ fontSize: 13, fontWeight: 500 }}>{m.title}</div>
            <div style={{ ...ol_meta, marginTop: 2, textTransform: "capitalize" }}>{m.type}{m.passRate ? ` · pass rate ${m.passRate}%` : ""}</div>
          </div>
          <span style={{ ...ol_meta }}>{m.time} min</span>
          <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
            <Progress value={m.completion} max={100} />
            <span style={{ fontSize: 11, color: "var(--fg-3)", fontVariantNumeric: "tabular-nums" }}>{m.completion}%</span>
          </div>
          <span style={{ fontSize: 12, color: m.drops > 2 ? "var(--crimson-600)" : "var(--fg-3)", fontVariantNumeric: "tabular-nums" }}>{m.drops}</span>
          <IconBtn icon={IconMore} size={28} />
        </div>
      ))}
    </Card>
  );
};

// ---- Enrollments ----
const CourseEnrollments = ({ c, go }) => {
  const [filter, setFilter] = useOL("all");

  const enrollments = VOLUNTEERS.slice(0, 8).map((v, i) => {
    const states = ["completed", "in-progress", "completed", "behind", "completed", "in-progress", "not-started", "completed"];
    const progresses = [100, 56, 100, 32, 100, 72, 0, 100];
    const dates = ["May 4", "May 18", "Apr 22", "Apr 18", "May 1", "May 16", "—", "Apr 30"];
    const scores = [92, null, 88, null, 96, null, null, 84];
    return { v, state: states[i], progress: progresses[i], lastActive: dates[i], score: scores[i] };
  });

  const filtered = filter === "all" ? enrollments : enrollments.filter(e => e.state === filter);

  return (
    <>
      <div style={{ display: "flex", gap: 8, marginBottom: 14 }}>
        {[
          { id: "all", t: "All", n: 124 },
          { id: "completed", t: "Completed", n: 89 },
          { id: "in-progress", t: "In progress", n: 22 },
          { id: "behind", t: "Behind", n: 7 },
          { id: "not-started", t: "Not started", n: 6 },
        ].map(f => (
          <button key={f.id} onClick={() => setFilter(f.id)} style={{
            background: filter === f.id ? "var(--ink)" : "transparent",
            color: filter === f.id ? "var(--paper)" : "var(--fg-1)",
            border: "1px solid " + (filter === f.id ? "var(--ink)" : "var(--border)"),
            padding: "7px 13px", borderRadius: 999, fontSize: 12, fontWeight: 500, cursor: "pointer", fontFamily: "inherit",
          }}>{f.t} <span style={{ opacity: 0.65, marginLeft: 4 }}>{f.n}</span></button>
        ))}
        <div style={{ marginLeft: "auto", display: "flex", gap: 6 }}>
          <Btn size="sm" kind="ghost" icon={IconMail}>Nudge selected</Btn>
          <Btn size="sm" kind="secondary" icon={IconDownload}>Export</Btn>
        </div>
      </div>
      <Card padded={false}>
        <div style={{ display: "grid", gridTemplateColumns: "30px minmax(200px, 1.4fr) 130px 130px 110px 100px 36px", gap: 14, padding: "12px 16px", fontSize: 11, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--fg-3)", borderBottom: "1px solid var(--border)" }}>
          <Checkbox checked={false} onChange={() => {}} aria-label="Select all" />
          <span>Volunteer</span><span>State</span><span>Progress</span><span>Last active</span><span>Score</span><span />
        </div>
        {filtered.map((e, i, arr) => (
          <div key={e.v.id} onClick={() => go("volunteer/" + e.v.id)} style={{ display: "grid", gridTemplateColumns: "30px minmax(200px, 1.4fr) 130px 130px 110px 100px 36px", gap: 14, padding: "12px 16px", alignItems: "center", borderBottom: i === arr.length - 1 ? "none" : "1px solid var(--border-soft)", cursor: "pointer", fontSize: 13 }}>
            <Checkbox checked={false} onChange={() => {}} />
            <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
              <Avatar {...e.v} />
              <div><div style={{ fontWeight: 500 }}>{e.v.name}</div><div style={{ ...ol_meta }}>{e.v.role}</div></div>
            </div>
            <StatusChip
              status={e.state === "completed" ? "confirmed" : e.state === "in-progress" ? "info" : e.state === "behind" ? "expired" : "pending"}
              size="sm"
              label={e.state === "completed" ? "Completed" : e.state === "in-progress" ? "In progress" : e.state === "behind" ? "Behind" : "Not started"} />
            <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
              <Progress value={e.progress} max={100} />
              <span style={{ fontSize: 11, color: "var(--fg-3)", fontVariantNumeric: "tabular-nums" }}>{e.progress}%</span>
            </div>
            <span style={{ ...ol_meta }}>{e.lastActive}</span>
            <span style={{ fontSize: 13, color: "var(--ink)" }}>{e.score != null ? `${e.score}%` : "—"}</span>
            <IconBtn icon={IconMore} size={28} />
          </div>
        ))}
      </Card>
    </>
  );
};

// ---- Quiz analytics ----
const QuizAnalytics = ({ c }) => {
  const questions = [
    { n: 1,  text: "When you start compressions on an adult, what's the correct hand position?",     accuracy: 96, time: 18, retake: 2 },
    { n: 2,  text: "How fast should chest compressions be?",                                           accuracy: 92, time: 14, retake: 4 },
    { n: 3,  text: "A volunteer is unconscious on a backcountry trail with weak signal. First step?", accuracy: 84, time: 22, retake: 8 },
    { n: 4,  text: "What does the acronym RICE stand for?",                                            accuracy: 88, time: 16, retake: 4 },
    { n: 14, text: "(hardest) For a severe arterial bleed below the knee, what's the cutoff time on the tourniquet?", accuracy: 38, time: 38, retake: 24 },
    { n: 15, text: "(2nd hardest) When you suspect a spinal injury, what's the rule about moving them?", accuracy: 54, time: 28, retake: 14 },
    { n: 16, text: "Which of these are NOT signs of an opioid overdose?", accuracy: 72, time: 22, retake: 8 },
  ];
  return (
    <>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14, marginBottom: 22 }}>
        <Kpi label="Pass rate" value="86%" delta="3 attempts allowed" tone="up" icon={IconCheck} />
        <Kpi label="Avg attempts" value="1.4" delta="of 3 allowed" tone="neutral" icon={IconBook} />
        <Kpi label="Hardest question" value="38%" delta="Q14 · tourniquet cutoff" tone="down" icon={IconShield} />
        <Kpi label="Avg time to complete" value="11m 42s" delta="of 15m allotted" tone="neutral" icon={IconClock} />
      </div>

      <SectionHead title="Per-question performance" action={<button style={{ background: "none", border: "none", color: "var(--coral-700)", fontSize: 12, fontWeight: 500, cursor: "pointer" }}>Sort by accuracy</button>} />
      <Card padded={false}>
        <div style={{ display: "grid", gridTemplateColumns: "40px minmax(0, 1.6fr) 130px 110px 100px 36px", gap: 14, padding: "12px 18px", fontSize: 11, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--fg-3)", borderBottom: "1px solid var(--border)" }}>
          <span>#</span><span>Question</span><span>Accuracy</span><span>Time (avg)</span><span>Retakes</span><span />
        </div>
        {questions.map((q, i, arr) => (
          <div key={q.n} style={{ display: "grid", gridTemplateColumns: "40px minmax(0, 1.6fr) 130px 110px 100px 36px", gap: 14, padding: "13px 18px", alignItems: "center", borderBottom: i === arr.length - 1 ? "none" : "1px solid var(--border-soft)" }}>
            <span style={{ fontFamily: "var(--font-display)", fontSize: 18, color: "var(--fg-3)", fontVariantNumeric: "tabular-nums" }}>Q{q.n}</span>
            <span style={{ fontSize: 13, color: "var(--ink)" }}>{q.text}</span>
            <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
              <div style={{ height: 6, flex: 1, background: "var(--paper-deep)", borderRadius: 3, overflow: "hidden" }}>
                <div style={{ width: `${q.accuracy}%`, height: "100%", background: q.accuracy < 60 ? "var(--crimson-500)" : q.accuracy < 80 ? "var(--amber-500)" : "var(--sage-500)" }} />
              </div>
              <span style={{ fontSize: 11, fontVariantNumeric: "tabular-nums", color: q.accuracy < 60 ? "var(--crimson-600)" : "var(--fg-1)" }}>{q.accuracy}%</span>
            </div>
            <span style={{ fontSize: 12, fontVariantNumeric: "tabular-nums" }}>{q.time}s</span>
            <span style={{ fontSize: 12, color: q.retake > 10 ? "var(--crimson-600)" : "var(--fg-2)", fontVariantNumeric: "tabular-nums" }}>{q.retake}</span>
            <IconBtn icon={IconExternal} size={28} />
          </div>
        ))}
      </Card>

      <div style={{ marginTop: 18, padding: 14, background: "var(--amber-100)", color: "var(--amber-600)", borderRadius: 12, display: "flex", gap: 14, alignItems: "center" }}>
        <IconShield size={18} />
        <div style={{ flex: 1, fontSize: 12, lineHeight: 1.5, color: "var(--ink)" }}>
          <strong>Q14</strong> has a 38% accuracy across 124 attempts. Consider reviewing the question copy, the corresponding module 3 video at 06:42, or both. Click the question to see the breakdown of which distractor learners pick most.
        </div>
        <Btn size="sm" kind="secondary">Review Q14</Btn>
      </div>
    </>
  );
};

// ---- Assignment rules (per-course) ----
const CourseAssignmentRules = ({ c }) => (
  <>
    <p style={{ fontSize: 13, color: "var(--fg-2)", marginBottom: 18, maxWidth: 620 }}>
      Define who's auto-enrolled and the due dates. Rules run when a volunteer's role changes or when this course is updated.
    </p>
    <Card style={{ marginBottom: 14 }}>
      <div style={{ ...ol_over, marginBottom: 14 }}>Auto-enroll when…</div>
      <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
        <RuleChip op="WHEN" desc="Role becomes 'Camp host'" />
        <RuleChip op="OR"   desc="Role becomes 'Trail crew'" />
        <RuleChip op="OR"   desc="Role becomes 'Naturalist'" />
        <RuleChip op="AND"  desc="Volunteer is active (status = active OR trainee)" />
        <Btn size="sm" kind="ghost" icon={IconPlus} style={{ alignSelf: "flex-start" }}>Add rule</Btn>
      </div>
    </Card>

    <Card style={{ marginBottom: 14 }}>
      <div style={{ ...ol_over, marginBottom: 14 }}>Due date</div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
        <Field label="Due">
          <Select defaultValue="before-shift" options={[
            { value: "on-enroll", label: "Immediately (no grace period)" },
            { value: "7d",        label: "7 days after enrollment" },
            { value: "14d",       label: "14 days after enrollment" },
            { value: "before-shift", label: "Before next confirmed shift" },
            { value: "fixed",     label: "Fixed date" },
          ]} />
        </Field>
        <Field label="If past due">
          <Select defaultValue="auto-pause" options={[
            { value: "auto-pause", label: "Auto-pause shift signups" },
            { value: "warn",       label: "Warn coordinator only" },
            { value: "none",       label: "No action" },
          ]} />
        </Field>
      </div>
    </Card>

    <Card>
      <div style={{ ...ol_over, marginBottom: 14 }}>Escalation</div>
      <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
        {[
          { t: "Day −7", what: "Reminder email to volunteer" },
          { t: "Day −3", what: "Reminder email + SMS (if opted in)" },
          { t: "Day 0",  what: "Auto-pause shift signups + notify coordinator" },
          { t: "Day +7", what: "Coordinator review · option to extend or override" },
        ].map(s => (
          <div key={s.t} style={{ display: "grid", gridTemplateColumns: "80px 1fr auto", gap: 10, padding: "10px 12px", border: "1px solid var(--border-soft)", borderRadius: 8 }}>
            <span style={{ fontFamily: "var(--font-display)", fontSize: 16 }}>{s.t}</span>
            <span style={{ fontSize: 13 }}>{s.what}</span>
            <IconBtn icon={IconMore} size={28} />
          </div>
        ))}
      </div>
    </Card>
  </>
);

const RuleChip = ({ op, desc }) => (
  <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "9px 12px", borderRadius: 10, background: "var(--paper)", border: "1px solid var(--border-soft)" }}>
    <span style={{ fontSize: 10, padding: "2px 7px", borderRadius: 4, background: op === "WHEN" ? "var(--coral-100)" : "var(--iris-100)", color: op === "WHEN" ? "var(--coral-700)" : "var(--iris-600)", fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.08em" }}>{op}</span>
    <span style={{ fontSize: 13, color: "var(--ink)", flex: 1 }}>{desc}</span>
    <IconBtn icon={IconX} size={24} />
  </div>
);

const CourseSettings = ({ c }) => (
  <Card>
    <Field label="Title"><Input defaultValue={c.title} /></Field>
    <Field label="Program"><Select defaultValue={c.program} options={["State parks", "Wildlife", "Education", "Hunter Outreach", "All programs"]} /></Field>
    <Field label="Passing score"><Select defaultValue="80" options={[{ value: "70", label: "70%" }, { value: "80", label: "80% (default)" }, { value: "90", label: "90%" }, { value: "100", label: "100%" }]} /></Field>
    <Field label="Attempts allowed"><Select defaultValue="3" options={["1", "2", "3", "Unlimited"]} /></Field>
    <Field label="Issues certification">
      <Select defaultValue="first-aid" options={[{ value: "none", label: "None" }, { value: "first-aid", label: "First aid / CPR · 1-year validity" }]} />
    </Field>
    <Field label="State">
      <Select defaultValue={c.state} options={[{ value: "draft", label: "Draft (only visible to authors)" }, { value: "published", label: "Published" }, { value: "archived", label: "Archived (no new enrollments)" }]} />
    </Field>
  </Card>
);

// ============================================================
// EXISTING TABS — kept from prior version, lightly updated
// ============================================================
const CertsTable = () => (
  <Card padded={false}>
    <div style={{ padding: "14px 18px", display: "grid", gridTemplateColumns: "1fr 110px 100px 130px 110px 100px", gap: 14, fontSize: 11, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--fg-3)", borderBottom: "1px solid var(--border-soft)" }}>
      <span>Certification</span><span>Validity</span><span>Holders</span><span>Expiring 30 days</span><span>Expired</span><span></span>
    </div>
    {CERTS.map((cert, i) => (
      <div key={cert.id} style={{ display: "grid", gridTemplateColumns: "1fr 110px 100px 130px 110px 100px", gap: 14, padding: "14px 18px", alignItems: "center", borderBottom: i < CERTS.length - 1 ? "1px solid var(--border-soft)" : "none", fontSize: 13 }}>
        <div>
          <div style={{ fontSize: 13, fontWeight: 500 }}>{cert.name}</div>
          <div style={{ fontSize: 11, color: "var(--fg-3)" }}>{cert.kind === "external" ? "Tracked from external upload" : "Issued through CPW LMS"}</div>
        </div>
        <span style={{ fontSize: 12, color: "var(--fg-2)" }}>{cert.validYears} years</span>
        <span style={{ fontVariantNumeric: "tabular-nums" }}>{cert.holders}</span>
        <span style={{ fontSize: 11, color: cert.expiringSoon > 0 ? "var(--amber-600)" : "var(--fg-3)", fontWeight: 500 }}>{cert.expiringSoon} due</span>
        <span style={{ fontSize: 11, color: cert.expired > 0 ? "var(--crimson-600)" : "var(--fg-3)", fontWeight: 500 }}>{cert.expired} expired</span>
        <Btn size="sm" kind="secondary">Manage</Btn>
      </div>
    ))}
  </Card>
);

const BehindTable = ({ go }) => {
  const rows = [
    { id: "v-park",    course: "Camp host orientation",    due: "Before Jun 1 start",  days: 19, status: "auto-paused" },
    { id: "v-liu",     course: "Reservation system basics",due: "Before Jun 1 start",  days: 19, status: "in-progress" },
    { id: "v-walsh",   course: "First aid refresher",      due: "Before May 23 shift", days: 10, status: "auto-paused" },
    { id: "v-tovar",   course: "Trail crew safety",        due: "Before Jun 7 shift",  days: 25, status: "not-started" },
    { id: "v-okonkwo", course: "First aid refresher",      due: "Before May 30 shift", days: 17, status: "in-progress" },
    { id: "v-mendez",  course: "Trail crew safety",        due: "Before Jun 14 shift", days: 32, status: "not-started" },
  ];
  return (
    <Card padded={false}>
      <div style={{ padding: "14px 18px", display: "grid", gridTemplateColumns: "1fr 1fr 1fr 140px 200px", gap: 14, fontSize: 11, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--fg-3)", borderBottom: "1px solid var(--border-soft)" }}>
        <span>Volunteer</span><span>Course due</span><span>Deadline</span><span>Status</span><span></span>
      </div>
      {rows.map((r, i) => {
        const v = VOLUNTEERS.find(x => x.id === r.id);
        if (!v) return null;
        return (
          <div key={i} style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr 140px 200px", gap: 14, padding: "14px 18px", alignItems: "center", borderBottom: i < rows.length - 1 ? "1px solid var(--border-soft)" : "none", fontSize: 13 }}>
            <div onClick={() => go("volunteer/" + r.id)} style={{ display: "flex", alignItems: "center", gap: 10, cursor: "pointer" }}>
              <Avatar {...v} />
              <div>
                <div style={{ fontWeight: 500 }}>{v.name}</div>
                <div style={{ fontSize: 11, color: "var(--fg-3)" }}>{v.role}</div>
              </div>
            </div>
            <span style={{ fontSize: 13 }}>{r.course}</span>
            <span style={{ fontSize: 12, color: "var(--fg-2)" }}>{r.due} <span style={{ color: r.days < 14 ? "var(--coral-600)" : "var(--fg-3)" }}>· {r.days}d</span></span>
            <span style={{ fontSize: 11, padding: "2px 8px", borderRadius: 999, background: r.status === "auto-paused" ? "var(--crimson-100)" : r.status === "in-progress" ? "var(--iris-100)" : "var(--amber-100)", color: r.status === "auto-paused" ? "var(--crimson-600)" : r.status === "in-progress" ? "var(--iris-600)" : "var(--amber-600)", fontWeight: 500, justifySelf: "start" }}>
              {r.status === "auto-paused" ? "Signups paused" : r.status === "in-progress" ? "In progress" : "Not started"}
            </span>
            <div style={{ display: "flex", gap: 6, justifyContent: "flex-end" }}>
              <Btn size="sm" kind="secondary" icon={IconMail}>Nudge</Btn>
              <Btn size="sm" kind="ghost">Override</Btn>
            </div>
          </div>
        );
      })}
    </Card>
  );
};

// ============================================================
// ASSIGNMENT RULES (global tab) — separate from per-course rules
// ============================================================
const AssignmentRules = () => (
  <>
    <p style={{ fontSize: 13, color: "var(--fg-2)", marginBottom: 18, maxWidth: 720 }}>
      Global rules that map roles + lifecycle states to training & certifications. Volunteers see their full requirement list on their training dashboard.
    </p>
    <Card padded={false}>
      <div style={{ padding: "12px 16px", borderBottom: "1px solid var(--border)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <div style={{ ...ol_over }}>Rules · 6 active</div>
        <Btn size="sm" kind="secondary" icon={IconPlus}>New rule</Btn>
      </div>
      {[
        { name: "Camp host onboarding pack",       roles: ["Camp host"],                                    courses: 3, due: "Before first shift",     state: "active" },
        { name: "Trail crew safety",                roles: ["Trail crew", "Trail steward"],                  courses: 2, due: "Within 30 days of role",  state: "active" },
        { name: "Hunter ed instructor setup",       roles: ["Hunter ed instructor"],                          courses: 4, due: "Within 60 days of role",  state: "active" },
        { name: "First aid certification renewal",  roles: ["Camp host", "Trail steward", "Naturalist"],     courses: 1, due: "11 mo after issue",        state: "active" },
        { name: "Naturalist program",                roles: ["Naturalist"],                                    courses: 3, due: "Before first program",    state: "active" },
        { name: "Wildlife encounters (recommended)", roles: ["All field roles"],                               courses: 1, due: "—",                          state: "draft" },
      ].map((r, i, arr) => (
        <div key={i} style={{ display: "grid", gridTemplateColumns: "minmax(200px, 1.6fr) minmax(180px, 1.2fr) 110px 180px 100px 36px", gap: 14, padding: "13px 16px", alignItems: "center", borderBottom: i === arr.length - 1 ? "none" : "1px solid var(--border-soft)", fontSize: 13 }}>
          <div>
            <div style={{ fontWeight: 500 }}>{r.name}</div>
            <div style={{ ...ol_meta, marginTop: 2 }}>{r.courses} course{r.courses === 1 ? "" : "s"}</div>
          </div>
          <div style={{ display: "flex", gap: 4, flexWrap: "wrap" }}>
            {r.roles.map(role => <span key={role} style={{ fontSize: 11, padding: "2px 8px", borderRadius: 999, background: "var(--paper-deep)", color: "var(--fg-1)" }}>{role}</span>)}
          </div>
          <span style={{ fontSize: 12, color: "var(--fg-2)" }}>{r.courses}</span>
          <span style={{ fontSize: 12, color: "var(--fg-2)" }}>{r.due}</span>
          <StatusChip status={r.state === "active" ? "confirmed" : "draft"} size="sm" label={r.state === "active" ? "Active" : "Draft"} />
          <IconBtn icon={IconMore} size={28} />
        </div>
      ))}
    </Card>

    <div style={{ marginTop: 18, padding: 14, background: "var(--iris-100)", color: "var(--iris-600)", borderRadius: 12, fontSize: 12, lineHeight: 1.5 }}>
      <IconShield size={14} style={{ verticalAlign: "middle", marginRight: 6 }} />
      When a rule changes, affected volunteers see the new requirement on their next session. If shifts depend on a now-required course, they're auto-paused with a coordinator notification.
    </div>
  </>
);

// ============================================================
// COURSE BUILDER (existing — preserved)
// ============================================================
const CourseBuilder = () => (
  <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1.4fr) minmax(280px, 1fr)", gap: 18 }}>
    <Card>
      <Field label="Course title"><Input defaultValue="Wildlife encounter protocols v2" /></Field>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
        <Field label="Program"><Select options={["All programs", "State parks", "Hunter Outreach", "Naturalists", "Community Science"]} /></Field>
        <Field label="Estimated time"><Input defaultValue="25 min" /></Field>
      </div>
      <Field label="Modules">
        <div style={{ display: "grid", gap: 8 }}>
          {[
            { type: "Video",    title: "Intro — coexisting with wildlife",   time: "6 min" },
            { type: "Text",     title: "Bear protocol",                       time: "5 min" },
            { type: "Video",    title: "Mountain lion encounters",            time: "4 min" },
            { type: "Document", title: "Reference PDF — what to carry",       time: "—" },
            { type: "Quiz",     title: "Knowledge check (8 questions)",       time: "10 min" },
          ].map((m, i) => (
            <div key={i} style={{ display: "grid", gridTemplateColumns: "auto 80px 1fr auto auto", gap: 12, padding: "10px 12px", background: "var(--paper)", border: "1px solid var(--border-soft)", borderRadius: 10, alignItems: "center" }}>
              <div style={{ width: 28, height: 28, borderRadius: 7, background: "var(--paper-deep)", color: "var(--fg-2)", display: "flex", alignItems: "center", justifyContent: "center" }}>
                {m.type === "Video" ? <IconEye size={13} /> : m.type === "Quiz" ? <IconClipboard size={13} /> : m.type === "Document" ? <IconBook size={13} /> : <IconEdit size={13} />}
              </div>
              <span style={{ fontSize: 11, color: "var(--fg-3)" }}>{m.type}</span>
              <span style={{ fontSize: 13, color: "var(--ink)" }}>{m.title}</span>
              <span style={{ fontSize: 11, color: "var(--fg-3)" }}>{m.time}</span>
              <IconBtn icon={IconMore} size={28} />
            </div>
          ))}
          <Btn size="sm" kind="ghost" icon={IconPlus} style={{ alignSelf: "flex-start" }}>Add module</Btn>
        </div>
      </Field>
    </Card>
    <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      <Card>
        <div style={{ ...ol_over, marginBottom: 14 }}>Module types supported</div>
        {[
          { i: IconEye,       t: "Video",                  d: "Embed or upload (MP4, WebM). Auto-thumbnail." },
          { i: IconEdit,      t: "Text + rich media",       d: "Markdown editor with images, links." },
          { i: IconBook,      t: "Document",                d: "PDF, DOCX. Downloadable." },
          { i: IconClipboard, t: "Quiz",                    d: "Multiple choice, true/false, free-text grading." },
          { i: IconAward,     t: "Exam",                    d: "Pass/fail with attempts and proctor option." },
          { i: IconExternal,  t: "External (SCORM/xAPI)",  d: "Import from Articulate, Rise, Captivate." },
        ].map(m => (
          <div key={m.t} style={{ display: "grid", gridTemplateColumns: "auto 1fr", gap: 10, padding: "8px 0", borderTop: "1px solid var(--border-soft)", alignItems: "flex-start" }}>
            <div style={{ width: 26, height: 26, borderRadius: 7, background: "var(--paper-deep)", color: "var(--fg-2)", display: "flex", alignItems: "center", justifyContent: "center" }}><m.i size={13} /></div>
            <div>
              <div style={{ fontSize: 13, fontWeight: 500 }}>{m.t}</div>
              <div style={{ fontSize: 11, color: "var(--fg-3)" }}>{m.d}</div>
            </div>
          </div>
        ))}
      </Card>
      <Card>
        <div style={{ ...ol_over, marginBottom: 10 }}>Auto-enrollment</div>
        <div style={{ fontSize: 12, color: "var(--fg-2)", lineHeight: 1.55, marginBottom: 12 }}>This course will be automatically required for volunteers in selected roles.</div>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
          {["Camp host", "Trail steward", "Naturalist"].map(r => <span key={r} style={{ fontSize: 11, padding: "3px 9px", borderRadius: 999, background: "var(--sage-700)", color: "#fff", fontWeight: 500 }}>{r} ×</span>)}
          <Btn size="sm" kind="ghost" icon={IconPlus}>Role</Btn>
        </div>
      </Card>
    </div>
  </div>
);

// ============================================================
// EXTERNAL LMS (existing — preserved)
// ============================================================
const ExternalLMS = () => (
  <Card>
    <div style={{ ...ol_over, marginBottom: 14 }}>External LMS integration (optional)</div>
    <div style={{ fontSize: 13, color: "var(--fg-2)", marginBottom: 18, lineHeight: 1.55 }}>Send roster, completions, and certifications to and from external LMS platforms. Configurable — no preferred vendor.</div>
    {[
      { name: "Articulate Rise 360", status: "Not connected", desc: "Import published Rise courses as SCORM.", color: "var(--iris-100)" },
      { name: "Adobe Captivate",      status: "Not connected", desc: "Import .cptx published packages.", color: "var(--coral-100)" },
      { name: "Kalkomey (Hunter Ed)", status: "Connected · sync nightly", desc: "Imports instructor records and certification status.", color: "var(--sage-100)", connected: true },
      { name: "Moodle",                status: "Not connected", desc: "Send completions via LTI.", color: "var(--amber-100)" },
    ].map((p, i) => (
      <div key={p.name} style={{ display: "grid", gridTemplateColumns: "auto 1fr auto auto", gap: 14, padding: "14px 0", alignItems: "center", borderTop: i > 0 ? "1px solid var(--border-soft)" : "none" }}>
        <div style={{ width: 36, height: 36, borderRadius: 8, background: p.color, display: "flex", alignItems: "center", justifyContent: "center", color: "var(--ink)" }}><IconBook size={16} /></div>
        <div>
          <div style={{ fontSize: 13, fontWeight: 500 }}>{p.name}</div>
          <div style={{ fontSize: 11, color: "var(--fg-3)" }}>{p.desc}</div>
        </div>
        <span style={{ fontSize: 11, color: p.connected ? "var(--sage-700)" : "var(--fg-3)" }}>{p.status}</span>
        <Btn size="sm" kind={p.connected ? "secondary" : "primary"}>{p.connected ? "Manage" : "Connect"}</Btn>
      </div>
    ))}
  </Card>
);

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