/* Insights & Performance — recommendation cards + charts */

function InsightsTab({ creatives, mode }) {
  const target = window.ADORE.platforms.target_cpl;
  const active = creatives.filter(c => !c.removed);

  if (mode === "pipeline") {
    return <PipelineInsights creatives={active} />;
  }

  // --- live recommendations ---
  const withMetrics = active.filter(c => c.liveStatus !== "paused");
  const recs = buildRecs(active, target);
  const totalSpend = withMetrics.reduce((s, c) => s + c.live.spend, 0);
  const totalLeads = withMetrics.reduce((s, c) => s + c.live.leads, 0);
  const blendedCpl = totalLeads ? totalSpend / totalLeads : null;

  // chart data
  const spendTrend = makeTrend(totalSpend);
  const cplTrend = makeCplTrend(blendedCpl);

  return (
    <div>
      <div className="charts">
        <SpendTrendChart data={spendTrend} total={totalSpend} />
        <CplChart data={cplTrend} target={target} current={blendedCpl} />
      </div>
      <FormatBreakdown creatives={withMetrics} target={target} />
      <div className="section-h serif">Recommendations</div>
      <div className="rec-grid">
        {recs.map((r, i) => <RecCard key={i} r={r} />)}
      </div>
    </div>
  );
}

/* ----- pipeline = status cards ----- */
function PipelineInsights({ creatives }) {
  const ready = creatives.filter(c => c.status === "ready").length;
  const paused = creatives.filter(c => c.status === "paused").length;
  const videos = creatives.filter(c => c.isVideo).length;
  const images = creatives.length - videos;
  const byTone = {};
  creatives.forEach(c => { byTone[c.tone] = (byTone[c.tone] || 0) + 1; });
  const cards = [
    { cls: "insight", tag: "PIPELINE", title: `${creatives.length} creatives ready to launch`, body: <><b>{ready}</b> ready (paused) · <b>{paused}</b> manually paused. None are spending yet — select them in Gallery & Launch and push to Meta to begin.</>, foot: ["status: pre-flight"] },
    { cls: "insight", tag: "MIX", title: "Format coverage", body: <>Library is <b>{videos} videos</b> and <b>{images} images</b>. Good split for a video-vs-image read once spend starts.</>, foot: [`${videos} video`, `${images} image`] },
    { cls: "scale", tag: "READY", title: "Tone A/B is set up", body: <>Tones in rotation: {Object.entries(byTone).map(([t, n]) => `${t} (${n})`).join(", ")}. Refresh from Meta after 3–4 days to compare CPL by tone.</>, foot: ["test: tone"] },
    { cls: "refresh", tag: "NEXT", title: "Hand briefs to the generator", body: <>Queue new angles in the <b>Generate</b> tab to keep the library fresh before fatigue sets in on launched ads.</>, foot: ["action: generate"] },
  ];
  return (
    <div>
      <div className="insight-empty">
        <Badge status="ready" />
        <div className="muted" style={{ marginTop: 12, fontSize: 14 }}>Pipeline mode — no live spend yet. Hit <b style={{ color: "var(--t1)" }}>Refresh from Meta</b> for performance charts and action cards.</div>
      </div>
      <div className="section-h serif" style={{ marginTop: 18 }}>Pipeline status</div>
      <div className="rec-grid">{cards.map((c, i) => <RecCard key={i} r={c} />)}</div>
    </div>
  );
}

