// Variation 3 — Heatmap
// Visualization-led. A unified controls heatmap grouped by framework at top.
// Suggested evidence appears as cards below, each tied to heatmap cells.

const { useState: useState3, useMemo: useMemo3 } = React;

function HeatmapDashboard({ density }) {
  const { ORG, PROJECTS, SUGGESTIONS, FRAMEWORKS, orgStats, projectStats, maturityColor } = window.MockData;
  const stats = orgStats();
  const [hoveredSuggestion, setHoveredSuggestion] = useState3(null);

  // Build a highlight set of {framework,controlIndex} for the hovered suggestion.
  // Since our suggestions use controlId strings, we'll highlight by framework+id
  // and just visually flash the matching project rows.
  const highlightSet = useMemo3(() => {
    if (!hoveredSuggestion) return new Set();
    const s = SUGGESTIONS.find((x) => x.id === hoveredSuggestion);
    if (!s) return new Set();
    return new Set(s.controls.map((c) => c.projectId));
  }, [hoveredSuggestion]);

  return (
    <div className="px-6 py-7 max-w-[1500px] mx-auto">
      <div className="flex items-end justify-between mb-6">
        <div>
          <p className="text-xs uppercase tracking-[0.12em] text-main/55 font-semibold mb-1">Posture Map</p>
          <h1 className="text-3xl font-semibold tracking-tight text-main">{ORG.name}</h1>
          <p className="text-main/60 text-sm mt-1">Every control across every framework, in one view.</p>
        </div>
        <div className="flex items-center gap-2">
          <MaturityLegend />
          <Button variant="main" size="md"><Icon name="plus" className="h-4 w-4" />Add Framework</Button>
        </div>
      </div>

      {/* Top stats strip */}
      <div className="grid grid-cols-5 gap-3 mb-6">
        <KpiTile label="Frameworks" value={PROJECTS.length} sublabel="active" icon="briefcase" />
        <KpiTile label="Avg Maturity" value={stats.avg ?? "—"} sublabel="/5" icon="arrow-trending-up" dark />
        <KpiTile label="Assessed" value={`${stats.completion}%`} sublabel={`${stats.assessed}/${stats.total}`} icon="check-circle" />
        <KpiTile label="At Risk" value={stats.atRisk} sublabel="≤ level 2" icon="exclamation-circle" />
        <KpiTile label="AI Suggestions" value={SUGGESTIONS.filter(s => s.status === "new").length} sublabel="pending" icon="sparkles" accent />
      </div>

      {/* Heatmap */}
      <Card className="mb-6 overflow-hidden">
        <div className="px-5 py-3 border-b border-main/10 flex items-center justify-between bg-[#FAF7F4]">
          <div>
            <h2 className="text-sm font-semibold text-main">Control Posture Heatmap</h2>
            <p className="text-[11px] text-main/55">Hover an evidence suggestion below to see which controls it would lift.</p>
          </div>
          <div className="flex items-center gap-1">
            <button className="px-2.5 py-1 rounded text-[11px] font-medium bg-main text-white">By Framework</button>
            <button className="px-2.5 py-1 rounded text-[11px] font-medium text-main/60 hover:bg-main/5">By Domain</button>
          </div>
        </div>
        <div className="p-5 space-y-4">
          {PROJECTS.map((p) => {
            const fw = FRAMEWORKS.find((f) => f.key === p.framework);
            const s = projectStats(p);
            const highlighted = highlightSet.has(p.id);
            return (
              <div key={p.id} className={`transition-opacity ${hoveredSuggestion && !highlighted ? "opacity-30" : "opacity-100"}`}>
                <div className="flex items-center justify-between mb-1.5">
                  <div className="flex items-center gap-2">
                    <span className="h-3 w-3 rounded-sm" style={{ backgroundColor: fw.color }}></span>
                    <span className="text-[13px] font-semibold text-main">{fw.name}</span>
                    <Badge variant="outline">{p.controls.length} controls</Badge>
                    {highlighted && <Badge variant="success">affected</Badge>}
                  </div>
                  <div className="flex items-center gap-4 text-[11px] text-main/60">
                    <span>avg <span className="font-semibold text-main">{s.avg ?? "—"}</span></span>
                    <span>{s.completion}% assessed</span>
                    <span>{s.atRisk} at risk</span>
                  </div>
                </div>
                <div className="flex flex-wrap gap-[3px]">
                  {p.controls.map((c) => (
                    <div
                      key={c.id}
                      title={`${c.controlId}${c.score ? ` — ${c.score}` : " — unassessed"}`}
                      className={`rounded-[2px] transition-all ${highlighted ? "ring-1 ring-secondary" : ""}`}
                      style={{
                        width: density === "compact" ? 10 : 12,
                        height: density === "compact" ? 10 : 12,
                        backgroundColor: c.score == null ? "transparent" : maturityColor(c.score),
                        boxShadow: c.score == null ? "inset 0 0 0 1px rgba(147,210,204,0.5)" : "inset 0 0 0 1px rgba(147,210,204,0.6)",
                      }}
                    />
                  ))}
                </div>
              </div>
            );
          })}
        </div>
      </Card>

      {/* Suggested evidence */}
      <div className="flex items-center justify-between mb-3">
        <div>
          <h2 className="text-base font-semibold text-main flex items-center gap-2">
            <Icon name="sparkles" className="h-4 w-4 text-secondary" strokeWidth={1.8} />
            AI-Suggested Evidence
          </h2>
          <p className="text-xs text-main/55">Upload these to lift multiple controls at once.</p>
        </div>
        <Button variant="ghost" size="sm">View all →</Button>
      </div>
      <div className="grid grid-cols-3 gap-3">
        {SUGGESTIONS.filter((s) => s.status === "new").map((s) => (
          <SuggestionHeatmapCard
            key={s.id}
            suggestion={s}
            onHover={setHoveredSuggestion}
          />
        ))}
      </div>
    </div>
  );
}

