/* Workshop disagreement view — facilitator panel. */
/* global React, FRAMEWORK, ALL_LEAVES, LEAF_BY_ID, GROUP_BY_ID, PRIORITY_LABEL */

// Generate stub participant data — n participants each independently set priorities.
// We seed it deterministically from the current session so the page is stable.
function generateParticipants(session, n = 5) {
  const names = [
    { name: "Anika V.",   role: "Protein engineer" },
    { name: "Marc D.",    role: "Process scientist" },
    { name: "Sien R.",    role: "Regulatory" },
    { name: "Otto K.",    role: "Commercial / BD" },
    { name: "Leila T.",   role: "Computational lead" },
    { name: "Pieter J.",  role: "Bench scientist" },
  ];
  const participants = [];
  // Simple LCG seeded by the session's lead count for stability
  const leadCount = Object.values(session.priorities).filter(p => p === "lead").length;
  let seed = (leadCount + 1) * 7919;
  const rand = () => { seed = (seed * 1103515245 + 12345) & 0x7fffffff; return seed / 0x7fffffff; };

  for (let i = 0; i < n; i++) {
    const priorities = {};
    for (const id in session.priorities) {
      const original = session.priorities[id];
      // Most participants agree with the canonical version, with controlled drift
      const r = rand();
      if (r < 0.78) {
        priorities[id] = original;
      } else if (r < 0.86) {
        // Slight drift: out↔unset, follow↔lead
        if (original === "lead") priorities[id] = "follow";
        else if (original === "follow") priorities[id] = "lead";
        else if (original === "out") priorities[id] = "unset";
        else priorities[id] = "out";
      } else if (r < 0.94) {
        // Bigger drift: out → follow or unset → follow
        if (original === "out" || original === "unset") priorities[id] = "follow";
        else if (original === "follow") priorities[id] = "out";
        else priorities[id] = "follow";
      } else {
        // Wildcard: someone marked it lead
        priorities[id] = "lead";
      }
    }
    participants.push({ id: `p${i}`, name: names[i].name, role: names[i].role, priorities });
  }
  return participants;
}

// Compute per-leaf disagreement = entropy of the priority distribution
function leafDisagreement(leaf, participants) {
  const counts = { lead: 0, follow: 0, out: 0, unset: 0 };
  for (const p of participants) counts[p.priorities[leaf.id]]++;
  const n = participants.length;
  const probs = Object.values(counts).map(c => c / n).filter(p => p > 0);
  const entropy = probs.reduce((s, p) => s - p * Math.log2(p), 0);
  return { counts, entropy, n };
}

