// Right panel — real results gallery, measurements with deltas, anatomy notes, real history.

const RightPanel = ({ ctx }) => {
  const { state, set } = ctx;
  const session = state.session;
  if (!session) return <EmptyRightPanel />;

  return (
    <div className="panel right">
      {/* 04 RESULTS */}
      <div className="panel-section">
        <div className="section-label">
          <span><span className="num">04</span>Results</span>
          <span className="mono-tiny">{state.results.length} of ∞</span>
        </div>
        <div className="result-tray">
          {state.results.map((r) => (
            <div
              key={r.id}
              className={`result-card ${state.activeResult === r.id ? "active" : ""} ${r.kind === "original" ? "original" : ""}`}
              onClick={() => set({ activeResult: r.id })}
            >
              <div className="result-thumb">
                <img src={r.url} alt={r.label} style={{ width: "100%", height: "100%", objectFit: "cover", opacity: 0.95 }} />
                {r.kind === "warp" && (
                  <div style={{ position: "absolute", inset: 0, background: "rgba(184,90,42,0.06)" }} />
                )}
              </div>
              <div className={`result-badge ${r.pinned ? "pinned" : ""}`}>{r.label}</div>
              {r.kind !== "original" && (
                <div className="result-actions" onClick={(e) => e.stopPropagation()}>
                  <button
                    className={r.pinned ? "pinned" : ""}
                    onClick={() => set({ results: state.results.map(x => x.id === r.id ? { ...x, pinned: !x.pinned } : x) })}
                    title="Pin"
                  >★</button>
                  <button
                    title="Delete"
                    onClick={() => set({ results: state.results.filter(x => x.id !== r.id) })}
                  >×</button>
                </div>
              )}
              <div className="result-meta">
                <span>{r.time}</span>
                <span><b>{r.metric}</b></span>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* 05 MEASUREMENTS */}
      <div className="panel-section">
        <div className="section-label">
          <span><span className="num">05</span>Measurements</span>
          <span className="mono-tiny">Δ from baseline</span>
        </div>
        <MeasurementGrid baseline={session.baseline} deltas={state.deltas} />
        <div className="mono-tiny" style={{ marginTop: 10, color: "var(--ink-4)", textTransform: "none", fontSize: 10, lineHeight: 1.5 }}>
          mm anchored on IPD ≈ 63mm · {session.measurements.mm_per_px} mm/px · {session.measurements.ipd_px}px detected.
        </div>
      </div>

      {/* 06 ANATOMY */}
      <div className="panel-section">
        <div className="section-label">
          <span><span className="num">06</span>Anatomy</span>
          <span className="mono-tiny">Reference</span>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 1 }}>
          {[
            { label: "Radix", desc: "Root of the nose, between the eyes." },
            { label: "Dorsum", desc: "Bridge — bony upper, cartilaginous lower." },
            { label: "Tip", desc: "Lower lateral cartilage assembly." },
            { label: "Ala", desc: "Lateral wall of the nostril; controls width." },
            { label: "Columella", desc: "Vertical strip between the nostrils." },
          ].map(a => (
            <div key={a.label} style={{ padding: "8px 0", borderBottom: "1px solid var(--hairline)", display: "grid", gridTemplateColumns: "70px 1fr", gap: 10, fontSize: 11 }}>
              <span style={{ fontFamily: "var(--serif)", fontStyle: "italic", fontSize: 14 }}>{a.label}</span>
              <span style={{ color: "var(--ink-3)" }}>{a.desc}</span>
            </div>
          ))}
        </div>
      </div>

      {/* 07 HISTORY */}
      <div className="panel-section">
        <div className="section-label">
          <span><span className="num">07</span>History</span>
          <span className="mono-tiny">{session.history.length}</span>
        </div>
        <div className="history-list">
          {session.history.map((h, i) => (
            <div key={i} className="history-row">
              <div className="time">{h.time}</div>
              <div className="desc">
                {h.desc}
                {h.detail && <small>{h.detail}</small>}
              </div>
              <div className="badge">{h.kind}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

const MeasurementGrid = ({ baseline, deltas }) => {
  const fmt = (key, unit) => {
    const v = baseline[key];
    const d = deltas[key];
    return { val: v, unit, delta: d };
  };
  const cells = [
    { label: "Nasolabial", ...fmt("nasolabial", "°") },
    { label: "Dorsal hump", ...fmt("dorsal_mm", " mm") },
    { label: "Bridge width", ...fmt("bridge_mm", " mm") },
    { label: "Tip width", ...fmt("tip_w_mm", " mm") },
    { label: "Nose length", ...fmt("nose_len_mm", " mm") },
    { label: "Alar width", ...fmt("alar_mm", " mm") },
    { label: "Projection", ...fmt("projection_mm", " mm") },
    { label: "Tip rotation", ...fmt("tip_rotation", "°") },
    { label: "Symmetry", ...fmt("symmetry", "") },
  ];
  return (
    <div className="anatomy">
      {cells.map(c => {
        const showDelta = typeof c.delta === "number" && c.delta !== 0;
        const dColor = showDelta ? (c.delta > 0 ? "var(--ok)" : "var(--warn)") : "var(--ink-3)";
        return (
          <div key={c.label}>
            <span>{c.label}</span>
            <span style={{ fontFamily: "var(--serif)", fontStyle: "italic", fontSize: 16 }}>
              {c.val}{c.unit}
            </span>
            <span style={{ marginTop: 4, color: dColor }}>
              {showDelta ? `${c.delta > 0 ? "+" : ""}${c.delta.toFixed(2)}${c.unit}` : (c.delta === 0 ? "no change" : "baseline")}
            </span>
          </div>
        );
      })}
    </div>
  );
};

const EmptyRightPanel = () => (
  <div className="panel right">
    <div className="panel-section">
      <div className="section-label"><span><span className="num">04</span>Results</span></div>
      <div className="mono-tiny" style={{ color: "var(--ink-4)", textTransform: "none", fontSize: 11, lineHeight: 1.5 }}>
        Results, measurements, and session history appear here once you load a portrait.
      </div>
    </div>
  </div>
);

Object.assign(window, { RightPanel, MeasurementGrid, EmptyRightPanel });
