// mailroom-analytics.jsx — Analytics. Sends-over-time, reply-rate by sequence
// step, reply-category mix, per-campaign table, A/B compare. Exports: ViewAnalytics.

const SENDS_30D = [120,180,150,210,190,260,240, 220,280,300,260,310,290,340, 300,360,330,380,360,410,390, 360,420,440,400,460,430,480, 450,500];
const REPLIES_30D = SENDS_30D.map((s, i) => Math.round(s * (0.035 + 0.012 * Math.sin(i / 4))));
const STEP_REPLY = [
  { step: "1 · Opener", rate: 2.4, vol: 6470 },
  { step: "2 · Bump", rate: 1.9, vol: 5210 },
  { step: "3 · Value", rate: 3.1, vol: 4180 },
  { step: "4 · Breakup", rate: 4.6, vol: 3020 },
];
const CAT_MIX = [
  { cat: "POSITIVE", n: 116, tone: "good" },
  { cat: "BOOKING", n: 41, tone: "accent" },
  { cat: "OBJECTION", n: 73, tone: "warn" },
  { cat: "NEGATIVE", n: 58, tone: "bad" },
  { cat: "UNSUB", n: 31, tone: "neutral" },
  { cat: "NOISE", n: 92, tone: "neutral" },
];
const PERF = [
  { name: "Q3 · Series-A SaaS founders", id: "cmp_8fa2", sent: 1240, open: 58, reply: 4.8, pos: 31, booked: 5 },
  { name: "Agency owners · warm reactivation", id: "cmp_9c04", sent: 940, open: 63, reply: 6.1, pos: 18, booked: 3 },
  { name: "PLG SaaS · expansion", id: "cmp_6e90", sent: 1980, open: 55, reply: 4.1, pos: 27, booked: 2 },
  { name: "VC scouts · intro round", id: "cmp_2f18", sent: 620, open: 49, reply: 5.4, pos: 14, booked: 1 },
  { name: "Fractional CFOs · breakup test B", id: "cmp_1d55", sent: 460, open: 44, reply: 2.2, pos: 4, booked: 0 },
];

function toneVal(t, tone) {
  return tone === "good" ? t.good : tone === "accent" ? t.accent : tone === "warn" ? t.warn : tone === "bad" ? t.bad : t.textMuted;
}

/* ---- area + line chart ---- */
function SendsChart({ t }) {
  const W = 760, H = 200, P = 6;
  const max = Math.max(...SENDS_30D) * 1.1;
  const xs = (i) => P + (i / (SENDS_30D.length - 1)) * (W - P * 2);
  const ys = (v) => H - 24 - (v / max) * (H - 40);
  const line = SENDS_30D.map((v, i) => `${xs(i)},${ys(v)}`).join(" ");
  const rline = REPLIES_30D.map((v, i) => `${xs(i)},${ys(v * 8)}`).join(" "); // scaled to read
  const area = `${P},${H - 24} ${line} ${W - P},${H - 24}`;
  return (
    <svg viewBox={`0 0 ${W} ${H}`} width="100%" style={{ display: "block" }} preserveAspectRatio="none">
      <defs>
        <linearGradient id="mrArea" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={t.accent} stopOpacity={t.dark ? 0.4 : 0.22} />
          <stop offset="100%" stopColor={t.accent} stopOpacity="0" />
        </linearGradient>
      </defs>
      {[0.25, 0.5, 0.75].map((g) => (
        <line key={g} x1={P} x2={W - P} y1={24 + g * (H - 48)} y2={24 + g * (H - 48)} stroke={t.border} strokeWidth="1" strokeDasharray="3 4" />
      ))}
      <polygon points={area} fill="url(#mrArea)" />
      <polyline points={line} fill="none" stroke={t.accent} strokeWidth="2.4" strokeLinejoin="round" strokeLinecap="round" />
      <polyline points={rline} fill="none" stroke={t.good} strokeWidth="2" strokeDasharray="2 4" strokeLinecap="round" />
    </svg>
  );
}