function Workshop({ project, session, setScreen, mode }) {
  const [participants, setParticipants] = useState(() => generateParticipants(session, 5));

  const ranked = useMemo(() => {
    return ALL_LEAVES.map(l => ({ leaf: l, ...leafDisagreement(l, participants) }))
      .sort((a, b) => b.entropy - a.entropy);
  }, [participants]);

  const topDisagreements = ranked.filter(r => r.entropy > 0.7).slice(0, 8);
  const fullConsensus = ranked.filter(r => r.entropy === 0).length;

  const reshuffle = () => setParticipants(generateParticipants(session, 5));

  return (
    <div style={{ background: "var(--surface-cream)", padding: "32px 32px 80px", maxWidth: 1440, margin: "0 auto" }}>
      <header style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", gap: 18, flexWrap: "wrap", marginBottom: 26 }}>
        <div>
          <div className="eyebrow violet">Workshop · Facilitator panel</div>
          <h2 style={{
            margin: "6px 0 4px",
            fontFamily: "var(--font-jakarta)",
            fontWeight: 700,
            fontSize: 30,
            letterSpacing: "-0.025em",
            lineHeight: 1.1,
          }}>Where does the room disagree?</h2>
          <p style={{ margin: 0, color: "var(--fg-3)", maxWidth: 720, fontSize: 14.5, lineHeight: 1.55, fontStyle: "italic" }}>
            After everyone has individually marked their priorities, this panel surfaces the leaves with the widest spread of opinions.
            That's the discussion the room needs to have — not the consensus items, not the chaff.
          </p>
        </div>
        <div style={{ display: "flex", gap: 10 }}>
          <button className="btn btn-ghost" onClick={reshuffle}>Reshuffle participant data</button>
          <button className="btn btn-dark" onClick={() => setScreen("pyramid")}>
            <span aria-hidden style={{ fontFamily: "var(--font-mono)" }}>↺</span>
            Back to poster
          </button>
        </div>
      </header>

      {/* Top stats */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14, marginBottom: 24 }}>
        <StatCard label="Room size" value={participants.length} sub="Participants in this round" />
        <StatCard label="Full consensus" value={fullConsensus} sub="Of 56 leaves, all participants agree" accent="emerald" />
        <StatCard label="Hot disagreements" value={topDisagreements.length} sub="Entropy > 0.7 bits" accent="gold" />
        <StatCard label="Mode" value={mode === "workshop" ? "Workshop" : "Self-serve"} sub="Switch in landing screen" />
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 24 }}>
        {/* Conflict list */}
        <div>
          <div className="eyebrow" style={{ marginBottom: 12 }}>Discussion order — most-divided first</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {topDisagreements.length === 0 && (
              <div style={{ padding: 24, border: "1px dashed var(--border-default)", borderRadius: 12, fontStyle: "italic", color: "var(--fg-4)" }}>
                The room is in remarkable agreement. Worth checking whether anyone is holding their tongue.
              </div>
            )}
            {topDisagreements.map((r, i) => (
              <ConflictRow key={r.leaf.id} rank={i + 1} item={r} participants={participants} />
            ))}
          </div>
        </div>

        {/* Participant cards */}
        <aside>
          <div className="eyebrow" style={{ marginBottom: 12 }}>In the room</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {participants.map((p, i) => (
              <ParticipantCard key={p.id} p={p} idx={i} />
            ))}
          </div>

          <div style={{ marginTop: 20 }}>
            <div className="eyebrow" style={{ marginBottom: 10 }}>Disagreement fingerprint</div>
            <div style={{
              background: "rgba(255,255,255,0.6)",
              border: "1px solid var(--border-default)",
              borderRadius: 12, padding: 16,
            }}>
              <DisagreementFingerprint ranked={ranked} />
              <div style={{ marginTop: 12, fontSize: 11.5, color: "var(--fg-4)", fontStyle: "italic", lineHeight: 1.4 }}>
                Each square is a leaf. Darker = wider spread. Hover for the name.
              </div>
            </div>
          </div>
        </aside>
      </div>

      <div style={{
        marginTop: 28, padding: "18px 22px",
        background: "rgba(245,158,11,0.06)",
        border: "1px solid rgba(245,158,11,0.20)",
        borderRadius: 12,
        fontSize: 13.5, color: "var(--fg-2)", lineHeight: 1.55,
      }}>
        <strong style={{ fontFamily: "var(--font-jakarta)", color: "var(--c-gold-700)", letterSpacing: "0.02em" }}>Facilitator note · </strong>
        Resolve top disagreements first, then re-run priority picking together to lock in the consensus poster.
        The panel is the conversation map, not the answer.
      </div>
    </div>
  );
}

function StatCard({ label, value, sub, accent }) {
  const color = accent === "emerald" ? "var(--c-emerald-700)" : accent === "gold" ? "var(--c-gold-700)" : "var(--fg-1)";
  return (
    <div style={{
      background: "rgba(255,255,255,0.6)",
      border: "1px solid var(--border-default)",
      borderRadius: 14,
      padding: "16px 18px",
    }}>
      <div className="eyebrow muted" style={{ fontSize: 10 }}>{label}</div>
      <div style={{
        fontFamily: "var(--font-jakarta)",
        fontWeight: 800,
        fontSize: 36,
        letterSpacing: "-0.03em",
        lineHeight: 1,
        color,
        marginTop: 6,
      }}>{value}</div>
      <div style={{ fontSize: 12, color: "var(--fg-4)", marginTop: 6, lineHeight: 1.4, fontStyle: "italic" }}>{sub}</div>
    </div>
  );
}

function ConflictRow({ rank, item, participants }) {
  const { leaf, counts, entropy, n } = item;
  const g = GROUP_BY_ID[leaf.groupId];

  return (
    <div style={{
      display: "grid",
      gridTemplateColumns: "32px 1fr 220px 64px",
      gap: 16,
      alignItems: "center",
      padding: "14px 18px",
      background: "rgba(255,255,255,0.6)",
      border: "1px solid var(--border-default)",
      borderRadius: 12,
    }}>
      <div style={{
        fontFamily: "var(--font-mono)",
        fontSize: 14,
        fontWeight: 600,
        color: "var(--c-gold-deep)",
        letterSpacing: "0.05em",
      }}>{String(rank).padStart(2, "0")}</div>

      <div>
        <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 4 }}>
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, padding: "2px 6px", borderRadius: 4, background: "rgba(34,49,83,0.05)", color: "var(--fg-3)" }}>{leaf.id}</span>
          <span style={{
            fontFamily: "var(--font-mono)", fontSize: 9, letterSpacing: "0.16em",
            color: g.accent === "violet" ? "var(--c-violet-deep)" : "var(--c-emerald-700)",
            textTransform: "uppercase",
          }}>{g.short}</span>
        </div>
        <div style={{ fontFamily: "var(--font-jakarta)", fontWeight: 700, fontSize: 16, color: "var(--fg-1)", letterSpacing: "-0.01em", lineHeight: 1.2 }}>
          {leaf.name}
        </div>
      </div>

      <div>
        <DistributionBar counts={counts} n={n} />
        <div style={{
          marginTop: 6, fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--fg-4)", letterSpacing: "0.04em",
          display: "flex", gap: 8, flexWrap: "wrap",
        }}>
          {Object.entries(counts).filter(([, c]) => c > 0).map(([k, c]) => (
            <span key={k} style={{ color: priorityColor(k) }}>{c} {PRIORITY_LABEL[k]}</span>
          ))}
        </div>
      </div>

      <div style={{ textAlign: "right" }}>
        <div style={{ fontFamily: "var(--font-jakarta)", fontWeight: 800, fontSize: 18, color: "var(--c-gold-deep)", letterSpacing: "-0.02em" }}>
          {entropy.toFixed(2)}
        </div>
        <div style={{ fontFamily: "var(--font-mono)", fontSize: 9, color: "var(--fg-5)", letterSpacing: "0.14em", textTransform: "uppercase" }}>bits</div>
      </div>
    </div>
  );
}

