/* Pyramid output — the primary wall poster. */
/* global React, FRAMEWORK, ALL_LEAVES, LEAF_BY_ID, GROUP_BY_ID,
   detectTradeoffs */

function Pyramid({ project, session, setScreen, mode }) {
  const priorities = session.priorities;

  const leads   = ALL_LEAVES.filter(l => priorities[l.id] === "lead");
  const follows = ALL_LEAVES.filter(l => priorities[l.id] === "follow");
  const outs    = ALL_LEAVES.filter(l => priorities[l.id] === "out");
  const detected = detectTradeoffs(priorities);

  const today = new Date().toISOString().slice(0, 10);

  return (
    <div style={{ background: "var(--surface-cream)", padding: "32px 32px 80px" }}>
      <OutputBar
        active="pyramid"
        setScreen={setScreen}
        project={project}
        session={session}
        onPrint={() => window.print()}
      />

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

          {/* --- 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">
                What matters for <span className="poster-em">{project || "Untitled project"}</span>
              </h1>
              <div className="poster-meta">
                <span><strong>{leads.length}</strong> lead</span>
                <span className="dot" />
                <span><strong>{follows.length}</strong> follow</span>
                <span className="dot" />
                <span><strong>{outs.length}</strong> out of scope</span>
                <span className="dot" />
                <span><strong>{detected.length}</strong> trade-off{detected.length === 1 ? "" : "s"} live</span>
              </div>
            </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">Framework</span><span className="val">10 groups · 56 leaves</span></div>
              </div>
            </div>
          </header>

          {/* --- BODY: pyramid + side panel --- */}
          <div className="poster-body">

            {/* Pyramid bands */}
            <div className="poster-bands">

              {/* LEAD */}
              <BandHeader
                tier="lead"
                title="Lead"
                rule="3–5"
                blurb="The project lives or dies on these. Spell out the metric or threshold where you can."
                count={leads.length}
              />
              <div className="band band-lead">
                {leads.length === 0 && <EmptyTier label="Lead tier — pick the 3–5 attributes that define success." />}
                <div className="band-lead-grid" style={{
                  gridTemplateColumns: `repeat(${Math.min(Math.max(leads.length, 1), 4)}, 1fr)`
                }}>
                  {leads.map(l => <LeadCard key={l.id} leaf={l} note={session.notes[l.id]} />)}
                </div>
              </div>

              {/* FOLLOW */}
              <BandHeader
                tier="follow"
                title="Follow"
                rule="5–10"
                blurb="Tracked. Should land in spec; not the thing the program optimizes for."
                count={follows.length}
              />
              <div className="band band-follow">
                {follows.length === 0 && <EmptyTier muted label="Nothing here yet." />}
                <div className="follow-grid">
                  {follows.map(l => <FollowCard key={l.id} leaf={l} note={session.notes[l.id]} />)}
                </div>
              </div>

              {/* OUT-OF-SCOPE */}
              <BandHeader
                tier="out"
                title="Out of scope"
                rule="the rest"
                blurb="Knowingly excluded. The framework is bigger than this project — and that is the point."
                count={outs.length}
              />
              <div className="band band-out">
                <div className="ghost-list">
                  {outs.length === 0
                    ? <EmptyTier muted label="No out-of-scope items marked. Be more discerning." />
                    : outs.map(l => <GhostLabel key={l.id} leaf={l} />)
                  }
                </div>
              </div>
            </div>

            {/* SIDE PANEL */}
            <aside className="poster-side">
              <div className="side-section">
                <div className="side-eyebrow">Trade-offs to navigate</div>
                <div className="side-trades">
                  {detected.length === 0 && (
                    <div className="side-empty">No trade-offs detected for 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 className="side-trade-note">{t.note}</div>
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>

              {/* QUIET GROUPS */}
              <div className="side-section">
                <div className="side-eyebrow">Quiet groups</div>
                <QuietGroups priorities={priorities} />
                <div className="side-foot-note">
                  Framework groups with no leads and no follows. We are not engineering for these — and that is a decision.
                </div>
              </div>

            </aside>
          </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 BandHeader({ tier, title, rule, blurb, count }) {
  return (
    <div className={`band-head band-head-${tier}`}>
      <div className="band-head-l">
        <span className="band-no">{tier === "lead" ? "I" : tier === "follow" ? "II" : "III"}</span>
        <div>
          <div className="band-title">{title}</div>
          <div className="band-rule">target · {rule}</div>
        </div>
      </div>
      <div className="band-head-r">
        <div className="band-count">
          <span className="count-n">{count}</span>
          <span className="count-of">/ 56</span>
        </div>
        <div className="band-blurb">{blurb}</div>
      </div>
    </div>
  );
}

function LeadCard({ leaf, note }) {
  const g = GROUP_BY_ID[leaf.groupId];
  return (
    <div className="lead-card">
      <div className="lead-card-head">
        <span className="lead-id">{leaf.id}</span>
        <span className="lead-group">{g.short}</span>
      </div>
      <div className="lead-name">{leaf.name}</div>
      <div className="lead-meta">
        <div className="lead-meta-label">Metric</div>
        <div className="lead-meta-val">{leaf.metric}</div>
      </div>
      {note && note.threshold ? (
        <div className="lead-threshold">
          <span className="lead-threshold-label">Target</span>
          <span className="lead-threshold-val">{note.threshold}</span>
        </div>
      ) : (
        <div className="lead-threshold lead-threshold-empty">
          <span className="lead-threshold-label">Target</span>
          <span className="lead-threshold-val">— specify in the workspace —</span>
        </div>
      )}
    </div>
  );
}

function FollowCard({ leaf, note }) {
  return (
    <div className="follow-card">
      <span className="follow-id">{leaf.id}</span>
      <span className="follow-name">{leaf.short}</span>
      <span className="follow-full">{leaf.name}</span>
      {note && note.threshold && <span className="follow-thresh">· {note.threshold}</span>}
    </div>
  );
}

function GhostLabel({ leaf }) {
  return (
    <span className="ghost-leaf">
      <span className="ghost-id">{leaf.id}</span>
      <span className="ghost-name">{leaf.short}</span>
    </span>
  );
}

function EmptyTier({ label, muted }) {
  return (
    <div className="empty-tier" style={{ opacity: muted ? 0.4 : 1 }}>{label}</div>
  );
}

function QuietGroups({ priorities }) {
  const quiet = FRAMEWORK.groups.filter(g => {
    return g.leaves.every(l => {
      const p = priorities[l.id] || "unset";
      return p !== "lead" && p !== "follow";
    });
  });

  if (quiet.length === 0) {
    return (
      <div className="quiet-empty">
        Every group has at least one priority. Consider sharpening — sparsity is the signal.
      </div>
    );
  }

  return (
    <ul className="quiet-list">
      {quiet.map(g => (
        <li key={g.id} className="quiet-row">
          <span className="quiet-no">{String(g.id).padStart(2, "0")}</span>
          <span className="quiet-name">{g.name}</span>
          <span className="quiet-count">{g.leaves.length}</span>
        </li>
      ))}
    </ul>
  );
}

function MiniFingerprint({ priorities }) {
  return (
    <div className="fp">
      {FRAMEWORK.groups.map(g => (
        <div key={g.id} className="fp-row">
          <span className="fp-no">{String(g.id).padStart(2, "0")}</span>
          <span className="fp-cells">
            {g.leaves.map(l => {
              const p = priorities[l.id] || "unset";
              return <span key={l.id} className={`fp-cell fp-${p}`} title={`${l.id} ${l.name}`} />;
            })}
          </span>
        </div>
      ))}
    </div>
  );
}

function QRPlaceholder() {
  // 6×6 mock QR with corner markers — fast, decorative
  const cells = [];
  for (let y = 0; y < 6; y++) {
    for (let x = 0; x < 6; x++) {
      const isCornerL = (x === 0 || x === 1) && (y === 0 || y === 1);
      const isCornerR = (x === 4 || x === 5) && (y === 0 || y === 1);
      const isCornerB = (x === 0 || x === 1) && (y === 4 || y === 5);
      const corner = isCornerL || isCornerR || isCornerB;
      const fill = corner ? 1 : Math.random() > 0.55 ? 1 : 0;
      cells.push(<rect key={`${x}-${y}`} x={x * 10} y={y * 10} width={9} height={9} fill={fill ? "var(--fg-1)" : "transparent"} />);
    }
  }
  return (
    <svg viewBox="0 0 60 60" width={60} height={60} style={{ display: "block" }}>
      {cells}
    </svg>
  );
}

function buildMarkdown({ project, session }) {
  const today = new Date().toLocaleDateString("en-CA"); // YYYY-MM-DD
  const priorities = session.priorities;
  const notes = session.notes || {};

  const leaves = (state) => FRAMEWORK.groups.flatMap(g =>
    g.leaves
      .filter(l => priorities[l.id] === state)
      .map(l => ({ ...l, group: g }))
  );
  const leads = leaves("lead");
  const follows = leaves("follow");
  const detected = detectTradeoffs(priorities);

  const renderLeaf = (l) => {
    const n = notes[l.id] || {};
    const target = n.threshold ? ` — **target:** ${n.threshold}` : "";
    return `- **${l.id} ${l.name}** _(${l.group.name})_\n  - metric: ${l.metric}${target}`;
  };

  const lines = [];
  lines.push(`# ${project || "Untitled project"}`);
  lines.push("");
  lines.push("_Protein Engineering Quality Attributes — priority summary_");
  lines.push(`_Generated ${today}_`);
  lines.push("");
  lines.push("---");
  lines.push("");
  lines.push(`## Lead — what we are actively engineering for (${leads.length})`);
  lines.push("");
  lines.push(leads.length ? leads.map(renderLeaf).join("\n") : "_None marked. Sharpen this list before locking in._");
  lines.push("");
  lines.push(`## Follow — watched, not yet a target (${follows.length})`);
  lines.push("");
  lines.push(follows.length ? follows.map(renderLeaf).join("\n") : "_None marked._");
  lines.push("");
  if (detected.length) {
    lines.push(`## Trade-offs to navigate (${detected.length})`);
    lines.push("");
    detected.forEach((t, i) => {
      const a = LEAF_BY_ID[t.a];
      const b = LEAF_BY_ID[t.b];
      lines.push(`${i + 1}. **${t.title}** — ${a.id} ${a.short} ⇌ ${b.id} ${b.short}`);
      lines.push(`   _${t.note}_`);
    });
    lines.push("");
  }
  lines.push("---");
  lines.push("");
  lines.push("_Crane Bioworks · Protein Engineering Quality Attributes_");
  return lines.join("\n");
}

function downloadMarkdown({ project, session }) {
  const md = buildMarkdown({ project, session });
  const slug = (project || "untitled-project")
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "")
    .slice(0, 60) || "untitled-project";
  const blob = new Blob([md], { type: "text/markdown;charset=utf-8" });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = `${slug}-qa-summary.md`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  setTimeout(() => URL.revokeObjectURL(url), 1000);
}

function OutputBar({ active, setScreen, onPrint, project, session }) {
  return (
    <div style={{
      maxWidth: 1440, margin: "0 auto 22px",
      display: "flex", justifyContent: "space-between", alignItems: "center", gap: 16,
    }}>
      <div>
        <div className="eyebrow violet">Output · Wall poster</div>
        <h2 style={{
          margin: "4px 0 0",
          fontFamily: "var(--font-jakarta)",
          fontSize: 22, fontWeight: 700, letterSpacing: "-0.015em",
        }}>{active === "pyramid" ? "Pyramid — what matters" : "Heatmap — the field we chose from"}</h2>
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
        <div style={{
          display: "flex", background: "rgba(255,255,255,0.6)",
          border: "1px solid var(--border-default)", borderRadius: 999, padding: 3,
        }}>
          <button onClick={() => setScreen("pyramid")} style={outputTabStyle(active === "pyramid")}>Pyramid</button>
          <button onClick={() => setScreen("heatmap")} style={outputTabStyle(active === "heatmap")}>Heatmap</button>
        </div>
        <button className="btn btn-ghost" onClick={() => setScreen("workspace")}>
          <span aria-hidden style={{ fontFamily: "var(--font-mono)" }}>←</span>
          Edit priorities
        </button>
        {project !== undefined && session && (
          <button className="btn btn-ghost" onClick={() => downloadMarkdown({ project, session })} title="Download a markdown summary of Lead and Follow QAs">
            <span aria-hidden style={{ fontFamily: "var(--font-mono)", marginRight: 4 }}>↓</span>
            Markdown
          </button>
        )}
        <button className="btn btn-dark" onClick={onPrint}>Print poster</button>
      </div>
    </div>
  );
}

function outputTabStyle(active) {
  return {
    appearance: "none", border: 0, padding: "7px 16px", borderRadius: 999,
    background: active ? "var(--surface-navy)" : "transparent",
    color: active ? "var(--fg-on-dark)" : "var(--fg-3)",
    fontFamily: "var(--font-jakarta)", fontWeight: 600, fontSize: 12,
    cursor: "pointer", transition: "all 160ms",
  };
}

window.Pyramid = Pyramid;
window.OutputBar = OutputBar;
window.outputTabStyle = outputTabStyle;
