// Dashboard page — Bloomberg-dense KPI overview for Raudhah clinic group
// Data source: window.RAUDHAH_DATA (server-rendered from FastAPI)

const D = window.RAUDHAH_DATA;
const URLS = window.RAUDHAH_URLS || { dashboard: "/", entry: "/entry", targets: "/targets", branch: "/branch/" };

// ---- Summary KPIs -------------------------------------------------------
function KpiSummary({ mode, branches, windowSize }) {
  const last = D.weeks.length - 1;
  const start = Math.max(0, last - windowSize + 1);
  const sumAt = (obj, wk) => branches.reduce((a, b) => a + ((obj[b.id] && obj[b.id][wk]) || 0), 0);

  const fbSeries = D.weeks.map((_, i) => sumAt(D.fb, i));
  const waSeries = D.weeks.map((_, i) => sumAt(D.wa, i));
  const ttSeries = D.weeks.map((_, i) => sumAt(D.tt, i));
  const igSeries = D.ig.total || [];

  function windowBaseline(series) {
    for (let i = start; i <= last; i++) {
      if (series[i] != null) return { value: series[i], idx: i };
    }
    return { value: null, idx: null };
  }

  const cards = [
    { key: "fb", label: "FB FOLLOWERS",     swatch: "var(--raudhah-pink)", series: fbSeries, color: "var(--raudhah-pink)" },
    { key: "wa", label: "WA MEMBERS",       swatch: "var(--teal)",         series: waSeries, color: "var(--teal)" },
    { key: "tt", label: "TIKTOK FOLLOWERS", swatch: "var(--b-bs)",         series: ttSeries, color: "var(--b-bs)" },
    { key: "ig", label: "IG FOLLOWERS",     swatch: "var(--b-mn)",         series: igSeries, color: "var(--b-mn)" },
  ];

  // Branch view: hide IG (not branch-scoped)
  const visibleCards = mode === "branch" ? cards.filter(c => c.key !== "ig") : cards;

  const grVals = Object.values(D.gr).filter(g => g);
  const grTotal = grVals.reduce((a, b) => a + (b.total || 0), 0);
  const grRating = grTotal ? (grVals.reduce((a, b) => a + (b.rating || 0) * (b.total || 0), 0) / grTotal).toFixed(2) : "—";

  const pendingEntries = (D.missing || []).length;
  const newBranchCount = D.BRANCHES.filter(b => b.isNew).length;

  return (
    <div className="row c-4" style={{ marginBottom: 12 }}>
      {visibleCards.map(c => {
        const value = c.series[last] || 0;
        const baseline = windowBaseline(c.series);
        const d = baseline.value != null ? value - baseline.value : null;
        const pct = (baseline.value != null && baseline.value !== 0) ? +((d / baseline.value) * 100).toFixed(2) : null;
        const since = baseline.idx != null && baseline.idx > start ? D.weeks[baseline.idx] : null;
        const sparkSlice = c.series.slice(start);
        return (
          <div className="kpi-card" key={c.label} data-tip={`Click to open ${c.label}`}>
            <div>
              <div className="kpi-label"><span className="swatch" style={{ background: c.swatch }}></span>{c.label}</div>
              <div className="kpi-value">{value.toLocaleString()}</div>
            </div>
            <div className="kpi-foot">
              <div className="spark"><Sparkline data={sparkSlice} color={c.color} /></div>
              {d == null
                ? <span className="delta flat">—</span>
                : <Delta value={d} pct={pct} />}
              {since && <small style={{ color: "var(--fg3)", fontSize: 10, marginLeft: 4 }}>since {since.slice(5)}</small>}
            </div>
          </div>
        );
      })}
      <div className="kpi-card" style={{ gridColumn: "1 / -1", minHeight: 0 }}>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 24, alignItems: "center" }}>
          <div>
            <div className="kpi-label"><span className="swatch" style={{ background: "#D9C14A" }}></span>GOOGLE REVIEWS · TOTAL</div>
            <div className="kpi-value">{grTotal.toLocaleString()}</div>
          </div>
          <div>
            <div className="kpi-label"><span className="swatch" style={{ background: "var(--ok)" }}></span>AVG RATING</div>
            <div className="kpi-value">{grRating}<span className="unit">★</span></div>
          </div>
          <div>
            <div className="kpi-label"><span className="swatch" style={{ background: "var(--raudhah-pink)" }}></span>ACTIVE BRANCHES</div>
            <div className="kpi-value">{D.BRANCHES.length}{newBranchCount ? <span className="unit">· {newBranchCount} new</span> : null}</div>
          </div>
          <div>
            <div className="kpi-label"><span className="swatch" style={{ background: "var(--warn)" }}></span>WEEKLY ENTRIES DUE</div>
            <div className="kpi-value">{pendingEntries}<span className="unit">pending</span></div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ---- Multi-branch line chart (ApexCharts) -------------------------------