function priorityColor(p) {
  return p === "lead" ? "var(--c-violet)" :
         p === "follow" ? "var(--c-emerald-700)" :
         p === "out" ? "rgba(34,49,83,0.55)" :
         "var(--fg-4)";
}

function DistributionBar({ counts, n }) {
  return (
    <div style={{ display: "flex", height: 8, borderRadius: 999, overflow: "hidden", background: "rgba(34,49,83,0.05)" }}>
      {["lead", "follow", "out", "unset"].map(p => {
        const w = counts[p] / n;
        if (w === 0) return null;
        return <div key={p} style={{
          flex: w,
          background: p === "lead" ? "var(--c-violet)"
                     : p === "follow" ? "var(--c-emerald)"
                     : p === "out" ? "rgba(34,49,83,0.30)"
                     : "rgba(34,49,83,0.10)",
        }} />;
      })}
    </div>
  );
}

function ParticipantCard({ p, idx }) {
  const colors = ["#10b981", "#685ad9", "#f59e0b", "#059669", "#4f44b5", "#d97706"];
  const c = colors[idx % colors.length];
  const counts = { lead: 0, follow: 0, out: 0, unset: 0 };
  for (const id in p.priorities) counts[p.priorities[id]]++;

  return (
    <div style={{
      display: "grid", gridTemplateColumns: "32px 1fr auto", alignItems: "center", gap: 12,
      background: "rgba(255,255,255,0.6)",
      border: "1px solid var(--border-default)",
      borderRadius: 10, padding: "10px 14px",
    }}>
      <div style={{
        width: 28, height: 28, borderRadius: 999, background: c,
        color: "#fff", display: "flex", alignItems: "center", justifyContent: "center",
        fontFamily: "var(--font-jakarta)", fontSize: 11, fontWeight: 700, letterSpacing: "0.04em",
      }}>{p.name.split(" ").map(s => s[0]).slice(0, 2).join("")}</div>
      <div>
        <div style={{ fontFamily: "var(--font-jakarta)", fontWeight: 700, fontSize: 13, color: "var(--fg-1)" }}>{p.name}</div>
        <div style={{ fontSize: 11, color: "var(--fg-4)", fontStyle: "italic" }}>{p.role}</div>
      </div>
      <div style={{ display: "flex", gap: 4, alignItems: "center", fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--fg-4)" }}>
        <span style={{ color: "var(--c-violet)" }}>{counts.lead}</span>
        <span>·</span>
        <span style={{ color: "var(--c-emerald)" }}>{counts.follow}</span>
      </div>
    </div>
  );
}

function DisagreementFingerprint({ ranked }) {
  // Layout: a single block of 56 squares, sorted by entropy descending
  return (
    <div style={{ display: "grid", gridTemplateColumns: "repeat(14, 1fr)", gap: 3 }}>
      {ranked.map(r => {
        const intensity = Math.min(1, r.entropy / 2.0); // entropy can be 0..2 bits
        const bg = `rgba(245,158,11,${0.08 + intensity * 0.85})`;
        return (
          <div key={r.leaf.id}
            title={`${r.leaf.id} ${r.leaf.name} — entropy ${r.entropy.toFixed(2)} bits`}
            style={{
              aspectRatio: "1 / 1",
              background: bg,
              borderRadius: 3,
              border: r.entropy === 0 ? "1px solid rgba(34,49,83,0.04)" : "1px solid rgba(245,158,11,0.18)",
            }}
          />
        );
      })}
    </div>
  );
}

window.Workshop = Workshop;