function buildRecs(creatives, target) {
  const recs = [];
  const m = creatives.filter(c => c.liveStatus !== "paused");

  const winners = m.filter(c => c.live.cpa != null && c.live.cpa <= target * 0.8 && c.liveStatus === "active")
                   .sort((a, b) => a.live.cpa - b.live.cpa).slice(0, 1);
  winners.forEach(c => recs.push({ cls: "scale", tag: "Scale", title: `${shortModel(c.model)} — ${c.angle}`, body: <>Beating target at <b>{fmt.cpl(c.live.cpa)} CPL</b> ({Math.round((1 - c.live.cpa / target) * 100)}% under ${target}) on <b>{c.live.leads} leads</b>. Raise daily budget and duplicate the angle.</>, foot: [c.id, `CTR ${fmt.pct(c.live.ctr)}`, `${c.format}`] }));

  const fatigued = m.filter(c => c.liveStatus === "fatigued").sort((a, b) => b.live.frequency - a.live.frequency).slice(0, 1);
  fatigued.forEach(c => recs.push({ cls: "refresh", tag: "Refresh", title: `${shortModel(c.model)} is fatiguing`, body: <>Frequency hit <b>{c.live.frequency}</b> and CPL drifted to <b>{fmt.cpl(c.live.cpa)}</b>. Swap in a fresh hook or rotate to a new tone before CPL climbs further.</>, foot: [c.id, `freq ${c.live.frequency}`] }));

  const losers = m.filter(c => c.live.cpa != null && c.live.cpa > target * 1.4).sort((a, b) => b.live.cpa - a.live.cpa).slice(0, 1);
  losers.forEach(c => recs.push({ cls: "pause", tag: "Pause", title: `${shortModel(c.model)} — ${c.angle}`, body: <>CPL is <b>{fmt.cpl(c.live.cpa)}</b>, {Math.round((c.live.cpa / target - 1) * 100)}% over the ${target} target on <b>{fmt.money(c.live.spend)}</b> spend. Pause and reallocate to the scale winner.</>, foot: [c.id, `spend ${fmt.money(c.live.spend)}`] }));

  // video vs image insight
  const vid = m.filter(c => c.isVideo && c.live.cpa != null);
  const img = m.filter(c => !c.isVideo && c.live.cpa != null);
  const vAvg = avg(vid.map(c => c.live.cpa)), iAvg = avg(img.map(c => c.live.cpa));
  if (vid.length && img.length) {
    const better = vAvg < iAvg ? "Video" : "Image";
    recs.push({ cls: "insight", tag: "Insight", title: `${better} is winning on CPL`, body: <>Video avg <b>{fmt.cpl(vAvg)}</b> vs image avg <b>{fmt.cpl(iAvg)}</b>. Weight the next generation batch toward <b>{better.toLowerCase()}</b> formats.</>, foot: [`video ${fmt.cpl(vAvg)}`, `image ${fmt.cpl(iAvg)}`] });
  }

  // tone A/B
  const byTone = {};
  m.forEach(c => { if (c.live.cpa != null) { (byTone[c.tone] = byTone[c.tone] || []).push(c.live.cpa); } });
  const toneAvgs = Object.entries(byTone).map(([t, arr]) => [t, avg(arr)]).sort((a, b) => a[1] - b[1]);
  if (toneAvgs.length >= 2) {
    recs.push({ cls: "insight", tag: "Insight", title: `"${toneAvgs[0][0]}" tone leads the A/B`, body: <><b>{toneAvgs[0][0]}</b> at {fmt.cpl(toneAvgs[0][1])} CPL is outperforming <b>{toneAvgs[toneAvgs.length - 1][0]}</b> at {fmt.cpl(toneAvgs[toneAvgs.length - 1][1])}. Lean into it for the next round.</>, foot: toneAvgs.map(([t, v]) => `${t} ${fmt.cpl(v)}`) });
  }
  return recs;
}

function RecCard({ r }) {
  return (
    <div className={"rec " + r.cls}>
      <div className="rec-tag"><span className="bd"></span>{r.tag}</div>
      <div className="rec-title">{r.title}</div>
      <div className="rec-body">{r.body}</div>
      {r.foot && <div className="rec-foot">{r.foot.map((f, i) => <span key={i}>{f}</span>)}</div>}
    </div>
  );
}

/* ---------- charts ---------- */
function SpendTrendChart({ data, total }) {
  const w = 520, h = 150, pad = 6;
  const max = Math.max(...data) * 1.15;
  const x = (i) => pad + (i / (data.length - 1)) * (w - pad * 2);
  const y = (v) => h - pad - (v / max) * (h - pad * 2);
  const line = data.map((v, i) => `${x(i)},${y(v)}`).join(" ");
  const area = `${pad},${h - pad} ${line} ${w - pad},${h - pad}`;
  return (
    <div className="chart-card">
      <div className="chart-head">
        <h4 className="serif">Spend trend · 14 days</h4>
        <div className="muted mono" style={{ fontSize: 12 }}>{fmt.money(total)} total</div>
      </div>
      <svg width="100%" viewBox={`0 0 ${w} ${h}`} fill="none" preserveAspectRatio="none" style={{ display: "block" }}>
        <defs><linearGradient id="sg" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stopColor="var(--acc)" stopOpacity="0.32" /><stop offset="1" stopColor="var(--acc)" stopOpacity="0" /></linearGradient></defs>
        <polygon points={area} fill="url(#sg)" />
        <polyline points={line} stroke="var(--acc)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
        {data.map((v, i) => i === data.length - 1 && <circle key={i} cx={x(i)} cy={y(v)} r="3.5" fill="var(--acc)" />)}
      </svg>
    </div>
  );
}