function LineChart({ id, title, eyebrow, sourceKey, branches, windowSize = 12, height = 240, foot }) {
  const ref = useRef(null);
  const chartRef = useRef(null);
  const [theme, setTheme] = useState(document.documentElement.getAttribute("data-theme") || "light");

  useEffect(() => {
    const obs = new MutationObserver(() => setTheme(document.documentElement.getAttribute("data-theme") || "light"));
    obs.observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme"] });
    return () => obs.disconnect();
  }, []);

  useEffect(() => {
    if (!ref.current || !window.ApexCharts) return;
    const last = D.weeks.length - 1;
    const start = Math.max(0, last - windowSize + 1);
    const slicedWeeks = D.weeks.slice(start);
    const series = (sourceKey === "ig")
      ? [{ name: "IG", data: (D.ig.total || []).slice(start).map((v, i) => ({ x: slicedWeeks[i], y: v })), color: "var(--b-mn)" }]
      : branches.map(b => ({
          name: b.code,
          data: ((D[sourceKey] && D[sourceKey][b.id]) || []).slice(start).map((v, i) => ({ x: slicedWeeks[i], y: v })),
          color: b.hex,
        }));
    const opts = {
      chart: {
        type: "line", height, toolbar: { show: false },
        animations: { enabled: true, speed: 500 },
        fontFamily: "Poppins", background: "transparent", parentHeightOffset: 0,
        events: {
          markerClick: (_, __, cfg) => {
            const br = branches[cfg.seriesIndex];
            if (br && br.slug) location.href = URLS.branch + br.slug;
          },
        },
      },
      theme: { mode: theme },
      series,
      stroke: { curve: "smooth", width: 2 },
      colors: sourceKey === "ig" ? ["var(--b-mn)"] : branches.map(b => b.hex),
      markers: { size: 0, hover: { size: 5 } },
      grid: { borderColor: "var(--grid-line-strong)", strokeDashArray: 3, padding: { left: 10, right: 10, top: 0, bottom: 0 } },
      xaxis: {
        type: "datetime",
        labels: { style: { colors: "var(--fg3)", fontSize: "10px", fontFamily: "JetBrains Mono" }, datetimeFormatter: { month: "MMM dd" } },
        axisBorder: { show: false }, axisTicks: { show: false },
      },
      yaxis: {
        labels: { style: { colors: "var(--fg3)", fontSize: "10px", fontFamily: "JetBrains Mono" }, formatter: v => v == null ? "" : Math.round(v).toLocaleString() },
      },
      legend: { show: false },
      tooltip: { theme, x: { format: "dd MMM yyyy" }, y: { formatter: v => v == null ? "—" : v.toLocaleString() } },
      dataLabels: { enabled: false },
    };
    chartRef.current = new ApexCharts(ref.current, opts);
    chartRef.current.render();
    return () => chartRef.current && chartRef.current.destroy();
  }, [sourceKey, branches.map(b=>b.id).join(","), theme, windowSize]);

  return (
    <div className="panel">
      <div className="panel-head">
        <div>
          <div className="eyebrow">{eyebrow}</div>
          <h3>{title}</h3>
        </div>
        <div className="legend">
          {(sourceKey === "ig" ? [{ id: "ig", code: "IG", hex: "#6A8E3E" }] : branches).map(b => (
            <span key={b.id} className="sw"><span className="c" style={{ background: b.hex }}></span>{b.code}</span>
          ))}
        </div>
      </div>
      <div ref={ref} style={{ minHeight: height }} />
      {foot && <div className="hint" style={{ marginTop: 8 }}>{foot}</div>}
    </div>
  );
}

