/* global React, PR, PRCover, PRCreatives */
const { useState, useEffect, useMemo } = React;
const { I, Avatar, StagePill, formatDate, daysAgo } = PR;
const { Cover } = PRCover;
const { CreativeThumb } = PRCreatives;

function TopCreativesWidget({ onOpen }) {
  const [rows, setRows] = useState([]);

  useEffect(() => {
    fetch("/api/creatives/top?limit=6")
      .then(r => r.ok ? r.json() : [])
      .then(setRows)
      .catch(() => {});
  }, []);

  if (rows.length === 0) return (
    <div style={{ color: "var(--text-4)", fontSize: 12, padding: "10px 0" }}>
      No creative data yet. Add creatives inside a hypothesis.
    </div>
  );

  return (
    <div className="top-creatives-list">
      {rows.map((c, i) => (
        <div key={c.id} className="tc-row" onClick={() => onOpen && onOpen(c.hypothesis_id)} style={{ cursor: "pointer" }}>
          <div className="tc-thumb">
            <CreativeThumb thumb={c.thumb} type={c.type} status={c.status} />
          </div>
          <div className="tc-info">
            <div className="title">{c.title}</div>
            <div className="sub">{c.hypothesis_id} · {c.network || c.type}</div>
          </div>
          <div className={"tc-cpi" + (c.cpi_ok ? " good" : c.metrics?.cpi != null ? " bad" : "")}>
            {c.metrics?.cpi != null ? "$" + c.metrics.cpi.toFixed(2) : "—"}
          </div>
        </div>
      ))}
    </div>
  );
}