function MaturityLegend() {
  return (
    <div className="flex items-center gap-2 px-3 py-1.5 bg-white rounded-md border border-main/10">
      <span className="text-[10.5px] uppercase tracking-[0.08em] font-semibold text-main/55">Maturity</span>
      {[1, 2, 3, 4, 5].map((n) => (
        <div key={n} className="flex items-center gap-1">
          <span className="h-3 w-3 rounded-sm" style={{ backgroundColor: window.MockData.maturityColor(n) }}></span>
          <span className="text-[10.5px] text-main/65 font-medium tabular-nums">{n}</span>
        </div>
      ))}
    </div>
  );
}

function SuggestionHeatmapCard({ suggestion, onHover }) {
  const { FRAMEWORKS } = window.MockData;
  const [accepted, setAccepted] = useState3(false);
  const frameworkKeys = [...new Set(suggestion.controls.map((c) => c.framework))];
  const lift = suggestion.controls.reduce((acc, c) => acc + ((c.projectedScore ?? 0) - (c.currentScore ?? 0)), 0);

  return (
    <Card
      hoverable
      className="p-4"
    >
      <div
        onMouseEnter={() => onHover(suggestion.id)}
        onMouseLeave={() => onHover(null)}
      >
        <div className="flex items-start justify-between gap-2 mb-2">
          <div className="flex items-center gap-2">
            {suggestion.impact === "high" && <Icon name="fire" className="h-4 w-4 text-[#E07A5F]" />}
            {suggestion.impact === "medium" && <Icon name="bolt" className="h-4 w-4 text-[#c4864a]" />}
            {suggestion.impact === "low" && <Icon name="tag" className="h-4 w-4 text-main/50" />}
            <Badge variant="outline">{suggestion.evidenceType}</Badge>
          </div>
          <span className="text-[10.5px] text-main/45">{suggestion.age}</span>
        </div>
        <h3 className="font-semibold text-[14px] text-main leading-snug">{suggestion.title}</h3>
        <p className="text-[11.5px] text-main/60 mt-1 leading-snug line-clamp-2">{suggestion.description}</p>

        <div className="mt-3 flex items-center justify-between">
          <ConfidencePill value={suggestion.confidence} />
          <div className="flex items-center gap-1 text-[11px] font-semibold text-[#3a7a4a]">
            <Icon name="arrow-trending-up" className="h-3 w-3" />
            +{lift} maturity pts
          </div>
        </div>

        <div className="mt-3 pt-3 border-t border-main/8">
          <div className="flex items-center justify-between text-[10.5px] uppercase tracking-[0.08em] font-semibold text-main/55 mb-1.5">
            <span>Lifts {suggestion.controls.length} controls</span>
            <div className="flex items-center gap-1">
              {frameworkKeys.map((k) => {
                const fw = FRAMEWORKS.find(f => f.key === k);
                return <span key={k} className="h-2 w-2 rounded-sm" title={fw.short} style={{ backgroundColor: fw.color }}></span>;
              })}
            </div>
          </div>
          <div className="space-y-1">
            {suggestion.controls.slice(0, 3).map((c) => {
              const fw = FRAMEWORKS.find(f => f.key === c.framework);
              return (
                <div key={c.controlId} className="flex items-center gap-2 text-[11px]">
                  <span className="h-1.5 w-1.5 rounded-sm" style={{ backgroundColor: fw.color }}></span>
                  <span className="font-mono text-main/70">{c.controlId}</span>
                  <div className="flex-1 flex items-center gap-0.5">
                    <div className="h-2 w-4 rounded-sm" style={{ backgroundColor: c.currentScore ? window.MockData.maturityColor(c.currentScore) : "transparent", boxShadow: "inset 0 0 0 1px rgba(147,210,204,0.5)" }} />
                    <Icon name="arrow-right" className="h-2.5 w-2.5 text-main/40" />
                    <div className="h-2 w-4 rounded-sm" style={{ backgroundColor: window.MockData.maturityColor(c.projectedScore) }} />
                  </div>
                </div>
              );
            })}
            {suggestion.controls.length > 3 && (
              <p className="text-[10.5px] text-main/45 pl-3.5">+{suggestion.controls.length - 3} more</p>
            )}
          </div>
        </div>

        <div className="mt-3 flex items-center gap-1.5">
          <Button variant="main" size="sm" className="flex-1" onClick={(e) => { e.stopPropagation(); setAccepted(true); }}>
            {accepted ? <><Icon name="check" className="h-3 w-3" />Uploading…</> : <><Icon name="arrow-up-tray" className="h-3 w-3" />Upload</>}
          </Button>
          <Button variant="ghost" size="sm"><Icon name="moon" className="h-3 w-3" /></Button>
          <Button variant="ghost" size="sm"><Icon name="x" className="h-3 w-3" /></Button>
        </div>
      </div>
    </Card>
  );
}

window.HeatmapDashboard = HeatmapDashboard;