function CplChart({ data, target, current }) {
  const w = 360, h = 150, pad = 6, n = data.length;
  const max = Math.max(...data, target) * 1.2;
  const bw = (w - pad * 2) / n * 0.62;
  const y = (v) => h - pad - (v / max) * (h - pad * 2);
  const tY = y(target);
  return (
    <div className="chart-card">
      <div className="chart-head">
        <h4 className="serif">CPL vs target</h4>
        <div className="legend">
          <i><span className="sw" style={{ background: "var(--ok)" }}></span>under</i>
          <i><span className="sw" style={{ background: "var(--bad)" }}></span>over</i>
        </div>
      </div>
      <svg width="100%" viewBox={`0 0 ${w} ${h}`} fill="none" preserveAspectRatio="none" style={{ display: "block" }}>
        {data.map((v, i) => {
          const cx = pad + (i + 0.5) * ((w - pad * 2) / n);
          const over = v > target;
          return <rect key={i} x={cx - bw / 2} y={y(v)} width={bw} height={h - pad - y(v)} rx="3" fill={over ? "var(--bad)" : "var(--ok)"} opacity="0.85" />;
        })}
        <line x1={pad} y1={tY} x2={w - pad} y2={tY} stroke="var(--acc)" strokeWidth="1.4" strokeDasharray="5 4" />
      </svg>
      <div style={{ display: "flex", justifyContent: "space-between", marginTop: 8 }}>
        <span className="mono muted" style={{ fontSize: 11 }}>target ${target}</span>
        <span className="mono" style={{ fontSize: 11, color: current && current <= target ? "var(--ok)" : "var(--bad)" }}>now {fmt.cpl(current)}</span>
      </div>
    </div>
  );
}

function FormatBreakdown({ creatives, target }) {
  const vid = creatives.filter(c => c.isVideo && c.live.cpa != null);
  const img = creatives.filter(c => !c.isVideo && c.live.cpa != null);
  const rows = [
    { label: "Video", arr: vid, hue: "var(--acc)" },
    { label: "Image", arr: img, hue: "var(--gold)" },
  ];
  const maxCpl = Math.max(target, ...creatives.filter(c => c.live.cpa).map(c => c.live.cpa)) * 1.1;
  return (
    <div className="chart-card" style={{ marginBottom: 22 }}>
      <div className="chart-head"><h4 className="serif">Video vs Image · avg CPL</h4><span className="muted mono" style={{ fontSize: 12 }}>target ≤ ${target}</span></div>
      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        {rows.map(r => {
          const a = avg(r.arr.map(c => c.live.cpa));
          const pct = Math.min(100, (a / maxCpl) * 100);
          const tpct = (target / maxCpl) * 100;
          return (
            <div key={r.label}>
              <div style={{ display: "flex", justifyContent: "space-between", fontSize: 13, marginBottom: 6 }}>
                <span>{r.label} <span className="muted mono" style={{ fontSize: 11 }}>· {r.arr.length} ads</span></span>
                <span className="mono" style={{ color: a <= target ? "var(--ok)" : "var(--bad)" }}>{fmt.cpl(a)} CPL</span>
              </div>
              <div style={{ position: "relative", height: 12, background: "var(--inset)", borderRadius: 7, overflow: "hidden" }}>
                <div style={{ position: "absolute", inset: 0, width: pct + "%", background: a <= target ? "var(--ok)" : "var(--bad)", opacity: 0.8, borderRadius: 7 }}></div>
                <div style={{ position: "absolute", left: tpct + "%", top: -3, bottom: -3, width: 2, background: "var(--acc)" }}></div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

/* helpers */
function avg(arr) { return arr.length ? arr.reduce((a, b) => a + b, 0) / arr.length : 0; }
function makeTrend(total) {
  const base = total / 14;
  return Array.from({ length: 14 }, (_, i) => Math.max(0, base * (0.5 + i * 0.06) * (0.85 + ((i * 7) % 5) / 12)));
}
function makeCplTrend(cur) {
  const c = cur || 130;
  return [c * 1.35, c * 1.1, c * 1.2, c * 0.95, c * 1.05, c * 0.88, c];
}

Object.assign(window, { InsightsTab });
