// ===== m9-resources.jsx =====
// M9 · Resource library — FR4

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, IconMore, IconMail, IconFlag, IconClipboard, IconCal, IconPin,
} = window;
const { useState: useR9 } = React;

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

const RESOURCES = [
  { id: "r-trail-handbook",  type: "doc",   name: "Trail crew handbook · 2026 edition",        category: "Handbook",      audience: "Trail crew", scope: "Statewide", owner: "Priya Sandoval",  updated: "May 14, 2026", state: "published", size: "8.4 MB", links: ["Opportunities · Trail crew", "Onboarding tasks"] },
  { id: "r-camp-handbook",   type: "doc",   name: "Camp host handbook · 2026",                  category: "Handbook",      audience: "Camp host", scope: "Statewide", owner: "Aliyah Chen",      updated: "Mar 28, 2026", state: "published", size: "12.1 MB", links: ["Camp host orientation course", "Camp host roles"] },
  { id: "r-bear-protocol",   type: "doc",   name: "Bear encounter protocol · field card",       category: "Field reference", audience: "Volunteers", scope: "Statewide", owner: "Marcus Chen",   updated: "Apr 18, 2026", state: "published", size: "1.2 MB", links: ["Wildlife encounters course"] },
  { id: "r-tools",           type: "video", name: "Trail tools: pick, mattock, McLeod",         category: "Skill",         audience: "Volunteers", scope: "Statewide", owner: "Priya Sandoval",  updated: "May 8, 2026", state: "published", size: "84 MB · 12 min", links: ["Trail crew safety course"] },
  { id: "r-map-cherry",      type: "map",   name: "Cherry Creek SP volunteer area map",        category: "Map",           audience: "Volunteers + staff", scope: "Cherry Creek SP", owner: "Marcus Chen", updated: "May 1, 2026", state: "published", size: "2.4 MB", links: ["Cherry Creek shoreline cleanup", "Site page"] },
  { id: "r-map-boyd",        type: "map",   name: "Boyd Lake SP volunteer area map",            category: "Map",           audience: "Volunteers + staff", scope: "Boyd Lake SP",    owner: "Aliyah Chen",  updated: "Apr 22, 2026", state: "published", size: "2.8 MB", links: ["Boyd Lake trail crew", "Site page"] },
  { id: "r-er-card",         type: "doc",   name: "Emergency contacts · pocket card",           category: "Field reference", audience: "Volunteers", scope: "Statewide", owner: "Aliyah Chen",  updated: "Feb 8, 2026", state: "published", size: "184 KB", links: ["All onboarding tasks"] },
  { id: "r-photo-release",   type: "doc",   name: "Photo / media release form",                 category: "Form",          audience: "Volunteers", scope: "Statewide", owner: "Priya Sandoval", updated: "Jan 5, 2026", state: "published", size: "120 KB", links: ["Onboarding agreements"] },
  { id: "r-grant-hunter",    type: "doc",   name: "Hunter Outreach grant FAQ (staff)",          category: "Staff guide",   audience: "Staff only", scope: "Statewide", owner: "Aliyah Chen",  updated: "May 4, 2026", state: "published", size: "320 KB", links: ["Hunter ed program"], staffOnly: true },
  { id: "r-recon-photos",    type: "photos",name: "Trail conditions · spring 2026 photos",      category: "Field reference", audience: "Staff only", scope: "Statewide", owner: "Priya Sandoval", updated: "May 18, 2026", state: "published", size: "48 photos", links: ["Trail crew workdays"], staffOnly: true },
  { id: "r-storify",         type: "link",  name: "Stories Engine · public photo wall",         category: "External link", audience: "Volunteers + staff", scope: "Statewide", owner: "Marcus Chen", updated: "Apr 1, 2026", state: "published", size: "—", links: ["Account overview"], url: "https://stories.cpw.state.co.us" },
  { id: "r-arc-recovery",    type: "doc",   name: "Burn scar restoration guidance · 2026",      category: "Field reference", audience: "Volunteers + staff", scope: "Statewide", owner: "Aliyah Chen",  updated: "Mar 12, 2026", state: "archived", size: "4.2 MB", links: [] },
  { id: "r-draft-camp",      type: "doc",   name: "Camp host weekly checklist (draft)",         category: "Field reference", audience: "Camp host", scope: "Statewide", owner: "Aliyah Chen",  updated: "Today", state: "draft", size: "180 KB", links: [] },
];

const CATEGORIES = ["Handbook", "Field reference", "Map", "Form", "Skill", "Staff guide", "External link"];

