// Variation 2 — Workbench
// Compact operator's view. Left: persistent project list (sortable rows
// with inline matrix preview). Right: AI suggestion inbox as a triage queue.

const { useState: useState2 } = React;

function WorkbenchDashboard({ density }) {
  const { ORG, PROJECTS, SUGGESTIONS, FRAMEWORKS, orgStats, projectStats } = window.MockData;
  const stats = orgStats();
  const [selectedProject, setSelectedProject] = useState2(PROJECTS[0].id);
  const [suggestionFilter, setSuggestionFilter] = useState2("new");
  const [handled, setHandled] = useState2({});

  const newSuggestions = SUGGESTIONS.filter((s) => s.status === "new");
  const snoozedSuggestions = SUGGESTIONS.filter((s) => s.status === "snoozed");
  const shownSuggestions = suggestionFilter === "new" ? newSuggestions : suggestionFilter === "snoozed" ? snoozedSuggestions : SUGGESTIONS;

  const current = PROJECTS.find((p) => p.id === selectedProject);

  return (
    <div className="px-6 py-6 max-w-[1500px] mx-auto">
      {/* Compact title row with inline KPIs */}
      <div className="flex items-center justify-between mb-5">
        <div className="flex items-center gap-6">
          <div>
            <h1 className="text-2xl font-semibold tracking-tight text-main">{ORG.name}</h1>
            <p className="text-xs text-main/55">Workbench · {PROJECTS.length} projects</p>
          </div>
          <div className="flex items-center gap-5 pl-6 border-l border-main/15">
            <InlineStat label="Avg maturity" value={stats.avg ?? "—"} accent />
            <InlineStat label="Assessed" value={`${stats.completion}%`} sub={`${stats.assessed}/${stats.total}`} />
            <InlineStat label="At risk" value={stats.atRisk} danger />
            <InlineStat label="Evidence" value="284" />
          </div>
        </div>
        <div className="flex items-center gap-2">
          <Button variant="outline" size="sm"><Icon name="arrow-up-tray" className="h-3.5 w-3.5" />Evidence</Button>
          <Button variant="main" size="sm"><Icon name="plus" className="h-3.5 w-3.5" />Project</Button>
        </div>
      </div>

      {/* Split layout */}
      <div className="grid grid-cols-12 gap-4">
        {/* Left: project list */}
        <div className="col-span-7">
          <Card className="overflow-hidden">
            <div className="px-4 py-2.5 border-b border-main/10 bg-[#FAF7F4] flex items-center justify-between">
              <div className="flex items-center gap-2">
                <Icon name="briefcase" className="h-3.5 w-3.5 text-main/60" />
                <h2 className="text-[13px] font-semibold text-main">Projects</h2>
                <Badge variant="outline">{PROJECTS.length}</Badge>
              </div>
              <div className="flex items-center gap-1 text-[11px] text-main/55">
                <button className="px-2 py-1 hover:bg-main/5 rounded">Framework</button>
                <button className="px-2 py-1 hover:bg-main/5 rounded">Maturity</button>
                <button className="px-2 py-1 hover:bg-main/5 rounded font-medium text-main">Recent</button>
              </div>
            </div>
            <div className="divide-y divide-main/8">
              {PROJECTS.map((p) => (
                <ProjectWorkbenchRow
                  key={p.id}
                  project={p}
                  selected={selectedProject === p.id}
                  onSelect={() => setSelectedProject(p.id)}
                  density={density}
                />
              ))}
            </div>
          </Card>

          {/* Selected project detail */}
          {current && (
            <Card className="mt-4">
              <div className="px-5 py-3 border-b border-main/10 flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <h3 className="text-[13px] font-semibold text-main">{current.name}</h3>
                  <Badge variant="secondary">{window.MockData.FRAMEWORKS.find(f => f.key === current.framework).short}</Badge>
                </div>
                <Button variant="ghost" size="sm">Open<Icon name="arrow-right" className="h-3 w-3" /></Button>
              </div>
              <div className="p-5">
                <div className="flex items-center gap-2 mb-3">
                  <p className="text-[11px] uppercase tracking-[0.08em] font-semibold text-main/60">Control matrix</p>
                  <div className="flex items-center gap-2 ml-auto text-[10.5px] text-main/55">
                    {[1, 2, 3, 4, 5].map((n) => (
                      <span key={n} className="inline-flex items-center gap-1">
                        <span className="h-2 w-2 rounded-sm" style={{ backgroundColor: window.MockData.maturityColor(n) }}></span>
                        {n}
                      </span>
                    ))}
                    <span className="inline-flex items-center gap-1">
                      <span className="h-2 w-2 rounded-sm border border-secondary/50"></span>unassessed
                    </span>
                  </div>
                </div>
                <ControlMatrix controls={current.controls} density={density} />
              </div>
            </Card>
          )}
        </div>

        {/* Right: Suggestion inbox */}
        <div className="col-span-5">
          <Card className="sticky top-4 overflow-hidden">
            <div className="px-4 py-2.5 border-b border-main/10 bg-gradient-to-r from-secondary/20 to-transparent flex items-center justify-between">
              <div className="flex items-center gap-2">
                <Icon name="sparkles" className="h-3.5 w-3.5 text-main" strokeWidth={1.7} />
                <h2 className="text-[13px] font-semibold text-main">Evidence Inbox</h2>
                <Badge variant="default">{newSuggestions.length} new</Badge>
              </div>
              <button className="text-[11px] text-main/55 hover:text-main flex items-center gap-1">
                <Icon name="cog" className="h-3 w-3" />
              </button>
            </div>
            <div className="px-4 py-2 border-b border-main/10 flex items-center gap-1">
              {[
                { k: "new", l: "New", count: newSuggestions.length },
                { k: "snoozed", l: "Snoozed", count: snoozedSuggestions.length },
                { k: "all", l: "All", count: SUGGESTIONS.length },
              ].map((t) => (
                <button
                  key={t.k}
                  onClick={() => setSuggestionFilter(t.k)}
                  className={`flex items-center gap-1.5 px-2.5 py-1 rounded text-[11.5px] font-medium ${
                    suggestionFilter === t.k ? "bg-main text-white" : "text-main/65 hover:bg-main/5"
                  }`}
                >
                  {t.l}
                  <span className={`text-[10px] ${suggestionFilter === t.k ? "text-white/70" : "text-main/45"}`}>{t.count}</span>
                </button>
              ))}
            </div>
            <div className="max-h-[720px] overflow-y-auto divide-y divide-main/8">
              {shownSuggestions.map((s) => (
                <SuggestionCard key={s.id} suggestion={s} handled={handled[s.id]} onHandle={(action) => setHandled({ ...handled, [s.id]: action })} />
              ))}
              {shownSuggestions.length === 0 && (
                <div className="px-4 py-10 text-center">
                  <Icon name="inbox" className="h-8 w-8 mx-auto text-main/30 mb-2" />
                  <p className="text-sm text-main/55">All caught up</p>
                </div>
              )}
            </div>
            <div className="px-4 py-2.5 border-t border-main/10 bg-[#FAF7F4] flex items-center justify-between">
              <p className="text-[11px] text-main/55">Source: Slack, Linear, Okta, KnowBe4, calendar</p>
              <button className="text-[11px] font-medium text-main hover:underline">Connect more</button>
            </div>
          </Card>
        </div>
      </div>
    </div>
  );
}