// ---- Target attainment panel -------------------------------------------
function TargetAttainment({ branches }) {
  const rows = branches.map(b => {
    const tgt = (D.targets || []).filter(t => t.kpi === "fb_followers" && t.branch === b.id);
    tgt.sort((a, c) => a.value - c.value);
    const primary = tgt[0];
    const stretch = tgt[1];
    const value = (D.fb[b.id] || []).slice(-1)[0] || 0;
    return { b, value, target: primary ? primary.value : null, target2: stretch ? stretch.value : null };
  }).filter(r => r.target != null);

  if (!rows.length) {
    return (
      <div className="panel">
        <div className="panel-head">
          <div>
            <div className="eyebrow">Target attainment</div>
            <h3>Facebook follower targets</h3>
            <div className="meta">No FB targets set yet.</div>
          </div>
          <a href={URLS.targets} className="btn ghost sm">Set targets →</a>
        </div>
      </div>
    );
  }

  return (
    <div className="panel">
      <div className="panel-head">
        <div>
          <div className="eyebrow">Target attainment</div>
          <h3>Facebook follower targets</h3>
          <div className="meta">Primary + stretch · progress to due date</div>
        </div>
        <a href={URLS.targets} className="btn ghost sm">Manage →</a>
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
        {rows.map((r, i) => (
          <Bullet key={i}
            label={<span><BranchChip branch={r.b} /> <span style={{ marginLeft: 6, fontFamily: "var(--font-body)", fontWeight: 600 }}>{r.b.name}</span></span>}
            value={r.value} target={r.target} target2={r.target2} color={r.b.hex}
            onClick={() => r.b.slug && (location.href = URLS.branch + r.b.slug)} />
        ))}
      </div>
    </div>
  );
}

// ---- Ranking bars -------------------------------------------------------
function Ranking({ title, eyebrow, sourceKey, format = v => v.toLocaleString(), branches }) {
  const data = branches.map(b => ({
    b,
    value: sourceKey === "gr"
      ? (D.gr[b.id] ? D.gr[b.id].total : 0)
      : ((D[sourceKey] && D[sourceKey][b.id]) ? D[sourceKey][b.id].slice(-1)[0] || 0 : 0),
  })).sort((a, b) => b.value - a.value);
  const max = Math.max(1, ...data.map(d => d.value));
  return (
    <div className="panel">
      <div className="panel-head">
        <div>
          <div className="eyebrow">{eyebrow}</div>
          <h3>{title}</h3>
        </div>
      </div>
      {data.map(d => (
        <div className="rank-row" key={d.b.id} style={{ cursor: "pointer" }}
             onClick={() => d.b.slug && (location.href = URLS.branch + d.b.slug)}>
          <BranchChip branch={d.b} />
          <div className="track">
            <div className="fill" style={{ width: (d.value / max * 100) + "%", background: `linear-gradient(90deg, ${d.b.hex}CC, ${d.b.hex})` }} />
            <div className="lab" style={{ color: d.value / max > 0.35 ? "white" : "var(--fg1)", textShadow: d.value / max > 0.35 ? "0 1px 1px rgba(0,0,0,0.2)" : "none" }}>
              {d.b.name}
            </div>
          </div>
          <div className="val">{format(d.value)}</div>
        </div>
      ))}
    </div>
  );
}

// ---- Google reviews stacked ---------------------------------------------
function ReviewBreakdown({ branches }) {
  const entries = branches.map(b => ({ b, g: D.gr[b.id] })).filter(x => x.g);
  const maxTotal = Math.max(1, ...entries.map(x => x.g.total));
  return (
    <div className="panel">
      <div className="panel-head">
        <div>
          <div className="eyebrow">Google Reviews</div>
          <h3>Star distribution by branch</h3>
          <div className="meta">Stacked 5★ → 1★ · width proportional to review count</div>
        </div>
        <div className="legend">
          <span className="sw"><span className="c" style={{ background: "#2E8B63" }}></span>5★</span>
          <span className="sw"><span className="c" style={{ background: "#6AB07A" }}></span>4★</span>
          <span className="sw"><span className="c" style={{ background: "#D9C14A" }}></span>3★</span>
          <span className="sw"><span className="c" style={{ background: "#D98B3A" }}></span>2★</span>
          <span className="sw"><span className="c" style={{ background: "#C44040" }}></span>1★</span>
        </div>
      </div>
      {entries.map(({ b, g }) => {
        const width = (g.total / maxTotal * 100);
        return (
          <div className="stack-row" key={b.id} style={{ cursor: "pointer" }}
               onClick={() => b.slug && (location.href = URLS.branch + b.slug)}>
            <BranchChip branch={b} />
            <div className="stack" style={{ width: width + "%" }}>
              {[5,4,3,2,1].map(s => {
                const n = g.stars ? (g.stars[s] || 0) : 0;
                const pct = g.total ? (n / g.total) * 100 : 0;
                return <span key={s} className={"star-" + s} style={{ width: pct + "%" }} data-tip={`${s}★ · ${n}`} />;
              })}
            </div>
            <div className="rating">
              {g.rating != null ? g.rating.toFixed(1) : "—"}★
              <small>{(g.total || 0).toLocaleString()} reviews</small>
            </div>
          </div>
        );
      })}
    </div>
  );
}