// ============================================================
// ROOT
// ============================================================
const OrgResources = ({ go }) => {
  const [tab, setTab] = useR9("library");
  const [q, setQ] = useR9("");
  const [cat, setCat] = useR9("all");
  const [stateFilter, setStateFilter] = useR9("published");
  const [uploadOpen, setUploadOpen] = useR9(false);

  return (
    <>
      <TopBar title="Resource library"
        subtitle={`${RESOURCES.filter(r => r.state === "published").length} published · ${RESOURCES.filter(r => r.state === "draft").length} draft · ${RESOURCES.filter(r => r.state === "archived").length} archived · tenant-scoped, audience-permissioned`}
        primary={<Btn icon={IconPlus} onClick={() => setUploadOpen(true)}>Add resource</Btn>}
        secondary={<Btn kind="secondary" icon={IconDownload}>Export library</Btn>} />
      <div style={{ flex: 1, overflow: "auto", padding: "20px 32px 56px" }}>
        <Tabs active={tab} onChange={setTab} tabs={[
          { id: "library",     label: "Library",     count: RESOURCES.length },
          { id: "categories",  label: "Categories",   count: CATEGORIES.length },
          { id: "audit",       label: "Access log" },
        ]} />

        {tab === "library" && (
          <>
            <Card style={{ padding: 14, marginBottom: 16 }}>
              <div style={{ display: "grid", gridTemplateColumns: "minmax(180px, 2fr) 200px 160px auto", gap: 10, alignItems: "end" }}>
                <Field label="Search">
                  <div style={{ position: "relative" }}>
                    <Input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Trail handbook, bear protocol…" style={{ width: "100%", paddingLeft: 32 }} />
                    <IconSearch size={14} style={{ position: "absolute", left: 12, top: 12, color: "var(--fg-3)" }} />
                  </div>
                </Field>
                <Field label="Category">
                  <Select value={cat} onChange={(e) => setCat(e.target.value)}
                    options={[{ value: "all", label: "All categories" }, ...CATEGORIES.map(c => ({ value: c, label: c }))]} />
                </Field>
                <Field label="State">
                  <Select value={stateFilter} onChange={(e) => setStateFilter(e.target.value)}
                    options={[
                      { value: "all", label: "All" },
                      { value: "published", label: "Published" },
                      { value: "draft", label: "Draft" },
                      { value: "archived", label: "Archived" },
                    ]} />
                </Field>
                <Btn kind="ghost" size="sm" onClick={() => { setQ(""); setCat("all"); setStateFilter("published"); }}>Reset</Btn>
              </div>
            </Card>

            <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 14 }}>
              {RESOURCES.filter(r => {
                if (stateFilter !== "all" && r.state !== stateFilter) return false;
                if (cat !== "all" && r.category !== cat) return false;
                if (q && !(r.name + r.category + r.audience).toLowerCase().includes(q.toLowerCase())) return false;
                return true;
              }).map(r => <ResourceCard key={r.id} r={r} />)}
            </div>
          </>
        )}

        {tab === "categories" && <CategoriesTab />}
        {tab === "audit"      && <AuditLog />}
      </div>

      {uploadOpen && <UploadDrawer onClose={() => setUploadOpen(false)} />}
    </>
  );
};

// ============================================================
// RESOURCE CARD
// ============================================================
const ResourceCard = ({ r }) => {
  const iconFor = (t) => t === "video" ? <IconEye size={18} /> : t === "map" ? <IconPin size={18} /> : t === "link" ? <IconExternal size={18} /> : t === "photos" ? <IconStar size={18} /> : <IconBook size={18} />;
  return (
    <Card padded={false}>
      <div style={{ aspectRatio: "16/9", background: r.type === "video" ? "var(--coral-700)" : r.type === "map" ? "var(--sage-700)" : r.type === "link" ? "var(--iris-600)" : r.type === "photos" ? "var(--amber-600)" : "var(--stone-700)", display: "flex", alignItems: "center", justifyContent: "center", color: "rgba(255,255,255,0.85)" }}>
        <div style={{ width: 56, height: 56, borderRadius: 12, background: "rgba(255,255,255,0.18)", display: "flex", alignItems: "center", justifyContent: "center" }}>
          {iconFor(r.type)}
        </div>
      </div>
      <div style={{ padding: 14 }}>
        <div style={{ display: "flex", gap: 6, marginBottom: 6 }}>
          <span style={{ fontSize: 10, padding: "2px 7px", borderRadius: 999, background: "var(--paper-deep)", color: "var(--fg-2)", fontWeight: 500 }}>{r.category}</span>
          {r.staffOnly && <span style={{ fontSize: 10, padding: "2px 7px", borderRadius: 999, background: "var(--iris-100)", color: "var(--iris-600)", fontWeight: 500 }}>Staff only</span>}
          {r.state === "draft" && <span style={{ fontSize: 10, padding: "2px 7px", borderRadius: 999, background: "var(--amber-100)", color: "var(--amber-600)", fontWeight: 500 }}>Draft</span>}
          {r.state === "archived" && <span style={{ fontSize: 10, padding: "2px 7px", borderRadius: 999, background: "var(--paper-deep)", color: "var(--fg-3)", fontWeight: 500 }}>Archived</span>}
        </div>
        <div style={{ fontSize: 14, fontWeight: 500, color: "var(--ink)", marginBottom: 6, lineHeight: 1.3 }}>{r.name}</div>
        <div style={{ ...r_meta, marginBottom: 10 }}>Audience: {r.audience} · Scope: {r.scope}</div>
        <div style={{ ...r_meta, marginBottom: 10 }}>{r.size} · Updated {r.updated} by {r.owner}</div>
        {r.links.length > 0 && (
          <div style={{ ...r_meta, marginBottom: 12 }}>
            Attached to: {r.links.slice(0, 2).join(", ")}{r.links.length > 2 ? ` +${r.links.length - 2}` : ""}
          </div>
        )}
        <div style={{ display: "flex", gap: 6 }}>
          <Btn size="sm" kind="secondary" icon={r.type === "link" ? IconExternal : IconDownload} full>{r.type === "link" ? "Open" : "Preview"}</Btn>
          <IconBtn icon={IconMore} size={32} />
        </div>
      </div>
    </Card>
  );
};