function InlineStat({ label, value, sub, accent, danger }) {
  return (
    <div className="flex flex-col">
      <span className="text-[10px] uppercase tracking-[0.08em] font-semibold text-main/55">{label}</span>
      <div className="flex items-baseline gap-1.5">
        <span className={`text-[18px] font-semibold tabular-nums ${danger ? "text-[#a44832]" : accent ? "text-main" : "text-main"}`}>{value}</span>
        {sub && <span className="text-[10.5px] text-main/50">{sub}</span>}
      </div>
    </div>
  );
}

function ProjectWorkbenchRow({ project, selected, onSelect, density }) {
  const { FRAMEWORKS, projectStats } = window.MockData;
  const fw = FRAMEWORKS.find((f) => f.key === project.framework);
  const s = projectStats(project);
  const due = project.dueDate ? Math.round((project.dueDate - Date.now()) / (1000 * 60 * 60 * 24)) : null;

  return (
    <div
      onClick={onSelect}
      className={`px-4 py-3 cursor-pointer transition-colors ${selected ? "bg-secondary/15" : "hover:bg-main/[0.03]"}`}
    >
      <div className="flex items-center gap-3">
        <div className="w-1 self-stretch rounded-full" style={{ backgroundColor: selected ? "var(--color-main)" : fw.color }} />
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2">
            <p className="text-[13.5px] font-semibold text-main truncate">{project.name}</p>
            <Badge variant="outline">{fw.short}</Badge>
          </div>
          <div className="mt-1.5 flex items-center gap-3 text-[11px] text-main/60">
            <span>avg <span className="font-semibold text-main tabular-nums">{s.avg ?? "—"}</span></span>
            <span>·</span>
            <span><span className="font-semibold text-main tabular-nums">{s.completion}%</span> assessed</span>
            <span>·</span>
            <span><span className="text-[#a44832] font-semibold">{s.atRisk}</span> at risk</span>
            {due != null && (
              <>
                <span>·</span>
                <span className={due < 30 ? "text-[#a44832] font-medium" : ""}>
                  {due > 0 ? `${due}d left` : "overdue"}
                </span>
              </>
            )}
          </div>
        </div>
        <div className="flex items-center gap-2 shrink-0">
          {/* Inline mini-matrix preview */}
          <div className="flex flex-wrap max-w-[100px] gap-[2px]">
            {project.controls.slice(0, 28).map((c) => (
              <span
                key={c.id}
                className="h-[8px] w-[8px] rounded-[1.5px]"
                style={{
                  backgroundColor: c.score == null ? "transparent" : window.MockData.maturityColor(c.score),
                  boxShadow: "inset 0 0 0 0.5px rgba(147,210,204,0.5)",
                }}
              />
            ))}
          </div>
          <div className="w-20">
            <ProgressBar value={s.completion} />
          </div>
        </div>
      </div>
    </div>
  );
}