// ---- Posting heatmap ----------------------------------------------------
function PostingHeatmap({ branches, mode }) {
  const labs14 = D.postingWeeks || [];
  const [tab, setTab] = useState("fb");
  const channelRows = (D.posting && D.posting[tab]) || [];

  // Branch filter: when in single-branch mode, keep only rows whose label prefix matches the branch code
  let rows = channelRows;
  if (mode === "branch" && branches.length === 1) {
    const code = branches[0].code;
    rows = channelRows.filter(r => r.label.split("·")[0] === code);
  } else if (mode === "hq") {
    // HQ: show DR·TT row in TT tab, HQ·TH row in TH tab; FB tab effectively empty
    if (tab === "fb") rows = [];
    else if (tab === "tt") rows = channelRows.filter(r => r.label.startsWith("DR"));
    else if (tab === "th") rows = channelRows; // single HQ·TH row
  }

  return (
    <div className="panel">
      <div className="panel-head">
        <div>
          <div className="eyebrow">Posting consistency</div>
          <h3>Weekly posts · 14-week heatmap</h3>
          <div className="meta">0 posts → 5+ posts per week · gaps flagged in alerts</div>
        </div>
        <div className="heatmap-tabs">
          {["fb", "tt", "th"].map(t => (
            <button key={t} className={tab === t ? "active" : ""} onClick={() => setTab(t)}>
              {t.toUpperCase()}
            </button>
          ))}
        </div>
      </div>
      <div className="legend-scale" style={{ marginBottom: 8 }}>
        <span style={{ marginRight: 4 }}>Less</span>
        {[0,1,2,3,4,5].map(v => (
          <span key={v} className="step" style={{ background: v===0 ? "var(--panel-sunken)" : ["#F5D3BC","#ECA890","#E17A7E","#C21658","#A8124C"][v-1] }}></span>
        ))}
        <span style={{ marginLeft: 4 }}>More</span>
      </div>
      {rows.length === 0 ? (
        <div className="hint" style={{ padding: "12px 0" }}>No data for this filter</div>
      ) : (
        <>
          <div className="heat-head">
            <span></span>
            {labs14.map(l => <span key={l}>{l}</span>)}
            <span>Σ</span>
          </div>
          <div className="heatmap">
            {rows.map(row => (
              <div className="heat-row" key={row.label}>
                <div className="h-lbl">{row.label}</div>
                {row.values.map((v, i) => (
                  <div key={i} className="heat-cell" data-v={Math.min(5, v)} data-tip={`${row.label} · week of ${labs14[i]} · ${v} posts`}/>
                ))}
                <div className="h-sum">{row.values.reduce((a,b)=>a+b,0)}</div>
              </div>
            ))}
          </div>
        </>
      )}
    </div>
  );
}

// ---- Alerts side-rail ---------------------------------------------------
function AlertsRail() {
  const [dismissed, setDismissed] = useState(() => new Set());
  const allAlerts = D.alerts || [];
  const visibleAlerts = allAlerts.filter(a => !dismissed.has(`${a.group}::${a.text}::${a.sub}`));

  const groups = {};
  visibleAlerts.forEach(a => { (groups[a.group] = groups[a.group] || []).push(a); });

  const tickChar = { bad: "!", warn: "▲", info: "i" };

  const onClickAlert = (a) => {
    if (a.branch) {
      location.href = URLS.branch + a.branch;
    } else {
      location.href = URLS.entry;
    }
  };

  const dismiss = (a, e) => {
    e.stopPropagation();
    const key = `${a.group}::${a.text}::${a.sub}`;
    setDismissed(prev => {
      const next = new Set(prev);
      next.add(key);
      return next;
    });
  };

  return (
    <aside className="alerts">
      <h3>Alerts <span className="count">{visibleAlerts.length}</span></h3>
      <div className="alerts-sub">Week of {D.weekLabel} · updated just now</div>
      {visibleAlerts.length === 0 ? (
        <div className="alert-empty">
          <div className="alert-empty-tick">✓</div>
          <div className="alert-empty-msg">All clear</div>
          <div className="alert-empty-sub">No active alerts this week</div>
        </div>
      ) : (
        Object.entries(groups).map(([g, items]) => (
          <div className="alert-group" key={g}>
            <div className="alert-group-head">
              <span>{g}</span>
              <span>{items.length}</span>
            </div>
            {items.map((a, i) => (
              <div className={"alert " + a.sev} key={i} onClick={() => onClickAlert(a)}>
                <div className="tick">{tickChar[a.sev]}</div>
                <div className="txt">
                  {a.text}
                  <small>{a.sub}</small>
                </div>
                <button className="dismiss" onClick={(e) => dismiss(a, e)} title="Dismiss this alert">✕</button>
              </div>
            ))}
          </div>
        ))
      )}
      <a className="btn ghost sm" style={{ width: "100%", justifyContent: "center", marginTop: 8 }} href={URLS.entry}>Enter data →</a>
    </aside>
  );
}

