/* Heatmap output — the periodic table view, alternate wall poster. */
/* global React, FRAMEWORK, ALL_LEAVES, LEAF_BY_ID, GROUP_BY_ID, detectTradeoffs,
   OutputBar */

function Heatmap({ project, session, setScreen, mode }) {
  const priorities = session.priorities;
  const leadCount = Object.values(priorities).filter(p => p === "lead").length;
  const followCount = Object.values(priorities).filter(p => p === "follow").length;
  const outCount = Object.values(priorities).filter(p => p === "out").length;
  const unsetCount = Object.values(priorities).filter(p => p === "unset").length;
  const detected = detectTradeoffs(priorities);
  const today = new Date().toISOString().slice(0, 10);

  // Group block widths — 8 columns wide as the standard; varies if needed.
  // We render each group as its own rectangular block with title + cells.
  return (
    <div style={{ background: "var(--surface-cream)", padding: "32px 32px 80px" }}>
      <OutputBar
        active="heatmap"
        setScreen={setScreen}
        project={project}
        session={session}
        onPrint={() => window.print()}
      />

      <div className="poster-stage">
        <div className="poster" id="heatmap-poster">

          {/* HEADER */}
          <header className="poster-head">
            <div className="poster-head-left">
              <div className="poster-eyebrow">
                <img src="assets/logo-hex.png" alt="" />
                <span>Crane Bioworks</span>
                <span className="sep">/</span>
                <span>Quality Attributes</span>
              </div>
              <h1 className="poster-h1">
                The field we chose from
              </h1>
              <p style={{
                fontFamily: "var(--font-serif)",
                fontSize: 15, color: "var(--fg-3)",
                marginTop: 12, marginBottom: 0, maxWidth: 540, lineHeight: 1.55, fontStyle: "italic",
              }}>
                Every Quality Attribute the framework knows about — shown at the intensity of its priority for{" "}
                <span style={{ color: "var(--c-violet-deep)", fontWeight: 500, fontStyle: "normal" }}>{project || "this project"}</span>.
                The unfilled cells are the project's fingerprint.
              </p>
            </div>
            <div className="poster-head-right">
              <div className="poster-mono">
                <div><span className="key">Project</span><span className="val">{project || "—"}</span></div>
                <div><span className="key">Dated</span><span className="val">{today}</span></div>
                <div><span className="key">Mode</span><span className="val">{mode === "workshop" ? "Workshop" : "Self-serve"}</span></div>
                <div><span className="key">Counts</span><span className="val">
                  <span style={{ color: "var(--c-violet)" }}>{leadCount}L</span> ·{" "}
                  <span style={{ color: "var(--c-emerald)" }}>{followCount}F</span> ·{" "}
                  <span>{outCount}O</span> · {unsetCount}?
                </span></div>
              </div>
            </div>
          </header>

          {/* GROUP BLOCKS */}
          <div style={{ paddingTop: 28 }}>
            <div className="heat-grid">
              {FRAMEWORK.groups.map(g => (
                <GroupBlock key={g.id} group={g} priorities={priorities} notes={session.notes} />
              ))}
            </div>
          </div>

          {/* LEGEND + TRADE-OFFS row */}
          <div className="heat-meta">
            <div className="heat-legend">
              <div className="side-eyebrow" style={{ marginBottom: 14 }}>How to read</div>
              <div className="legend-row">
                <LegendSwatch p="lead" />
                <div>
                  <div className="legend-label">Lead</div>
                  <div className="legend-blurb">Top priority. The project lives or dies on this.</div>
                </div>
              </div>
              <div className="legend-row">
                <LegendSwatch p="follow" />
                <div>
                  <div className="legend-label">Follow</div>
                  <div className="legend-blurb">Tracked — should land in spec, won't block.</div>
                </div>
              </div>
              <div className="legend-row">
                <LegendSwatch p="out" />
                <div>
                  <div className="legend-label">Out of scope</div>
                  <div className="legend-blurb">Knowingly excluded. Visible — the framework's durability is the message.</div>
                </div>
              </div>
              <div className="legend-row">
                <LegendSwatch p="unset" />
                <div>
                  <div className="legend-label">Unset</div>
                  <div className="legend-blurb">Not yet decided. Watch out for blind spots.</div>
                </div>
              </div>
            </div>

            <div className="heat-trades">
              <div className="side-eyebrow" style={{ marginBottom: 14 }}>Trade-offs live in this profile</div>
              <div className="side-trades">
                {detected.length === 0 && (
                  <div className="side-empty">No trade-offs triggered by this priority profile.</div>
                )}
                {detected.map((t, i) => {
                  const a = LEAF_BY_ID[t.a];
                  const b = LEAF_BY_ID[t.b];
                  return (
                    <div key={t.id} className="side-trade">
                      <div className="side-trade-no">{String(i + 1).padStart(2, "0")}</div>
                      <div className="side-trade-body">
                        <div className="side-trade-title">{t.title}</div>
                        <div className="side-trade-leaves">
                          <span className="leaf-chip">{a.id} {a.short}</span>
                          <span className="ar">⇌</span>
                          <span className="leaf-chip">{b.id} {b.short}</span>
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          </div>

          {/* FOOTER */}
          <footer className="poster-foot">
            <span>Protein Engineering Quality Attributes</span>
            <span className="dot" />
            <span>{project || "Untitled project"}</span>
            <span className="dot" />
            <span>{today}</span>
            <span className="dot" />
            <span>
              <a className="poster-link" href="https://cranebioworks.com" target="_blank" rel="noopener noreferrer">Crane Bioworks</a>
              {" · "}
              <a className="poster-link" href="mailto:hello@cranebioworks.com">Get in touch</a>
              {" · Built with ❤ from 🇧🇪 🇪🇺"}
            </span>
          </footer>
        </div>
      </div>
    </div>
  );
}

function GroupBlock({ group, priorities, notes }) {
  const isViolet = group.accent === "violet";
  const leadInGroup = group.leaves.filter(l => priorities[l.id] === "lead").length;
  const followInGroup = group.leaves.filter(l => priorities[l.id] === "follow").length;

  return (
    <div className="heat-block">
      <div className="heat-block-head">
        <div className="heat-block-no">{String(group.id).padStart(2, "0")}</div>
        <div className="heat-block-title-wrap">
          <h3 className="heat-block-title">{group.name}</h3>
          <div className="heat-block-desc">{group.desc}</div>
        </div>
        <div className="heat-block-counts">
          {leadInGroup > 0 && <span className="hb-c hb-c-lead">{leadInGroup}L</span>}
          {followInGroup > 0 && <span className="hb-c hb-c-follow">{followInGroup}F</span>}
        </div>
      </div>
      <div className={`heat-block-cells heat-block-${group.leaves.length}`}>
        {group.leaves.map(l => (
          <HeatCell key={l.id} leaf={l} priority={priorities[l.id]} note={notes[l.id]} />
        ))}
      </div>
    </div>
  );
}

function HeatCell({ leaf, priority, note }) {
  return (
    <div className={`heat-cell heat-${priority}`}>
      <div className="heat-cell-head">
        <span className="heat-cell-id">{leaf.id}</span>
        {priority === "lead" && <span className="heat-cell-pri">L</span>}
        {priority === "follow" && <span className="heat-cell-pri follow">F</span>}
      </div>
      <div className="heat-cell-name">{leaf.short}</div>
      {(priority === "lead") && note && note.threshold && (
        <div className="heat-cell-note">{note.threshold}</div>
      )}
    </div>
  );
}

function LegendSwatch({ p }) {
  return <div className={`legend-swatch legend-${p}`} />;
}

window.Heatmap = Heatmap;
