// Analytics page
const { Card: AnCard, Pill: AnPill, Btn: AnBtn, Topbar: AnTopbar, ConcernIcon: AnCon, Avatar: AnAvatar } = window.UI;

function Analytics() {
  const [range, setRange] = React.useState("30d");
  // Re-render when the real (scoped) bootstrap data lands or changes, so the
  // page never shows the bundled placeholder dataset.
  const [, setTick] = React.useState(0);
  React.useEffect(() => {
    let alive = true;
    const refresh = () => window.LoopData && window.LoopData.bootstrap().then(() => { if (alive) setTick(t => t + 1); }).catch(() => {});
    refresh();
    const off = (window.LoopData && window.LoopData.onChange) ? window.LoopData.onChange(refresh) : null;
    return () => { alive = false; off && off(); };
  }, []);
  const rangeDays = { "7d": 7, "30d": 30, "90d": 90, "1y": 365 }[range] || 30;
  // All figures below come from this user's (already server-scoped) data,
  // windowed to the selected range so the 7d/30d/90d/1y toggle drives the
  // WHOLE page — KPIs, concerns, site share, and the CSAT number/chart —
  // not just the volume bar chart.
  const rangeStart = Date.now() - rangeDays * 86400000;
  const allConvs = window.Mock.conversations || [];
  const convs = allConvs.filter(c => (c._updated || 0) >= rangeStart);
  const sites = window.Mock.websites || [];
  const total = convs.length;
  const open = convs.filter(c => c.status !== "closed").length;
  const closedCount = convs.filter(c => c.status === "closed").length;
  const rated = convs.filter(c => c.rating && (c.rating.stars || c.rating.thumbs));
  const positive = rated.filter(c => c.rating.thumbs ? c.rating.thumbs === "up" : (c.rating.stars || 0) >= 4).length;
  const csat = rated.length ? Math.round(100 * positive / rated.length) + "%" : "—";
  const starRated = rated.filter(c => c.rating.stars);
  const avgStars = starRated.length ? starRated.reduce((s, c) => s + c.rating.stars, 0) / starRated.length : null;
  const resolution = total ? Math.round(100 * closedCount / total) + "%" : "—";

  return (
    <div className="flex-1 flex flex-col h-full overflow-hidden">
      <AnTopbar
        title="Analytics"
        subtitle="Live operational metrics across all your sites"
        right={
          <div className="flex items-center gap-2">
            <div className="inline-flex p-1 rounded-xl bg-white/[0.04] border border-white/[0.06]">
              {["7d","30d","90d","1y"].map(r => (
                <button key={r} onClick={() => setRange(r)} className={`h-7 px-2.5 rounded-lg text-[11.5px] ${range === r ? "bg-white/[0.08] text-white" : "text-white/55"}`}>{r}</button>
              ))}
            </div>
            <AnBtn variant="ghost"><Icon.ArrowUpRight size={14}/> Export CSV</AnBtn>
          </div>
        }
      />
      <div className="flex-1 overflow-y-auto px-7 py-6 space-y-5">
        {/* Top KPIs */}
        <div className="grid md:grid-cols-2 lg:grid-cols-4 gap-3">
          <KPI label="Total chats" value={total.toLocaleString()} delta={`last ${rangeDays}d`} tint="#A6F84A"/>
          <KPI label="Open chats" value={open} delta="active + waiting" tint="#7AB6FF"/>
          <KPI label="Customer satisfaction" value={csat} delta={rated.length + " rating" + (rated.length === 1 ? "" : "s")} tint="#FF9DD2"/>
          <KPI label="Resolution rate" value={resolution} delta={closedCount + " closed"} tint="#FFD37A"/>
        </div>

        {/* Volume + by website */}
        <div className="grid grid-cols-1 lg:grid-cols-[1.5fr_1fr] gap-5">
          <AnCard padded={false}>
            <div className="flex items-center justify-between p-5 border-b border-white/[0.05]">
              <div>
                <div className="text-[14px] font-medium text-white/95">Chat volume by day</div>
                <div className="text-[12px] text-white/45 mt-0.5">Last {rangeDays} days · stacked by website</div>
              </div>
              <div className="flex gap-2">
                {window.Mock.websites.map(w => (
                  <span key={w.id} className="flex items-center gap-1.5 text-[11px] text-white/65"><span className="w-2 h-2 rounded-full" style={{ background: w.color }}/>{w.name.split(" ")[0]}</span>
                ))}
              </div>
            </div>
            <div className="p-5">
              <BigBars numDays={rangeDays}/>
            </div>
          </AnCard>
          <AnCard padded={false}>
            <div className="flex items-center justify-between p-5 border-b border-white/[0.05]">
              <div>
                <div className="text-[14px] font-medium text-white/95">Chats by website</div>
                <div className="text-[12px] text-white/45 mt-0.5">Share of total volume</div>
              </div>
            </div>
            <div className="p-5 grid grid-cols-[140px_1fr] gap-5 items-center">
              {(() => {
                const shares = sites.map(w => ({ w, n: convs.filter(c => c.site === w.id).length })).sort((a, b) => b.n - a.n);
                if (!total) return <div className="col-span-2 text-[12px] text-white/40 text-center py-6">No conversations yet.</div>;
                return (
                  <React.Fragment>
                    <Donut total={total} data={shares.map(s => ({ v: 100 * s.n / total, color: s.w.color }))}/>
                    <div className="space-y-3">
                      {shares.map(({ w, n }) => (
                        <div key={w.id}>
                          <div className="flex items-center justify-between text-[12.5px]">
                            <span className="flex items-center gap-2"><span className="w-2 h-2 rounded-full" style={{ background: w.color }}/>{w.name}</span>
                            <span className="text-white/55 tabular-nums">{n} · {Math.round(100 * n / total)}%</span>
                          </div>
                          <div className="h-1 rounded-full bg-white/[0.05] mt-1.5"><div className="h-full rounded-full" style={{ width: (100 * n / total) + "%", background: w.color }}/></div>
                        </div>
                      ))}
                    </div>
                  </React.Fragment>
                );
              })()}
            </div>
          </AnCard>
        </div>

        {/* Concerns + agent performance */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-5">
          <AnCard padded={false}>
            <div className="p-5 border-b border-white/[0.05]">
              <div className="text-[14px] font-medium text-white/95">Top concerns</div>
              <div className="text-[12px] text-white/45 mt-0.5">What visitors are asking about</div>
            </div>
            <div className="p-5 space-y-4">
              {(() => {
                const counts = {};
                convs.forEach(c => { const k = c.concern || "others"; counts[k] = (counts[k] || 0) + 1; });
                const rows = Object.keys(counts)
                  .map(id => ({ id, count: counts[id], v: Math.round(100 * counts[id] / (total || 1)) }))
                  .sort((a, b) => b.count - a.count).slice(0, 6);
                if (!rows.length) return <div className="text-[12px] text-white/40">No conversations yet.</div>;
                const top = rows[0].count;
                return rows.map(c => {
                  const meta = (window.Mock.concerns || []).find(x => x.id === c.id) || { label: c.id, tint: "#C7B6FF" };
                  return (
                    <div key={c.id}>
                      <div className="flex items-center justify-between mb-1.5">
                        <div className="flex items-center gap-2 text-[12.5px] text-white/85"><AnCon id={c.id} size={12}/> {meta.label}</div>
                        <div className="text-[11.5px] text-white/55 tabular-nums">{c.count.toLocaleString()} <span className="text-white/35">({c.v}%)</span></div>
                      </div>
                      <div className="h-1.5 rounded-full bg-white/[0.05] overflow-hidden"><div className="h-full" style={{ width: (100 * c.count / top) + "%", background: meta.tint }}/></div>
                    </div>
                  );
                });
              })()}
            </div>
          </AnCard>

          <AnCard padded={false}>
            <div className="p-5 border-b border-white/[0.05]">
              <div className="text-[14px] font-medium text-white/95">Agent performance</div>
              <div className="text-[12px] text-white/45 mt-0.5">Response time + CSAT this period</div>
            </div>
            <div className="p-2.5">
              <table className="w-full">
                <thead>
                  <tr className="text-[10.5px] uppercase tracking-wider text-white/40">
                    <th className="text-left px-3 py-2 font-medium">Agent</th>
                    <th className="text-right px-3 py-2 font-medium">Chats</th>
                    <th className="text-right px-3 py-2 font-medium">Avg reply</th>
                    <th className="text-right px-3 py-2 font-medium">CSAT</th>
                  </tr>
                </thead>
                <tbody>
                  {window.Mock.agents.map(a => (
                    <tr key={a.id} className="border-t border-white/[0.04]">
                      <td className="px-3 py-3">
                        <div className="flex items-center gap-2.5">
                          <AnAvatar name={a.name} color={a.color} size={28} status={a.status}/>
                          <div>
                            <div className="text-[12.5px] text-white/90">{a.name}</div>
                            <div className="text-[10.5px] text-white/45">{a.role}</div>
                          </div>
                        </div>
                      </td>
                      <td className="px-3 text-right text-[12.5px] text-white/85 tabular-nums">{a.chats}</td>
                      <td className="px-3 text-right text-[12.5px] text-white/85 tabular-nums">{a.avg}</td>
                      <td className="px-3 text-right">
                        <div className="inline-flex items-center gap-1 text-[12.5px] text-lime tabular-nums">
                          <Icon.Star size={11}/> {a.csat}
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </AnCard>
        </div>

        {/* CSAT trend */}
        <AnCard padded={false}>
          <div className="flex items-center justify-between p-5 border-b border-white/[0.05]">
            <div>
              <div className="text-[14px] font-medium text-white/95">Customer satisfaction</div>
              <div className="text-[12px] text-white/45 mt-0.5">Daily CSAT score (1–5) · last {rangeDays} days</div>
            </div>
            <div className="flex items-baseline gap-2">
              <span className="text-[28px] font-semibold text-white tracking-tight">{avgStars != null ? avgStars.toFixed(2) : "—"}</span>
              <span className="text-[12px] text-white/45">{starRated.length ? starRated.length + " rating" + (starRated.length === 1 ? "" : "s") : ""}</span>
            </div>
          </div>
          <div className="p-5"><LineSat numDays={rangeDays}/></div>
        </AnCard>
      </div>
    </div>
  );
}

function KPI({ label, value, delta, tint }) {
  return (
    <div className="glass rounded-2xl p-5 relative overflow-hidden">
      <div className="text-[11.5px] uppercase tracking-[0.08em] text-white/45">{label}</div>
      <div className="text-[28px] font-semibold tracking-tight text-white mt-2.5 leading-none">{value}</div>
      <div className="text-[11.5px] mt-2 text-white/45">{delta}</div>
      <div className="absolute -right-2 -bottom-2 w-16 h-16 rounded-full opacity-25" style={{ background: `radial-gradient(circle, ${tint}, transparent 70%)` }}/>
    </div>
  );
}

function BigBars({ numDays = 30 }) {
  // Real daily histogram of conversation activity (last-activity timestamps),
  // stacked by website — computed from the caller's scoped conversations.
  const convs = window.Mock.conversations || [];
  const sites = (window.Mock.websites || []).slice(0, 3);
  const dayMs = 86400000;
  const todayStart = new Date(); todayStart.setHours(0, 0, 0, 0);
  const start = todayStart.getTime() - (numDays - 1) * dayMs;
  const cols = Array.from({ length: numDays }, (_, i) => {
    const from = start + i * dayMs, to = from + dayMs;
    const inDay = convs.filter(c => (c._updated || 0) >= from && (c._updated || 0) < to);
    return {
      label: new Date(from).getDate(),
      parts: sites.map(s => inDay.filter(c => c.site === s.id).length),
      other: inDay.filter(c => !sites.some(s => s.id === c.site)).length,
    };
  });
  const totals = cols.map(d => d.parts.reduce((a, b) => a + b, 0) + d.other);
  const max = Math.max(1, ...totals);
  if (!convs.length) return <div className="h-[220px] grid place-items-center text-[12px] text-white/35">No conversations yet.</div>;
  return (
    <div className="h-[220px] flex items-end gap-1">
      {cols.map((d, i) => {
        const t = totals[i];
        return (
          <div key={i} className="flex-1 flex flex-col items-center gap-1.5 group">
            <div className="w-full rounded-md overflow-hidden flex flex-col-reverse" style={{ height: (t ? Math.max((t / max) * 100, 3) : 0) + "%" }}>
              {d.parts.map((n, j) => n > 0 ? <div key={j} style={{ height: (n / t) * 100 + "%", background: sites[j].color }}/> : null)}
              {d.other > 0 && <div style={{ height: (d.other / t) * 100 + "%", background: "#C7B6FF" }}/>}
            </div>
            <div className="text-[9px] text-white/30 tabular-nums">{(numDays <= 31 || i % 7 === 0) ? d.label : ""}</div>
          </div>
        );
      })}
    </div>
  );
}

function Donut({ data }) {
  const r = 50, cx = 60, cy = 60, c = 2 * Math.PI * r;
  let acc = 0;
  return (
    <svg viewBox="0 0 120 120" className="w-[140px] h-[140px] -rotate-90">
      <circle cx={cx} cy={cy} r={r} fill="none" stroke="rgba(255,255,255,0.05)" strokeWidth="14"/>
      {data.map((d, i) => {
        const len = (d.v / 100) * c;
        const offset = -acc;
        acc += len;
        return (
          <circle key={i} cx={cx} cy={cy} r={r} fill="none" stroke={d.color} strokeWidth="14" strokeDasharray={`${len} ${c - len}`} strokeDashoffset={offset} strokeLinecap="round"/>
        );
      })}
      <text x="60" y="60" textAnchor="middle" dy="6" fill="white" fontSize="20" fontWeight="600" transform="rotate(90 60 60)">100%</text>
    </svg>
  );
}

function LineSat({ numDays = 30 }) {
  // Real average star rating over the selected range, bucketed into up to 30
  // points (so a 1-year range groups into wider buckets instead of 365 dots).
  const convs = window.Mock.conversations || [];
  const dayMs = 86400000;
  const start = Date.now() - numDays * dayMs;
  const rated = convs.filter(c => c.rating && c.rating.stars && (c.rating.at || c._updated || 0) >= start);
  if (!rated.length) return <div className="h-[160px] grid place-items-center text-[12px] text-white/35">No ratings in this range — CSAT appears once customers rate their chats.</div>;
  const buckets = Math.min(numDays, 30);
  const span = (numDays * dayMs) / buckets;
  const points = Array.from({ length: buckets }, (_, i) => {
    const from = start + i * span, to = from + span;
    const day = rated.filter(c => { const at = c.rating.at || c._updated || 0; return at >= from && at < to; });
    return day.length ? day.reduce((s, c) => s + c.rating.stars, 0) / day.length : null;
  });
  const w = 800, h = 160, pad = 10;
  const min = 1, max = 5;
  const xs = points.map((_, i) => pad + (i / (points.length - 1)) * (w - pad * 2));
  const ys = points.map(v => v == null ? null : pad + (1 - (v - min) / (max - min)) * (h - pad * 2));
  let path = "", started = false;
  xs.forEach((x, i) => { if (ys[i] == null) return; path += `${started ? "L" : "M"} ${x} ${ys[i]} `; started = true; });
  return (
    <svg viewBox={`0 0 ${w} ${h}`} className="w-full h-[160px]">
      <path d={path} stroke="#A6F84A" strokeWidth="2" fill="none"/>
      {xs.map((x, i) => ys[i] != null && (
        <circle key={i} cx={x} cy={ys[i]} r="3.5" fill="#A6F84A" stroke="#070809" strokeWidth="2"/>
      ))}
    </svg>
  );
}

window.Analytics = Analytics;