function ViewAnalytics() {
  const t = useT();
  const [range, setRange] = React.useState("30d");
  const [loading, setLoading] = React.useState(true);
  React.useEffect(() => { setLoading(true); const x = setTimeout(() => setLoading(false), 620); return () => clearTimeout(x); }, [range]);

  const th = { textAlign: "left", fontSize: 10, fontWeight: 700, letterSpacing: ".06em", textTransform: "uppercase",
    color: t.textMuted, padding: "0 14px", height: 36, whiteSpace: "nowrap" };
  const td = { padding: "0 14px", fontSize: 13, color: t.text, whiteSpace: "nowrap" };
  const maxCat = Math.max(...CAT_MIX.map((c) => c.n));

  return (
    <>
      <PageHeader title="Analytics" sub="Performance across all campaigns">
        <div style={{ display: "flex", gap: 2, padding: 2, borderRadius: t.radiusSm, background: t.sunken, border: `1px solid ${t.border}` }}>
          {["7d", "30d", "90d"].map((r) => (
            <button key={r} onClick={() => setRange(r)} style={{ padding: "0 12px", height: 28, border: "none", borderRadius: 3, cursor: "pointer",
              fontFamily: t.mono, fontSize: 12, fontWeight: 700, background: range === r ? t.accent : "transparent", color: range === r ? "#fff" : t.textSec }}>{r}</button>
          ))}
        </div>
        <Btn kind="soft" icon="download" onClick={() => mrToast("Exported analytics · report.csv", { icon: "download" })}>Export</Btn>
      </PageHeader>

      <div style={{ flex: 1, overflowY: "auto", padding: t.pad, display: "flex", flexDirection: "column", gap: t.gap }}>
        {/* stat row */}
        <div style={{ display: "flex", gap: t.gap }}>
          {[["send", "Sent", "6,470", t.accent], ["inbox", "Open rate", "54%", t.info], ["replies", "Reply rate", "4.3%", t.good],
            ["target", "Positive", "116", t.accent], ["calendar", "Booked", "11", t.warn]].map(([ic, l, v, c], i) => (
            <Card key={i} style={{ flex: 1, minWidth: 0, padding: t.pad - 3 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <div style={{ width: 26, height: 26, borderRadius: t.radiusSm, background: hexA(c, t.dark ? 0.2 : 0.12),
                  display: "flex", alignItems: "center", justifyContent: "center", flex: "0 0 auto" }}><Icon name={ic} size={14} color={c} /></div>
                <Label style={{ fontSize: 10 }}>{l}</Label>
              </div>
              {loading ? <Skeleton t={t} w={64} h={26} style={{ marginTop: 13 }} />
                : <div style={{ fontFamily: t.mono, fontSize: 26, fontWeight: 700, color: t.text, letterSpacing: "-.02em", marginTop: 12 }}>{v}</div>}
            </Card>
          ))}
        </div>

        {/* sends over time */}
        <Card>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 14 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 9 }}>
              <span style={{ fontFamily: t.head, fontSize: 14.5, fontWeight: 700, color: t.text }}>Sends & replies over time</span>
              <Chip tone="neutral" mono>{range}</Chip>
            </div>
            <div style={{ display: "flex", gap: 16, fontSize: 11.5, color: t.textMuted }}>
              <LegendLine color={t.accent} label="sent" t={t} />
              <LegendLine color={t.good} dashed label="replies" t={t} />
            </div>
          </div>
          {loading ? <Skeleton t={t} w="100%" h={200} /> : <SendsChart t={t} />}
        </Card>

        {/* two col: step rate + category mix */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: t.gap }}>
          <Card>
            <span style={{ fontFamily: t.head, fontSize: 14.5, fontWeight: 700, color: t.text }}>Reply rate by step</span>
            <div style={{ marginTop: 16, display: "flex", flexDirection: "column", gap: 14 }}>
              {STEP_REPLY.map((s) => (
                <div key={s.step}>
                  <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 6 }}>
                    <span style={{ fontSize: 12.5, color: t.textSec }}>{s.step}</span>
                    <Mono style={{ fontSize: 12.5, fontWeight: 700, color: t.text }}>{s.rate}%</Mono>
                  </div>
                  <div style={{ height: 8, borderRadius: 3, background: t.sunken, overflow: "hidden" }}>
                    {loading ? null : <div style={{ height: "100%", width: `${(s.rate / 5) * 100}%`, background: t.accent, borderRadius: 3, transition: "width .4s" }} />}
                  </div>
                  <Mono style={{ fontSize: 10.5, color: t.textMuted, marginTop: 3 }}>{s.vol.toLocaleString()} sent</Mono>
                </div>
              ))}
            </div>
          </Card>

          <Card>
            <span style={{ fontFamily: t.head, fontSize: 14.5, fontWeight: 700, color: t.text }}>Reply category mix</span>
            <div style={{ marginTop: 18, display: "flex", alignItems: "flex-end", gap: 10, height: 150 }}>
              {CAT_MIX.map((c) => (
                <div key={c.cat} style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: 7, height: "100%", justifyContent: "flex-end" }}>
                  <Mono style={{ fontSize: 12, fontWeight: 700, color: toneVal(t, c.tone) }}>{c.n}</Mono>
                  <div style={{ width: "100%", maxWidth: 34, height: loading ? 0 : `${(c.n / maxCat) * 100}%`, minHeight: loading ? 0 : 4,
                    background: toneVal(t, c.tone), borderRadius: "3px 3px 0 0", transition: "height .4s" }} />
                  <span style={{ fontSize: 9, fontWeight: 700, color: t.textMuted, fontFamily: t.mono, letterSpacing: ".02em" }}>{c.cat}</span>
                </div>
              ))}
            </div>
          </Card>
        </div>

        {/* per-campaign table */}
        <Card pad={false} style={{ overflow: "hidden" }}>
          <div style={{ padding: "14px 16px 12px", borderBottom: `1px solid ${t.border}` }}>
            <span style={{ fontFamily: t.head, fontSize: 14.5, fontWeight: 700, color: t.text }}>By campaign</span>
          </div>
          <div style={{ overflowX: "auto" }}>
            <table style={{ width: "100%", borderCollapse: "collapse", minWidth: 720 }}>
              <thead><tr style={{ borderBottom: `1px solid ${t.border}`, background: t.sunken }}>
                <th style={{ ...th, width: "34%" }}>Campaign</th>
                <th style={{ ...th, textAlign: "right" }}>Sent</th>
                <th style={{ ...th, textAlign: "right" }}>Open</th>
                <th style={{ ...th, textAlign: "right" }}>Reply</th>
                <th style={{ ...th, textAlign: "right" }}>Positive</th>
                <th style={{ ...th, textAlign: "right" }}>Booked</th>
              </tr></thead>
              <tbody>
                {PERF.map((r, i) => (
                  <tr key={r.id} style={{ borderBottom: i < PERF.length - 1 ? `1px solid ${t.border}` : "none", height: t.rowH }}>
                    <td style={td}><div style={{ fontWeight: 600 }}>{r.name}</div><Mono style={{ fontSize: 10.5, color: t.textMuted }}>{r.id}</Mono></td>
                    <td style={{ ...td, textAlign: "right" }}><Mono>{r.sent.toLocaleString()}</Mono></td>
                    <td style={{ ...td, textAlign: "right" }}><Mono style={{ color: t.textSec }}>{r.open}%</Mono></td>
                    <td style={{ ...td, textAlign: "right" }}><Mono style={{ fontWeight: 700, color: r.reply >= 4 ? t.good : t.text }}>{r.reply}%</Mono></td>
                    <td style={{ ...td, textAlign: "right" }}><Mono>{r.pos}</Mono></td>
                    <td style={{ ...td, textAlign: "right" }}><Mono style={{ color: r.booked ? t.accent : t.textMuted, fontWeight: r.booked ? 700 : 400 }}>{r.booked || "—"}</Mono></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </Card>

        {/* A/B compare */}
        <Card>
          <div style={{ display: "flex", alignItems: "center", gap: 9, marginBottom: 4 }}>
            <Icon name="target" size={16} color={t.accent} />
            <span style={{ fontFamily: t.head, fontSize: 14.5, fontWeight: 700, color: t.text }}>A/B test · breakup line</span>
            <Chip tone="good" icon="check">winner: B</Chip>
          </div>
          <div style={{ fontSize: 12.5, color: t.textMuted, marginBottom: 16 }}>Fractional CFOs · subject-line variant on the day-12 breakup email</div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: t.gap }}>
            {[
              { v: "A", subj: "Closing the loop", reply: 2.2, pos: 4, win: false },
              { v: "B", subj: "Should I stop here?", reply: 4.6, pos: 9, win: true },
            ].map((x) => (
              <div key={x.v} style={{ padding: 15, borderRadius: t.radiusSm, border: `1px solid ${x.win ? hexA(t.good, 0.4) : t.border}`,
                background: x.win ? t.goodTint : t.sunken }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 10 }}>
                  <span style={{ width: 24, height: 24, borderRadius: t.radiusSm, background: x.win ? t.good : t.borderStrong, color: "#fff",
                    display: "flex", alignItems: "center", justifyContent: "center", fontFamily: t.mono, fontWeight: 700, fontSize: 12 }}>{x.v}</span>
                  <Mono style={{ fontSize: 12.5, color: t.text }}>"{x.subj}"</Mono>
                  {x.win && <Chip tone="good" style={{ marginLeft: "auto" }}>+109%</Chip>}
                </div>
                <div style={{ display: "flex", gap: 20 }}>
                  <div><Mono style={{ fontSize: 19, fontWeight: 700, color: x.win ? t.good : t.text }}>{x.reply}%</Mono><div style={{ fontSize: 11, color: t.textMuted }}>reply rate</div></div>
                  <div><Mono style={{ fontSize: 19, fontWeight: 700, color: t.text }}>{x.pos}</Mono><div style={{ fontSize: 11, color: t.textMuted }}>positive</div></div>
                </div>
              </div>
            ))}
          </div>
        </Card>
      </div>
    </>
  );
}

function LegendLine({ color, label, dashed, t }) {
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
      <span style={{ width: 16, height: 0, borderTop: `2px ${dashed ? "dashed" : "solid"} ${color}` }} />{label}
    </span>
  );
}
window.ViewAnalytics = ViewAnalytics;
