/* Dashboard (M15/M16) — KPI tiles double as selectors for ONE big daily chart
   (hover → the day's posts), combine-all + per-platform filter, and a post
   section that toggles between the next-5-days Scheduled Posts and Performers
   (sortable list/card, reschedule, reuse-best, CSV/XLSX export). Charts follow
   the dataviz skill: single-hue series, thin marks, recessive grid, hover. */
(function () {
  const D = window.CROPR_DATA;
  const A = window.CroprAnalytics;
  const S = window.CroprStore;
  const BLUE = "#0EA5B7"; // DS primary teal (chart line/bars/area)
  const nf = (n) => Number(n || 0).toLocaleString("en-GB");
  const compact = (n) => n >= 1000 ? (n / 1000).toFixed(n >= 10000 ? 0 : 1).replace(/\.0$/, "") + "K" : "" + n;
  const KPIS = [
    { id: "impressions", label: "Impressions" }, { id: "engagement", label: "Engagement" },
    { id: "likes", label: "Likes" }, { id: "shares", label: "Shares" }, { id: "comments", label: "Comments" },
    { id: "totalFollowers", label: "Total followers" }, { id: "newFollowers", label: "New followers" },
  ];
  const KLABEL = KPIS.reduce((m, k) => ((m[k.id] = k.label), m), {});

  function KpiTile({ label, value, active, onClick }) {
    return (
      <button onClick={onClick} style={{ textAlign: "left", cursor: "pointer", fontFamily: "inherit",
        background: active ? "var(--accent-weak)" : "var(--surface)", border: `1px solid ${active ? "var(--accent)" : "var(--border)"}`,
        borderRadius: 14, padding: "13px 15px", boxShadow: "var(--shadow-sm)", minWidth: 0, transition: "all 140ms" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
          <span style={{ width: 8, height: 8, borderRadius: 3, background: active ? BLUE : "var(--border-strong)" }} />
          <span style={{ fontSize: 11, color: active ? "var(--accent)" : "var(--fg3)", fontWeight: 600, textTransform: "uppercase", letterSpacing: ".04em", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{label}</span>
        </div>
        <div style={{ fontSize: 23, fontWeight: 700, fontVariantNumeric: "tabular-nums", letterSpacing: "-.01em", marginTop: 2 }}>{nf(value)}</div>
      </button>
    );
  }

  function BigChart({ kpi, data }) {
    const [hi, setHi] = React.useState(-1);
    const [type, setType] = React.useState("line");
    const ref = React.useRef(null);
    const w = 900, h = 300, padL = 6, padR = 6, padT = 16, padB = 24;
    const vals = data.map((d) => d.value); const max = Math.max(1, ...vals);
    const X = (i) => padL + (i / (data.length - 1 || 1)) * (w - padL - padR);
    const Y = (v) => padT + (1 - v / max) * (h - padT - padB);
    const line = data.map((d, i) => `${i ? "L" : "M"}${X(i).toFixed(1)},${Y(d.value).toFixed(1)}`).join(" ");
    const area = `${line} L${X(data.length - 1)},${h - padB} L${X(0)},${h - padB} Z`;
    const barW = Math.max(2, (w - padL - padR) / Math.max(1, data.length) * 0.62);
    const onMove = (e) => { const r = ref.current.getBoundingClientRect(); const ratio = (e.clientX - r.left) / r.width; setHi(Math.max(0, Math.min(data.length - 1, Math.round(ratio * (data.length - 1))))); };
    const hd = hi >= 0 ? data[hi] : null;
    const gridY = [0.25, 0.5, 0.75, 1].map((f) => padT + f * (h - padT - padB));
    return (
      <Card pad={18}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 8, gap: 12, flexWrap: "wrap" }}>
          <span style={{ fontSize: 15, fontWeight: 700 }}>{KLABEL[kpi]}</span>
          <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <span style={{ fontSize: 11.5, color: "var(--fg3)" }}>daily · hover for the day's posts</span>
            <Segmented value={type} onChange={setType} options={[{ value: "line", label: "Line", icon: "line-chart" }, { value: "bar", label: "Bar", icon: "bar-chart-3" }]} />
          </div>
        </div>
        <div style={{ position: "relative" }} ref={ref} onMouseMove={onMove} onMouseLeave={() => setHi(-1)}>
          <svg viewBox={`0 0 ${w} ${h}`} style={{ width: "100%", height: h, display: "block" }} preserveAspectRatio="none">
            <defs><linearGradient id="dash_area" x1="0" y1="0" x2="0" y2="1"><stop offset="0%" stopColor={BLUE} stopOpacity="0.22" /><stop offset="100%" stopColor={BLUE} stopOpacity="0" /></linearGradient></defs>
            {gridY.map((y, i) => <line key={i} x1={padL} y1={y} x2={w - padR} y2={y} stroke="var(--border)" strokeWidth="1" opacity="0.6" />)}
            {type === "bar" ? (
              data.map((d, i) => { const by = Y(d.value); return <rect key={i} x={X(i) - barW / 2} y={by} width={barW} height={Math.max(0, (h - padB) - by)} rx="2.5" fill={BLUE} opacity={hi < 0 || hi === i ? 1 : 0.4} />; })
            ) : (
              <React.Fragment>
                <path d={area} fill="url(#dash_area)" />
                <path d={line} fill="none" stroke={BLUE} strokeWidth="2.5" strokeLinejoin="round" strokeLinecap="round" />
              </React.Fragment>
            )}
            {hd && type === "line" && <line x1={X(hi)} y1={padT} x2={X(hi)} y2={h - padB} stroke={BLUE} strokeWidth="1" strokeDasharray="3 3" opacity="0.5" />}
            {hd && type === "line" && <circle cx={X(hi)} cy={Y(hd.value)} r="5" fill={BLUE} stroke="#fff" strokeWidth="2.5" />}
          </svg>
          <div style={{ display: "flex", justifyContent: "space-between", marginTop: 4 }}>
            <span style={{ fontSize: 10.5, color: "var(--fg4)" }}>{data.length ? new Date(data[0].date).toLocaleDateString("en-GB", { day: "2-digit", month: "short" }) : ""}</span>
            <span style={{ fontSize: 10.5, color: "var(--fg4)" }}>{data.length ? new Date(data[data.length - 1].date).toLocaleDateString("en-GB", { day: "2-digit", month: "short" }) : ""}</span>
          </div>
          {hd && (
            <div style={{ position: "absolute", top: 0, left: `${(hi / (data.length - 1 || 1)) * 100}%`, transform: `translateX(${hi > data.length / 2 ? "-100%" : "0"})`, pointerEvents: "none",
              background: "var(--fg1)", color: "#fff", borderRadius: 10, padding: "9px 12px", fontSize: 12, boxShadow: "var(--shadow-lg)", minWidth: 150, zIndex: 3 }}>
              <div style={{ opacity: .8 }}>{new Date(hd.date).toLocaleDateString("en-GB", { weekday: "short", day: "2-digit", month: "short" })}</div>
              <div style={{ fontSize: 17, fontWeight: 700, margin: "2px 0" }}>{nf(hd.value)}</div>
              {(hd.posts || []).slice(0, 4).map((p) => (
                <div key={p.id} style={{ opacity: .92, marginTop: 4, borderTop: "1px solid rgba(255,255,255,.15)", paddingTop: 4 }}>
                  <div style={{ fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis", maxWidth: 190 }}>{p.title}</div>
                  <div style={{ opacity: .7 }}>{compact(p.m.impressions)} impr · {compact(p.m.engagement)} eng</div>
                </div>
              ))}
              {(!hd.posts || hd.posts.length === 0) && <div style={{ opacity: .6, fontSize: 11 }}>no posts this day</div>}
            </div>
          )}
        </div>
      </Card>
    );
  }

  function Dots({ channels }) {
    return <span style={{ display: "inline-flex" }}>{(channels || []).map((ch, i) => { const cm = D.CHANNELS[ch]; if (!cm) return null; return <span key={ch} style={{ marginLeft: i ? -6 : 0, border: "2px solid var(--surface)", borderRadius: 999 }}><Avatar color={cm.avatar} initials={cm.initials} src={cm.icon} size={22} /></span>; })}</span>;
  }

  function Resched({ post, onToast }) {
    const [open, setOpen] = React.useState(false);
    const [val, setVal] = React.useState("");
    return (
      <span style={{ position: "relative", display: "inline-flex" }}>
        <Button size="sm" variant="ghost" icon="calendar" onClick={() => setOpen((o) => !o)}>Reschedule</Button>
        {open && (
          <div style={{ position: "absolute", top: 36, right: 0, zIndex: 30, background: "var(--surface)", border: "1px solid var(--border)", borderRadius: 12, boxShadow: "var(--shadow-lg)", padding: 12, width: 224 }}>
            <div style={{ fontSize: 11, fontWeight: 700, color: "var(--fg3)", marginBottom: 6 }}>Reschedule · Europe/Vienna</div>
            <input type="datetime-local" value={val} onChange={(e) => setVal(e.target.value)} style={{ width: "100%", boxSizing: "border-box", fontFamily: "inherit", fontSize: 12.5, padding: "7px 9px", borderRadius: 8, border: "1px solid var(--border-strong)", background: "var(--surface)", color: "var(--fg1)" }} />
            <div style={{ display: "flex", gap: 6, marginTop: 10, justifyContent: "flex-end" }}>
              <Button size="sm" variant="ghost" onClick={() => setOpen(false)}>Cancel</Button>
              <Button size="sm" variant="primary" disabled={!val} onClick={() => { if (val) { S.reschedule(post.id, new Date(val).toISOString()); onToast("Rescheduled"); } setOpen(false); }}>Save</Button>
            </div>
          </div>
        )}
      </span>
    );
  }

  function ScheduledRow({ post, onOpen }) {
    const dt = new Date(post.scheduleAt);
    return (
      <div style={{ display: "flex", alignItems: "center", gap: 14, padding: "12px 16px", borderBottom: "1px solid var(--border)" }}>
        <div style={{ textAlign: "center", flex: "none", width: 62 }}>
          <div style={{ fontSize: 12, fontWeight: 700, color: "var(--accent)" }}>{dt.toLocaleDateString("en-GB", { weekday: "short" })}</div>
          <div style={{ fontSize: 15, fontWeight: 700, fontVariantNumeric: "tabular-nums" }}>{dt.toLocaleDateString("en-GB", { day: "2-digit", month: "short" })}</div>
          <div style={{ fontSize: 11, color: "var(--fg3)" }}>{dt.toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit" })}</div>
        </div>
        <div style={{ width: 1, alignSelf: "stretch", background: "var(--border)" }} />
        <HoverImage src={postThumb(post)} size={44} radius={9} label={post.title} />
        <div style={{ minWidth: 0, flex: 1, cursor: "pointer" }} onClick={() => onOpen(post.id)}>
          <div style={{ fontSize: 13.5, fontWeight: 700, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{post.title}</div>
          <div style={{ fontSize: 11, color: "var(--fg3)", marginTop: 2 }}>{D.label(D.SERIES, post.series)}{post.campaign ? " · " + post.campaign : ""}</div>
        </div>
        <Dots channels={post.channels} />
        <StatusBadge status={post.status} />
        <Button size="sm" variant="ghost" icon="pen-line" onClick={() => onOpen(post.id)}>Open</Button>
      </div>
    );
  }

  function ScheduledCard({ post, onOpen }) {
    const dt = new Date(post.scheduleAt);
    return (
      <Card pad={16} hover onClick={() => onOpen(post.id)} style={{ cursor: "pointer" }}>
        {postThumb(post) && <img src={postThumb(post)} alt="" style={{ width: "100%", height: 120, objectFit: "cover", borderRadius: 10, marginBottom: 10, display: "block", border: "1px solid var(--border)" }} />}
        <div style={{ display: "flex", gap: 8, marginBottom: 8, alignItems: "center" }}><Dots channels={post.channels} /><div style={{ flex: 1 }} /><StatusBadge status={post.status} /></div>
        <div style={{ fontSize: 14, fontWeight: 700, marginBottom: 6, lineHeight: 1.3, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{post.title}</div>
        <div style={{ fontSize: 11.5, color: "var(--fg3)", display: "flex", alignItems: "center", gap: 6 }}>
          <Icon name="calendar-clock" size={13} color="var(--accent)" />
          {dt.toLocaleDateString("en-GB", { weekday: "short", day: "2-digit", month: "short" })} · {dt.toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit" })}
          {post.campaign ? <span style={{ marginLeft: 2 }}>· {post.campaign}</span> : null}
        </div>
      </Card>
    );
  }

  function PerfRow({ row, view, onOpen, onReuse, onToast }) {
    const p = row.post, m = row.m;
    const stat = (l, v, mw) => <span style={{ display: "flex", flexDirection: "column", minWidth: mw || 0 }}><span style={{ fontSize: 10, color: "var(--fg3)", fontWeight: 600 }}>{l}</span><span style={{ fontSize: 13, fontWeight: 700, fontVariantNumeric: "tabular-nums" }}>{compact(v)}</span></span>;
    if (view === "card") {
      return (
        <Card pad={16} hover onClick={() => onOpen(p.id)} style={{ cursor: "pointer" }}>
          {postThumb(p) && <img src={postThumb(p)} alt="" style={{ width: "100%", height: 120, objectFit: "cover", borderRadius: 10, marginBottom: 10, display: "block", border: "1px solid var(--border)" }} />}
          <div style={{ display: "flex", gap: 8, marginBottom: 8, alignItems: "center" }}><Dots channels={p.channels} /><div style={{ flex: 1 }} /><Badge color="var(--fg3)">{D.label(D.PILLARS, p.pillar)}</Badge></div>
          <div style={{ fontSize: 14, fontWeight: 700, marginBottom: 4, lineHeight: 1.3 }}>{p.title}</div>
          <div style={{ fontSize: 11, color: "var(--fg3)", marginBottom: 12 }}>{new Date(row.date).toLocaleDateString("en-GB", { day: "2-digit", month: "short" })}</div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "8px 12px", background: "var(--bg-subtle)", borderRadius: 10, padding: "10px 12px" }}>{stat("Impr", m.impressions)}{stat("Eng", m.engagement)}{stat("Likes", m.likes)}{stat("Shares", m.shares)}</div>
          <div style={{ display: "flex", gap: 8, marginTop: 12 }} onClick={(e) => e.stopPropagation()}><Resched post={p} onToast={onToast} /><Button size="sm" variant="ghost" icon="recycle" onClick={() => onReuse(p.id)}>Reuse</Button></div>
        </Card>
      );
    }
    return (
      <div style={{ display: "flex", alignItems: "center", gap: 14, padding: "12px 16px", borderBottom: "1px solid var(--border)" }}>
        <HoverImage src={postThumb(p)} size={40} radius={8} label={p.title} />
        <Dots channels={p.channels} />
        <div style={{ minWidth: 0, flex: 1, cursor: "pointer" }} onClick={() => onOpen(p.id)}>
          <div style={{ fontSize: 13.5, fontWeight: 700, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{p.title}</div>
          <div style={{ fontSize: 11, color: "var(--fg3)" }}>{D.label(D.PILLARS, p.pillar)} · {new Date(row.date).toLocaleDateString("en-GB", { day: "2-digit", month: "short" })}</div>
        </div>
        {stat("Impr", m.impressions, 54)}{stat("Eng", m.engagement, 54)}{stat("Likes", m.likes, 54)}{stat("Shares", m.shares, 54)}
        <Resched post={p} onToast={onToast} />
        <Button size="sm" variant="ghost" icon="recycle" onClick={() => onReuse(p.id)}>Reuse</Button>
      </div>
    );
  }

  // multi-select platform filter for the lists (All / X / LinkedIn / Telegram)
  function PlatformFilter({ value, onChange }) {
    const isAll = value.length === 0;
    const chip = (active, node, onClick, key) => <button key={key} onClick={onClick} style={{ display: "inline-flex", alignItems: "center", gap: 6, border: `1px solid ${active ? "var(--accent)" : "var(--border-strong)"}`, background: active ? "var(--accent-weak)" : "var(--surface)", color: active ? "var(--accent)" : "var(--fg2)", borderRadius: 999, padding: "5px 11px", fontSize: 12.5, fontWeight: 600, cursor: "pointer", fontFamily: "inherit" }}>{node}</button>;
    return (
      <div style={{ display: "inline-flex", gap: 6, flexWrap: "wrap" }}>
        {chip(isAll, "All", () => onChange([]), "all")}
        {D.PLATFORMS.map((p) => chip(value.includes(p.id), <React.Fragment><PlatformLogo platform={p.id} size={14} />{p.label}</React.Fragment>, () => onChange(value.includes(p.id) ? value.filter((x) => x !== p.id) : [...value, p.id]), p.id))}
      </div>
    );
  }

  // single Export button with a CSV / XLSX dropdown
  function ExportMenu({ onExport, count }) {
    const [open, setOpen] = React.useState(false);
    const item = (icon, label, kind) => (
      <button onClick={() => { setOpen(false); onExport(kind); }} style={{ display: "flex", alignItems: "center", gap: 8, width: "100%", border: 0, background: "transparent", cursor: "pointer", padding: "8px 10px", borderRadius: 8, fontSize: 13, fontWeight: 500, fontFamily: "inherit", color: "var(--fg1)" }}
        onMouseEnter={(e) => (e.currentTarget.style.background = "var(--bg-muted)")} onMouseLeave={(e) => (e.currentTarget.style.background = "transparent")}>
        <Icon name={icon} size={16} color="var(--fg2)" />{label}
      </button>
    );
    return (
      <div style={{ position: "relative" }}>
        <Button size="sm" variant="secondary" icon="download" iconRight="chevron-down" onClick={() => setOpen((o) => !o)}>Export</Button>
        {open && (
          <React.Fragment>
            <div onClick={() => setOpen(false)} style={{ position: "fixed", inset: 0, zIndex: 20 }} />
            <div style={{ position: "absolute", top: 38, right: 0, zIndex: 30, background: "var(--surface)", border: "1px solid var(--border)", borderRadius: 10, boxShadow: "var(--shadow-lg)", padding: 4, minWidth: 168 }}>
              {item("file-text", "CSV (.csv)", "csv")}
              {item("table", "Excel (.xlsx)", "xlsx")}
              <div style={{ fontSize: 10.5, color: "var(--fg4)", padding: "4px 10px 2px" }}>{count} rows · current filters</div>
            </div>
          </React.Fragment>
        )}
      </div>
    );
  }

  function AnalyticsView({ posts, onOpen, onReuse, onToast, onNav }) {
    const [range, setRange] = React.useState("14d");
    const [platform, setPlatform] = React.useState("all");
    const [kpi, setKpi] = React.useState("impressions");
    const [mode, setMode] = React.useState("scheduled");
    const [view, setView] = React.useState("list");
    const [sort, setSort] = React.useState("performance");
    const [listPlats, setListPlats] = React.useState([]); // multi-select platform filter for the lists

    const k = A.kpis(range, platform);
    const series = A.series(kpi, range, platform);
    const matchPlats = (post) => listPlats.length === 0 || (post.channels || []).some((ch) => listPlats.includes((D.CHANNELS[ch] || {}).platform));

    const now = Date.now(), in5 = now + 5 * 864e5;
    const scheduled = (posts || []).filter((p) => {
      if (!p.scheduleAt) return false;
      const t = new Date(p.scheduleAt).getTime();
      if (t < now || t > in5) return false;
      return ["queued", "paused", "publishing"].includes(p.scheduleState) || p.status === "scheduled" || p.status === "approved";
    }).filter(matchPlats).sort((a, b) => new Date(a.scheduleAt) - new Date(b.scheduleAt));

    const perf = A.postsList(sort, "all", range).filter((r) => matchPlats(r.post));

    const exportRows = perf.map((r) => ({
      date: new Date(r.date).toISOString().slice(0, 10),
      channels: r.post.channels.map((c) => { const m = D.CHANNELS[c] || {}; return (m.name || c) + "/" + (m.platform || "?"); }).join(" · "),
      pillar: D.label(D.PILLARS, r.post.pillar), series: D.label(D.SERIES, r.post.series), status: r.post.status,
      impressions: r.m.impressions, engagement: r.m.engagement, likes: r.m.likes, shares: r.m.shares,
    }));
    const EXPORT_COLS = ["date", "channels", "pillar", "series", "status", "impressions", "engagement", "likes", "shares"];
    const doExport = (kind) => {
      const name = `leap-analytics-${range}-${platform}`;
      if (kind === "csv") window.CroprExport.exportCSV(EXPORT_COLS, exportRows, name + ".csv");
      else window.CroprExport.exportXLSX(EXPORT_COLS, exportRows, name + ".xlsx");
      onToast(`Exported ${exportRows.length} rows (${kind.toUpperCase()})`);
    };

    return (
      <div style={{ maxWidth: "var(--page-w)", margin: "0 auto" }}>
        {window.WizardBanner && <div style={{ marginBottom: 18 }}><WizardBanner onExplore={() => onNav && onNav("wizards")} onBecome={() => onNav && onNav("settings")} /></div>}
        <div style={{ display: "flex", gap: 12, alignItems: "center", marginBottom: 18, flexWrap: "wrap" }}>
          <Segmented value={range} onChange={setRange} options={D.ANALYTICS_RANGES.map((r) => ({ value: r.id, label: r.label }))} />
          <div style={{ flex: 1 }} />
          <Segmented value={platform} onChange={setPlatform} options={[{ value: "all", label: "All" }].concat(D.PLATFORMS.map((p) => ({ value: p.id, label: p.label, iconNode: <PlatformLogo platform={p.id} size={15} /> })))} />
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(150px,1fr))", gap: 12, marginBottom: 18 }}>
          {KPIS.map((kp) => <KpiTile key={kp.id} label={kp.label} value={k[kp.id]} active={kpi === kp.id} onClick={() => setKpi(kp.id)} />)}
        </div>

        <div style={{ marginBottom: 26 }}><BigChart kpi={kpi} data={series} /></div>

        <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 12, flexWrap: "wrap" }}>
          <Segmented value={mode} onChange={setMode} options={[{ value: "scheduled", label: "Scheduled posts", icon: "calendar-clock" }, { value: "performers", label: "Performers", icon: "trending-up" }]} />
          <PlatformFilter value={listPlats} onChange={setListPlats} />
          <div style={{ flex: 1 }} />
          {mode === "performers" && <Segmented value={sort} onChange={setSort} options={[{ value: "performance", label: "Best", icon: "flame" }, { value: "date", label: "Newest", icon: "calendar" }]} />}
          <Segmented value={view} onChange={setView} options={[{ value: "list", label: "List", icon: "list" }, { value: "card", label: "Cards", icon: "layout-grid" }]} />
          {mode === "performers" && <ExportMenu onExport={doExport} count={perf.length} />}
        </div>

        {mode === "scheduled" ? (
          scheduled.length === 0
            ? <Card pad={40} style={{ textAlign: "center", color: "var(--fg3)" }}><Icon name="calendar-clock" size={26} color="var(--fg4)" /><div style={{ marginTop: 8, fontSize: 13 }}>Nothing scheduled in the next 5 days.</div></Card>
            : view === "card"
              ? <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill,minmax(240px,1fr))", gap: 14 }}>{scheduled.map((p) => <ScheduledCard key={p.id} post={p} onOpen={onOpen} />)}</div>
              : <Card pad={0}>
                  <div style={{ padding: "10px 16px", fontSize: 11, fontWeight: 700, color: "var(--fg3)", textTransform: "uppercase", letterSpacing: ".05em", borderBottom: "1px solid var(--border)", background: "var(--bg-subtle)", borderRadius: "16px 16px 0 0" }}>Next 5 days · {scheduled.length}</div>
                  {scheduled.map((p) => <ScheduledRow key={p.id} post={p} onOpen={onOpen} />)}
                </Card>
        ) : (
          perf.length === 0
            ? <Card pad={40} style={{ textAlign: "center", color: "var(--fg3)" }}>No published posts in this range.</Card>
            : view === "card"
              ? <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill,minmax(240px,1fr))", gap: 14 }}>{perf.map((r) => <PerfRow key={r.post.id} row={r} view="card" onOpen={onOpen} onReuse={onReuse} onToast={onToast} />)}</div>
              : <Card pad={0}>{perf.map((r) => <PerfRow key={r.post.id} row={r} view="list" onOpen={onOpen} onReuse={onReuse} onToast={onToast} />)}</Card>
        )}
      </div>
    );
  }
  window.AnalyticsView = AnalyticsView;
})();