function SuggestionCard({ suggestion, handled, onHandle }) {
  const { FRAMEWORKS } = window.MockData;
  const impactIcon = suggestion.impact === "high" ? "fire" : suggestion.impact === "medium" ? "bolt" : "tag";
  const impactColor = suggestion.impact === "high" ? "text-[#E07A5F]" : suggestion.impact === "medium" ? "text-[#c4864a]" : "text-main/60";

  if (handled) {
    return (
      <div className="px-4 py-3 flex items-center justify-between bg-[#FAF7F4]">
        <div className="flex items-center gap-2 text-[12px] text-main/70">
          <Icon name={handled === "uploaded" ? "check-circle" : handled === "snoozed" ? "moon" : "x"} className="h-3.5 w-3.5" />
          <span>{suggestion.title}</span>
          <span className="text-main/40">· {handled}</span>
        </div>
        <button onClick={() => onHandle(null)} className="text-[11px] text-main/50 hover:text-main">Undo</button>
      </div>
    );
  }

  return (
    <div className="px-4 py-3 hover:bg-secondary/5 transition-colors">
      <div className="flex items-start gap-2.5">
        <Icon name={impactIcon} className={`h-4 w-4 mt-0.5 shrink-0 ${impactColor}`} />
        <div className="flex-1 min-w-0">
          <div className="flex items-start justify-between gap-2">
            <p className="text-[13px] font-semibold text-main leading-snug">{suggestion.title}</p>
            <span className="text-[10.5px] text-main/45 shrink-0 tabular-nums">{suggestion.age}</span>
          </div>
          <p className="text-[11.5px] text-main/60 mt-0.5 leading-snug">{suggestion.description}</p>
          <div className="flex items-center gap-1.5 mt-2 flex-wrap">
            <ConfidencePill value={suggestion.confidence} />
            {[...new Set(suggestion.controls.map(c => c.framework))].map((fwKey) => {
              const fw = FRAMEWORKS.find(f => f.key === fwKey);
              const count = suggestion.controls.filter(c => c.framework === fwKey).length;
              return <Badge key={fwKey} variant="outline"><span className="h-1.5 w-1.5 rounded-full" style={{ backgroundColor: fw.color }}></span>{fw.short} <span className="text-main/50">×{count}</span></Badge>;
            })}
          </div>
          <div className="flex items-center gap-1 mt-2 flex-wrap">
            {suggestion.controls.slice(0, 5).map((c) => (
              <div key={c.controlId} className="inline-flex items-center gap-0.5 text-[10px] font-mono text-main/60 bg-main/5 rounded px-1 py-0.5">
                <span>{c.controlId}</span>
                <span className="text-main/35">{c.currentScore ?? "—"}→</span>
                <span className="text-[#3a7a4a] font-semibold">{c.projectedScore}</span>
              </div>
            ))}
            {suggestion.controls.length > 5 && <span className="text-[10px] text-main/45">+{suggestion.controls.length - 5}</span>}
          </div>
          <div className="flex items-center gap-1.5 mt-2.5">
            <Button variant="main" size="sm" onClick={() => onHandle("uploaded")}>
              <Icon name="arrow-up-tray" className="h-3 w-3" />Upload
            </Button>
            <Button variant="ghost" size="sm" onClick={() => onHandle("snoozed")}>Snooze</Button>
            <button onClick={() => onHandle("dismissed")} className="text-[11px] text-main/45 hover:text-main px-2 py-1">Dismiss</button>
          </div>
        </div>
      </div>
    </div>
  );
}

window.WorkbenchDashboard = WorkbenchDashboard;