// ============================================================
// CATEGORIES TAB
// ============================================================
const CategoriesTab = () => (
  <>
    <p style={{ fontSize: 13, color: "var(--fg-2)", marginBottom: 14, maxWidth: 620 }}>
      Categories help volunteers and staff find what they need fast. Reorder them to control how the library is browsed.
    </p>
    <Card padded={false}>
      <div style={{ display: "grid", gridTemplateColumns: "30px 1fr 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 /><span>Category</span><span>Resources</span><span>Default audience</span><span />
      </div>
      {CATEGORIES.map((c, i, arr) => {
        const n = RESOURCES.filter(r => r.category === c).length;
        return (
          <div key={c} style={{ display: "grid", gridTemplateColumns: "30px 1fr 130px 130px 36px", gap: 14, padding: "13px 18px", alignItems: "center", borderBottom: i === arr.length - 1 ? "none" : "1px solid var(--border-soft)", fontSize: 13 }}>
            <span style={{ fontFamily: "var(--font-mono)", color: "var(--fg-3)" }}>⋮⋮</span>
            <span style={{ fontWeight: 500 }}>{c}</span>
            <span style={{ fontSize: 13, fontVariantNumeric: "tabular-nums" }}>{n}</span>
            <span style={{ ...r_meta }}>{c === "Staff guide" ? "Staff only" : "Volunteers + staff"}</span>
            <IconBtn icon={IconMore} size={28} />
          </div>
        );
      })}
    </Card>
  </>
);

// ============================================================
// ACCESS LOG
// ============================================================
const AuditLog = () => (
  <>
    <p style={{ fontSize: 13, color: "var(--fg-2)", marginBottom: 14, maxWidth: 620 }}>
      Resource access is audited for staff-only and sensitive resources. Public volunteer-facing downloads are aggregated.
    </p>
    <Card padded={false}>
      {[
        { who: "Priya Sandoval", what: "Uploaded 'Trail crew handbook · 2026 edition' v3.1",  when: "May 14, 2026 · 11:14 am",  ref: "res-pub-trail-v31" },
        { who: "Aliyah Chen",    what: "Published 'Camp host weekly checklist' draft → live",  when: "May 12, 2026 · 4:08 pm",   ref: "res-pub-camp-check" },
        { who: "Marcus Chen",     what: "Archived 'Burn scar restoration guidance · 2026'",    when: "May 6, 2026 · 9:18 am",    ref: "res-arc-recovery" },
        { who: "Aliyah Chen",     what: "Downloaded 'Hunter Outreach grant FAQ' (staff-only)",  when: "Today · 8:42 am",         ref: "res-grant-hunter" },
        { who: "Priya Sandoval", what: "Linked 'Cherry Creek SP map' to opportunity",          when: "Today · 7:14 am",          ref: "res-map-cherry" },
        { who: "System",          what: "Auto-suppressed 2 staff-only resources from a volunteer search query", when: "Today · 6:02 am", ref: "res-sup-search-3k" },
      ].map((e, i, arr) => (
        <div key={i} style={{ display: "grid", gridTemplateColumns: "160px minmax(0, 2fr) minmax(160px, 1fr) 140px", gap: 14, padding: "13px 18px", alignItems: "center", borderBottom: i === arr.length - 1 ? "none" : "1px solid var(--border-soft)", fontSize: 13 }}>
          <span style={{ fontWeight: 500 }}>{e.who}</span>
          <span>{e.what}</span>
          <code style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--fg-3)" }}>{e.ref}</code>
          <span style={{ ...r_meta }}>{e.when}</span>
        </div>
      ))}
    </Card>
  </>
);

// ============================================================
// UPLOAD DRAWER
// ============================================================
const UploadDrawer = ({ onClose }) => (
  <div style={overlay} onClick={onClose}>
    <div style={drawer} onClick={(e) => e.stopPropagation()}>
      <div style={drawerHead}>
        <div>
          <div style={r_over}>Add resource</div>
          <div style={{ fontSize: 19, fontWeight: 500, color: "var(--ink)", marginTop: 4 }}>Upload a file or link an external resource</div>
        </div>
        <IconBtn icon={IconX} size={32} onClick={onClose} aria-label="Close" />
      </div>
      <div style={{ flex: 1, overflow: "auto", padding: 24 }}>
        <Field label="Type">
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 8 }}>
            {[
              { id: "file", t: "Upload file",    d: "PDF, DOCX, image, video" },
              { id: "link", t: "External link",   d: "Maps, Google Doc, partner site" },
              { id: "embed", t: "Embed",          d: "YouTube, Vimeo, Storify" },
            ].map((o, i) => (
              <Card key={o.id} style={{ padding: 14, cursor: "pointer", borderColor: i === 0 ? "var(--coral-500)" : "var(--border-soft)", borderWidth: i === 0 ? 2 : 1 }}>
                <div style={{ fontSize: 13, fontWeight: 500 }}>{o.t}</div>
                <div style={{ ...r_meta, marginTop: 4 }}>{o.d}</div>
              </Card>
            ))}
          </div>
        </Field>

        <div style={{ padding: 30, border: "2px dashed var(--stone-300)", borderRadius: 12, textAlign: "center", background: "var(--paper)", marginBottom: 16 }}>
          <IconUpload size={36} style={{ color: "var(--fg-3)", margin: "0 auto 14px" }} />
          <div style={{ fontSize: 14, fontWeight: 500, marginBottom: 4 }}>Drop file here, or browse</div>
          <div style={{ fontSize: 11, color: "var(--fg-3)" }}>Up to 100 MB · PDF, DOCX, MP4, PNG, JPG</div>
          <Btn size="sm" kind="secondary" style={{ marginTop: 12 }}>Choose file…</Btn>
        </div>

        <Field label="Title" required><Input placeholder="e.g. Trail crew handbook · 2026 edition" /></Field>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
          <Field label="Category" required>
            <Select defaultValue="Handbook" options={CATEGORIES} />
          </Field>
          <Field label="State">
            <Select defaultValue="draft" options={[{ value: "draft", label: "Draft (not visible)" }, { value: "published", label: "Publish now" }]} />
          </Field>
        </div>
        <Field label="Description">
          <Textarea rows={3} placeholder="Short description shown in the library card." />
        </Field>

        <div style={{ ...r_over, margin: "16px 0 10px" }}>Audience &amp; scope</div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
          <Field label="Audience">
            <Select defaultValue="vol-staff" options={[
              { value: "vol-staff", label: "Volunteers + staff" },
              { value: "vol-only",  label: "Volunteers only" },
              { value: "staff-only",label: "Staff only" },
              { value: "role",      label: "Specific role(s)…" },
            ]} />
          </Field>
          <Field label="Scope">
            <Select defaultValue="statewide" options={[
              { value: "statewide", label: "Statewide" },
              { value: "region",    label: "Region…" },
              { value: "site",      label: "Specific site…" },
              { value: "program",   label: "Specific program…" },
            ]} />
          </Field>
        </div>

        <div style={{ ...r_over, margin: "16px 0 10px" }}>Attach to context (optional)</div>
        <Field label="Show this resource on…">
          <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
            <span style={{ fontSize: 12, padding: "5px 10px", borderRadius: 999, background: "var(--paper-deep)", color: "var(--fg-1)" }}>Onboarding tasks ×</span>
            <span style={{ fontSize: 12, padding: "5px 10px", borderRadius: 999, background: "var(--paper-deep)", color: "var(--fg-1)" }}>Trail crew opportunities ×</span>
            <Btn size="sm" kind="ghost" icon={IconPlus}>Add</Btn>
          </div>
        </Field>
      </div>
      <div style={drawerFoot}>
        <Btn kind="ghost" onClick={onClose}>Cancel</Btn>
        <div style={{ marginLeft: "auto", display: "flex", gap: 8 }}>
          <Btn kind="secondary">Save as draft</Btn>
          <Btn icon={IconCheck}>Publish</Btn>
        </div>
      </div>
    </div>
  </div>
);

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

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