// ---- Snapshot strip (compact ticker) -----------------------------------
function SnapshotStrip({ branches, windowSize }) {
  const last = D.weeks.length - 1;
  const start = Math.max(0, last - windowSize + 1);
  const baselineAt = (series) => {
    for (let i = start; i <= last; i++) {
      if (series[i] != null) return series[i];
    }
    return null;
  };
  const cells = branches.map(b => {
    const fbSeries = D.fb[b.id] || [];
    const waSeries = D.wa[b.id] || [];
    const ttSeries = D.tt[b.id] || [];
    const fb = fbSeries[last] || 0;
    const wa = waSeries[last] || 0;
    const tt = ttSeries[last] || 0;
    const gr = (D.gr[b.id] && D.gr[b.id].total) || 0;
    const rating = (D.gr[b.id] && D.gr[b.id].rating) || null;
    const fbBase = baselineAt(fbSeries);
    const waBase = baselineAt(waSeries);
    const ttBase = baselineAt(ttSeries);
    return {
      b, fb, wa, tt, gr, rating,
      fbDelta: fbBase != null ? fb - fbBase : 0,
      waDelta: waBase != null ? wa - waBase : 0,
      ttDelta: ttBase != null ? tt - ttBase : 0,
    };
  });
  return (
    <div className="panel pad-sm" style={{ padding: "12px 14px" }}>
      <div style={{ display: "grid", gridTemplateColumns: `110px repeat(${cells.length}, 1fr)`, gap: 0, alignItems: "stretch" }}>
        <div style={{ borderRight: "1px solid var(--border-subtle)", paddingRight: 10 }}>
          <div className="eyebrow" style={{ marginBottom: 6 }}>Snapshot</div>
          <div className="hint" style={{ fontSize: 10, lineHeight: 1.35 }}>Week ending<br/><b style={{ color: "var(--fg1)", fontFamily: "var(--font-mono)" }}>{D.weekLabel}</b></div>
        </div>
        {cells.map((c, i) => (
          <div key={c.b.id} style={{ padding: "2px 12px", borderRight: i < cells.length - 1 ? "1px solid var(--border-subtle)" : "none", cursor: "pointer" }}
               onClick={() => c.b.slug && (location.href = URLS.branch + c.b.slug)}>
            <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 6 }}>
              <BranchChip branch={c.b} />
              <span style={{ fontSize: 11, fontWeight: 600, color: "var(--fg2)" }}>{c.b.name}</span>
              {c.b.isNew && <StatusPill kind="new">NEW</StatusPill>}
            </div>
            {[
              { k: "FB", v: c.fb, d: c.fbDelta },
              { k: "WA", v: c.wa, d: c.waDelta },
              { k: "TT", v: c.tt, d: c.ttDelta },
            ].map(row => (
              <div key={row.k} style={{ display: "grid", gridTemplateColumns: "32px 1fr auto", gap: 6, alignItems: "center", fontSize: 11, marginBottom: 2 }}>
                <span className="hint" style={{ fontFamily: "var(--font-mono)" }}>{row.k}</span>
                <span className="num" style={{ fontWeight: 600 }}>{row.v.toLocaleString()}</span>
                <Delta value={row.d} />
              </div>
            ))}
            <div style={{ display: "grid", gridTemplateColumns: "32px 1fr auto", gap: 6, alignItems: "center", fontSize: 11 }}>
              <span className="hint" style={{ fontFamily: "var(--font-mono)" }}>GR</span>
              <span className="num" style={{ fontWeight: 600 }}>{c.gr.toLocaleString()}</span>
              {c.rating != null && (
                <span className="pill ok" style={{ padding: "1px 5px", fontSize: 10 }}><span className="d"></span>{c.rating.toFixed(1)}★</span>
              )}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ---- HQ panels ----------------------------------------------------------
function HqKpiSummary({ windowSize }) {
  const last = D.weeks.length - 1;
  const start = Math.max(0, last - windowSize + 1);
  const igSeries = D.ig.total || [];
  const drSeries = (D.tt && D.tt.doctor) || [];
  const thFollowersSeries = D.thFollowers || [];
  const thViewsSeries = D.thViews || [];

  function windowBaseline(series) {
    for (let i = start; i <= last; i++) if (series[i] != null) return { value: series[i], idx: i };
    return { value: null, idx: null };
  }

  const cards = [
    { key: "ig",  label: "IG FOLLOWERS",       swatch: "var(--b-mn)", series: igSeries,          color: "var(--b-mn)" },
    { key: "dr",  label: "DOCTOR TIKTOK",      swatch: "var(--b-bs)", series: drSeries,          color: "var(--b-bs)" },
    { key: "thf", label: "THREADS · FOLLOWERS", swatch: "#1f2933",     series: thFollowersSeries, color: "#1f2933" },
    { key: "thv", label: "THREADS · VIEWS",     swatch: "#1f2933",     series: thViewsSeries,     color: "#1f2933", isSum: true },
  ];

  return (
    <div className="row c-4" style={{ marginBottom: 12 }}>
      {cards.map(c => {
        const value = c.isSum
          ? c.series.slice(start).reduce((a, b) => a + (b || 0), 0)
          : (c.series[last] || 0);
        const baseline = windowBaseline(c.series);
        let d = null, pct = null;
        if (c.isSum) {
          const prevWindow = c.series.slice(Math.max(0, start - windowSize), start).reduce((a, b) => a + (b || 0), 0);
          d = value - prevWindow;
          pct = prevWindow ? +((d / prevWindow) * 100).toFixed(2) : null;
        } else if (baseline.value != null) {
          d = value - baseline.value;
          pct = baseline.value ? +((d / baseline.value) * 100).toFixed(2) : null;
        }
        return (
          <div className="kpi-card" key={c.key}>
            <div>
              <div className="kpi-label"><span className="swatch" style={{ background: c.swatch }}></span>{c.label}</div>
              <div className="kpi-value">{value.toLocaleString()}</div>
            </div>
            <div className="kpi-foot">
              <div className="spark"><Sparkline data={c.series.slice(start)} color={c.color} /></div>
              {d == null ? <span className="delta flat">—</span> : <Delta value={d} pct={pct} />}
            </div>
          </div>
        );
      })}
    </div>
  );
}


function HqTargets() {
  const hqTargets = (D.targets || []).filter(t =>
    (t.kpi === "tiktok" && t.account === "doctor") || t.kpi === "ig"
  );
  if (hqTargets.length === 0) {
    return (
      <div className="panel">
        <div className="panel-head">
          <div>
            <div className="eyebrow">HQ targets</div>
            <h3>IG · Doctor TT</h3>
            <div className="meta">No HQ targets set yet.</div>
          </div>
          <a href={URLS.targets} className="btn ghost sm">Set targets →</a>
        </div>
      </div>
    );
  }
  return (
    <div className="panel">
      <div className="panel-head">
        <div>
          <div className="eyebrow">HQ targets</div>
          <h3>IG · Doctor TT</h3>
          <div className="meta">Active HQ targets</div>
        </div>
        <a href={URLS.targets} className="btn ghost sm">Manage →</a>
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
        {hqTargets.map((t, i) => {
          let value = 0;
          let label = "";
          if (t.kpi === "tiktok") {
            value = ((D.tt && D.tt.doctor) || []).slice(-1)[0] || 0;
            label = "Doctor TikTok followers";
          } else if (t.kpi === "ig") {
            value = (D.ig.total || []).slice(-1)[0] || 0;
            label = "Instagram followers";
          }
          return (
            <Bullet key={i} label={label} value={value} target={t.value} color="#1f2933" />
          );
        })}
      </div>
    </div>
  );
}


function HqRecentPosts() {
  const items = [];
  (D.th || []).forEach(p => items.push({ type: "TH", date: p.date, label: p.topic, extra: p.views != null ? `${p.views} views` : "" }));
  (D.doctorRecent || []).forEach(p => items.push({ type: "TT", date: p.date, label: p.title, extra: "" }));
  items.sort((a, b) => (a.date < b.date ? 1 : -1));
  const top = items.slice(0, 10);

  return (
    <div className="panel">
      <div className="panel-head">
        <div>
          <div className="eyebrow">HQ posts</div>
          <h3>Recent activity</h3>
          <div className="meta">Last 10 posts across Threads + Doctor TikTok</div>
        </div>
      </div>
      {top.length === 0 ? (
        <div className="hint" style={{ padding: 12 }}>No recent posts logged.</div>
      ) : (
        <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
          {top.map((p, i) => (
            <div key={i} className="hq-post-row">
              <span className={"chip " + (p.type === "TH" ? "chip-th" : "chip-tt")}>{p.type}</span>
              <div className="hq-post-meta">
                <div className="hq-post-label">{p.label}</div>
                <small>{p.date}{p.extra ? " · " + p.extra : ""}</small>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}


function HqGrowthRanking({ windowSize }) {
  const last = D.weeks.length - 1;
  const start = Math.max(0, last - windowSize + 1);

  function windowBaseline(series) {
    for (let i = start; i <= last; i++) if (series[i] != null) return series[i];
    return null;
  }

  const ig = D.ig.total || [];
  const dr = (D.tt && D.tt.doctor) || [];
  const th = D.thViews || [];

  const igCur = ig[last] || 0, igBase = windowBaseline(ig);
  const drCur = dr[last] || 0, drBase = windowBaseline(dr);
  const thWindow = th.slice(start).reduce((a, b) => a + (b || 0), 0);
  const thPrior = th.slice(Math.max(0, start - windowSize), start).reduce((a, b) => a + (b || 0), 0);

  const rows = [
    { label: "Instagram",    delta: igBase != null ? igCur - igBase : 0, hex: "var(--b-mn)" },
    { label: "Doctor TT",    delta: drBase != null ? drCur - drBase : 0, hex: "var(--b-bs)" },
    { label: "Threads views", delta: thWindow - thPrior, hex: "#1f2933" },
  ].sort((a, b) => b.delta - a.delta);

  const max = Math.max(1, ...rows.map(r => Math.abs(r.delta)));

  return (
    <div className="panel">
      <div className="panel-head">
        <div>
          <div className="eyebrow">HQ growth</div>
          <h3>By channel · this window</h3>
        </div>
      </div>
      {rows.map(r => (
        <div className="rank-row" key={r.label}>
          <div style={{ width: 110, fontWeight: 600 }}>{r.label}</div>
          <div className="track">
            <div className="fill" style={{ width: (Math.abs(r.delta) / max * 100) + "%", background: r.hex }} />
          </div>
          <div className="val">{r.delta >= 0 ? "+" : ""}{r.delta.toLocaleString()}</div>
        </div>
      ))}
    </div>
  );
}


// ---- Dashboard assembly -------------------------------------------------
function Dashboard() {
  const [branchFilter, setBranchFilter] = useState("all");
  const [timeframe, setTimeframe] = useState("12w");

  const HQ_CHIP = { id: "hq", code: "HQ", name: "Headquarters", hex: "#1f2933", isHq: true };
  const FILTER_CHIPS = [
    { id: "all", code: "ALL", hex: "var(--fg2)" },
    HQ_CHIP,
    ...D.BRANCHES,
  ];
  const mode = branchFilter === "all" ? "all" : (branchFilter === "hq" ? "hq" : "branch");
  const activeBranch = mode === "branch" ? D.BRANCHES.find(b => b.id === branchFilter) : null;

  const N = { "4w": 4, "12w": 12, "YTD": 52 }[timeframe] || 12;
  const visible = mode === "all"
    ? D.BRANCHES
    : mode === "hq"
      ? (D.HQ_ACCOUNTS || [])
      : D.BRANCHES.filter(b => b.id === branchFilter);
  const branchScope = mode === "branch" ? [activeBranch] : D.BRANCHES;

  const totals = {
    fb: D.BRANCHES.reduce((a, b) => a + ((D.fb[b.id] || []).slice(-1)[0] || 0), 0),
    wa: D.BRANCHES.reduce((a, b) => a + ((D.wa[b.id] || []).slice(-1)[0] || 0), 0),
    tt: Object.values(D.tt).reduce((a, arr) => a + ((arr || []).slice(-1)[0] || 0), 0),
    gr: Object.values(D.gr).reduce((a, g) => a + (g.total || 0), 0),
  };

  return (
    <div className="page" data-screen-label="01 Dashboard">
      <div className="page-head">
        <div className="title-block">
          <h1>Group Dashboard</h1>
          <div className="sub">
            {mode === "all" && <>{D.BRANCHES.length} branches · </>}
            {mode === "branch" && <><b>{activeBranch.name}</b> · </>}
            {mode === "hq" && <><b>IG · Doctor TT · Threads</b> · </>}
            <b>{N === 52 ? "52-week" : timeframe} view</b> ending <b>{D.weekLabel}</b>
            <span style={{ margin: "0 8px", opacity: 0.4 }}>·</span>
            {totals.fb.toLocaleString()} FB · {totals.wa.toLocaleString()} WA · {totals.tt.toLocaleString()} TikTok · {totals.gr.toLocaleString()} Google Reviews
          </div>
        </div>
        <div style={{ display: "flex", gap: 10, alignItems: "center", flexWrap: "wrap" }}>
          <div className="branch-chips">
            {FILTER_CHIPS.map(c => (
              <button
                key={c.id}
                className={branchFilter === c.id ? "active" : ""}
                onClick={() => setBranchFilter(c.id)}
              >
                {c.id !== "all" && (
                  <span className="dot" style={{ background: c.hex }}></span>
                )}
                {c.code}
              </button>
            ))}
          </div>
          <div className="segmented">
            {["4w", "12w", "YTD"].map(t => (
              <button key={t} className={timeframe===t?"active":""} onClick={()=>setTimeframe(t)}>{t}</button>
            ))}
          </div>
        </div>
      </div>

      <div className="grid-main">
        <div style={{ minWidth: 0 }}>
          {mode === "hq" ? (
            <>
              <HqKpiSummary windowSize={N} />
              <div style={{ height: 12 }}></div>
              <div className="row c-2">
                <LineChart id="ig" title="Instagram followers" eyebrow={`Growth · ${N === 52 ? "52" : N}w`} sourceKey="ig" branches={[]} windowSize={N} />
                <LineChart id="tt-dr" title="Doctor TikTok followers" eyebrow={`Growth · ${N === 52 ? "52" : N}w`} sourceKey="tt" branches={[{id: "doctor", code: "DR", hex: "#1f2933", slug: null}]} windowSize={N} />
              </div>
              <div className="row c-2">
                <HqTargets />
                <HqRecentPosts />
              </div>
              <div className="row">
                <HqGrowthRanking windowSize={N} />
              </div>
              <div className="row">
                <PostingHeatmap branches={D.HQ_ACCOUNTS || []} mode={mode} />
              </div>
            </>
          ) : (
            <>
              <KpiSummary mode={mode} branches={branchScope} windowSize={N} />
              <SnapshotStrip branches={branchScope} windowSize={N} />
              <div style={{ height: 12 }}></div>
              <div className="row c-2">
                <LineChart id="fb" title="Facebook followers" eyebrow={`Growth · ${N === 52 ? "52" : N}w`} sourceKey="fb" branches={visible} windowSize={N} />
                <LineChart id="wa" title="WhatsApp members" eyebrow={`Growth · ${N === 52 ? "52" : N}w`} sourceKey="wa" branches={visible} windowSize={N} />
              </div>
              <div className="row c-2">
                <LineChart id="tt" title="TikTok followers" eyebrow={`Growth · ${N === 52 ? "52" : N}w`} sourceKey="tt" branches={visible} windowSize={N} foot={D.tiktokFoot} />
                <TargetAttainment branches={branchScope} />
              </div>
              <div className="row c-2">
                <Ranking title="FB followers by branch" eyebrow="Ranking · this week" sourceKey="fb" branches={branchScope} />
                <Ranking title="Google Reviews by branch" eyebrow="Ranking · latest" sourceKey="gr" branches={branchScope} />
              </div>
              <div className="row">
                <ReviewBreakdown branches={branchScope} />
              </div>
              <div className="row">
                <PostingHeatmap branches={branchScope} mode={mode} />
              </div>
            </>
          )}
        </div>
        <AlertsRail />
      </div>
    </div>
  );
}

Object.assign(window, { Dashboard });