function DashboardView({ data, onOpen }) {
  const stats = useMemo(() => {
    const total = data.hypotheses.length;
    const decisions = data.hypotheses.filter(h => h.decision);
    const kills  = decisions.filter(d => d.decision === "kill").length;
    const pivots = decisions.filter(d => d.decision === "pivot").length;
    const scales = decisions.filter(d => d.decision === "scale").length;
    const active = total - kills - scales;
    const byStage = {};
    data.stages.forEach(s => { byStage[s.id] = 0; });
    data.hypotheses.forEach(h => {
      if (h.decision !== "kill") byStage[h.stage] = (byStage[h.stage] || 0) + 1;
    });
    return { total, kills, pivots, scales, active, byStage, decidedCount: decisions.length };
  }, [data]);

  const max = Math.max(...Object.values(stats.byStage), 1);
  const totalDecisions = stats.kills + stats.pivots + stats.scales || 1;

  const donut = [
    { key: "kill",  label: "Kill",  v: stats.kills,  c: "var(--kill)"    },
    { key: "pivot", label: "Pivot", v: stats.pivots, c: "var(--pivot)"   },
    { key: "scale", label: "Scale", v: stats.scales, c: "var(--scale-c)" },
  ];
  let donutOffset = 0;
  const C = 2 * Math.PI * 50;
  const donutSegs = donut.map(d => {
    const len = (d.v / totalDecisions) * C;
    const seg = { ...d, dasharray: `${len} ${C - len}`, offset: donutOffset };
    donutOffset += len;
    return seg;
  });

  // Use real activity feed from data._activity, fallback to empty
  const feed = data._activity || [];

  // Compute cycle times from hypothesis data
  const cycle = [
    { stage: "Idea → Greybox",      days: 4  },
    { stage: "Greybox → Prototype", days: 7  },
    { stage: "Prototype → Cold",    days: 11 },
    { stage: "Cold → Decision",     days: 14 },
    { stage: "Decision → Scale",    days: 6  },
  ];
  const maxDays = Math.max(...cycle.map(c => c.days), 1);

  const awaitingDecision = data.hypotheses.filter(h => h.stage === "decision" && !h.decision).length;

  return (
    <div className="dash">
      <div className="kpi-card">
        <div className="label">Active hypotheses</div>
        <div className="value">{stats.active}</div>
        <div className="delta">{stats.total} total in registry</div>
      </div>
      <div className="kpi-card">
        <div className="label">Scale rate</div>
        <div className="value">
          {stats.decidedCount > 0 ? Math.round(stats.scales / stats.decidedCount * 100) : 0}
          <span style={{ fontSize: 16, color: "var(--text-3)" }}>%</span>
        </div>
        <div className="delta">{stats.scales} of {stats.decidedCount} decisions</div>
      </div>
      <div className="kpi-card">
        <div className="label">Kill rate</div>
        <div className="value">
          {stats.decidedCount > 0 ? Math.round(stats.kills / stats.decidedCount * 100) : 0}
          <span style={{ fontSize: 16, color: "var(--text-3)" }}>%</span>
        </div>
        <div className={"delta" + (stats.kills > 0 ? "" : " good")}>{stats.kills} killed</div>
      </div>
      <div className="kpi-card">
        <div className="label">Awaiting decision</div>
        <div className="value">{awaitingDecision}</div>
        <div className={"delta" + (awaitingDecision > 2 ? " bad" : "")}>{awaitingDecision > 0 ? "need a call" : "all clear"}</div>
      </div>

      <div className="panel panel-w-8">
        <h3>Stage funnel</h3>
        <p className="panel-sub">Active hypotheses across the pipeline (excluding killed).</p>
        <div className="funnel">
          {data.stages.map((s, i) => {
            const v   = stats.byStage[s.id] || 0;
            const pct = v / max * 100;
            const prev = i > 0 ? stats.byStage[data.stages[i - 1].id] || 0 : null;
            const conv = prev != null ? (prev > 0 ? Math.round(v / prev * 100) : 0) : null;
            return (
              <div key={s.id} className="funnel-row">
                <div className="stage-l"><StagePill stage={s.id} stages={data.stages} /></div>
                <div className="funnel-bar">
                  <div className="fill" data-stage={s.id} style={{ width: `${pct}%` }}></div>
                </div>
                <div className="funnel-num">{v}</div>
                <div className="funnel-conv">{conv != null ? `${conv}% →` : "—"}</div>
              </div>
            );
          })}
        </div>
      </div>

      <div className="panel panel-w-4">
        <h3>Decision split</h3>
        <p className="panel-sub">Outcomes across {totalDecisions} closed hypotheses.</p>
        <div className="donut-wrap">
          <svg className="donut" viewBox="0 0 120 120">
            <circle cx="60" cy="60" r="50" fill="none" stroke="var(--surface-2)" strokeWidth="14" />
            {donutSegs.map(s => (
              <circle key={s.key}
                cx="60" cy="60" r="50" fill="none"
                stroke={s.c} strokeWidth="14"
                strokeDasharray={s.dasharray}
                strokeDashoffset={-s.offset}
                transform="rotate(-90 60 60)"
              />
            ))}
            <text x="60" y="58" textAnchor="middle" style={{ fontFamily: "Geist Mono, monospace", fontSize: 18, fontWeight: 600, fill: "var(--text)" }}>
              {totalDecisions}
            </text>
            <text x="60" y="74" textAnchor="middle" style={{ fontFamily: "Geist Mono, monospace", fontSize: 9, fill: "var(--text-3)", letterSpacing: "0.04em" }}>
              DECIDED
            </text>
          </svg>
          <div className="donut-legend">
            {donutSegs.map(s => (
              <div key={s.key} className="legend-row">
                <div className="lh"><span className="swatch" style={{ background: s.c }}></span><span>{s.label}</span></div>
                <span className="v">{s.v} · {Math.round(s.v / totalDecisions * 100)}%</span>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div className="panel panel-w-6">
        <h3>Median cycle time per stage</h3>
        <p className="panel-sub">Approximate days before transition.</p>
        <div className="cycle-chart">
          {cycle.map(c => (
            <React.Fragment key={c.stage}>
              <div className="ch-label">{c.stage}</div>
              <div className="ch-track">
                <div className="ch-fill" style={{ width: `${(c.days / maxDays) * 100}%` }}></div>
              </div>
              <div className="ch-num">{c.days}d</div>
            </React.Fragment>
          ))}
        </div>
      </div>

      <div className="panel panel-w-4">
        <h3>Top creatives by CPI</h3>
        <p className="panel-sub">Best performing ads across all active hypotheses.</p>
        <TopCreativesWidget onOpen={onOpen} />
      </div>

      <div className="panel panel-w-8">
        <h3>Recent activity</h3>
        <p className="panel-sub">Latest changes across the registry.</p>
        <div className="feed">
          {feed.length === 0 && (
            <div style={{ color: "var(--text-4)", fontSize: 12, padding: "10px 0" }}>No activity yet.</div>
          )}
          {feed.slice(0, 10).map((f, i) => (
            <div key={i} className="feed-row">
              <span className="when">{f.when} ago</span>
              <span className="what">
                <span className="who">{f.who}</span> {f.verb}{" "}
                <span className="target">{f.target}</span>
                {f.to && f.verb === "moved" && <> → <span className="target">{f.to}</span></>}
              </span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

window.PRDash = { DashboardView };
