// Dashboard Overview page
const { Card: DCard, Pill: DPill, Btn: DBtn, Avatar: DAvatar, Topbar: DTopbar, ConcernIcon: DCon } = window.UI;

function Dashboard({ onGoTo, authAgent }) {
  // window.Mock is filled asynchronously by bootstrap — re-render when the
  // real (scoped) data lands, and again on realtime change events, so the
  // page never sits on 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(); };
  }, []);
  // Compute live counts from window.Mock (populated by bootstrap)
  const allConvs = window.Mock.conversations || [];
  const openCount = allConvs.filter(c => c.status !== "closed").length;
  const onlineAgents = (window.Mock.agents || []).filter(a => a.status === "online").length;
  const totalAgents = (window.Mock.agents || []).length;
  const siteCount = (window.Mock.websites || []).length;

  return (
    <div className="flex-1 flex flex-col h-full overflow-hidden">
      <DTopbar
        title={(() => {
          const h = new Date().getHours();
          const tod = h < 12 ? "morning" : h < 18 ? "afternoon" : "evening";
          // Greet by the signed-in user's first name, minus role prefixes like "CS"/"Admin"
          const first = ((authAgent && authAgent.name) || "").replace(/^(admin|cs)\s+/i, "").split(" ")[0];
          return `Good ${tod}${first ? ", " + first : ""} 👋`;
        })()}
        subtitle={`Here's what's happening across ${siteCount} site${siteCount !== 1 ? "s" : ""} today.`}
        right={<DBtn variant="primary" size="md" onClick={() => onGoTo("conversations")}><Icon.Plus size={14}/> New conversation</DBtn>}
      />
      <div className="flex-1 overflow-y-auto px-7 py-6 space-y-6">
        {/* Stat strip */}
        <div className="grid grid-cols-2 lg:grid-cols-5 gap-3">
          {window.Mock.overviewStats.map(s => {
            const I = Icon[s.icon];
            return (
              <DCard key={s.id} className="overflow-hidden relative">
                <div className="flex items-start justify-between">
                  <div className="text-[11px] uppercase tracking-[0.08em] text-white/45">{s.label}</div>
                  <span className="grid place-items-center w-7 h-7 rounded-lg" style={{ background: `${s.tint}22`, color: s.tint }}>
                    <I size={13} />
                  </span>
                </div>
                <div className="text-[30px] font-semibold tracking-tight text-white mt-3 leading-none">{s.value}</div>
                <div className={`text-[11.5px] mt-2 flex items-center gap-1 ${s.trend === "up" ? "text-lime" : s.trend === "down" ? "text-rose-300" : "text-white/50"}`}>
                  {s.trend === "up" && "↗"} {s.trend === "down" && "↘"} {s.delta}
                </div>
                {/* Sparkline */}
                <svg viewBox="0 0 120 28" className="absolute right-0 bottom-0 w-[120px] h-[28px] opacity-40">
                  <path d="M0 22 L20 18 L40 21 L60 14 L80 16 L100 8 L120 12" stroke={s.tint} strokeWidth="1.5" fill="none"/>
                </svg>
              </DCard>
            );
          })}
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-[1.4fr_1fr] gap-5">
          {/* Live conversations preview */}
          <DCard 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">Live conversations</div>
                <div className="text-[12px] text-white/45 mt-0.5">{openCount} open across your sites · sorted by waiting time</div>
              </div>
              <button onClick={() => onGoTo("conversations")} className="text-[12.5px] text-lime hover:underline flex items-center gap-1">
                Open inbox <Icon.ArrowRight size={12} />
              </button>
            </div>
            <div className="divide-y divide-white/[0.04]">
              {window.Mock.conversations.slice(0,5).map(c => {
                const site = window.Mock.websites.find(w => w.id === c.site);
                return (
                  <div key={c.id} className="flex items-center gap-3 px-5 py-3.5 hover:bg-white/[0.02] cursor-pointer" onClick={() => onGoTo("conversations")}>
                    <DAvatar name={c.visitor} color={c.color} size={36} status="online" />
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2">
                        <span className="text-[13px] font-medium text-white/95 truncate">{c.visitor}</span>
                        <span className="text-[11px] text-white/40">{c.username}</span>
                      </div>
                      <div className="text-[12px] text-white/55 truncate mt-0.5">{c.last}</div>
                    </div>
                    <div className="flex items-center gap-2 shrink-0">
                      <DCon id={c.concern} size={11} />
                      <DPill tone="default" className="!text-[10.5px]">
                        <span className="w-1.5 h-1.5 rounded-full" style={{ background: site.color }}/>
                        {site.name}
                      </DPill>
                      <span className="text-[11px] text-white/40 w-12 text-right tabular-nums">{c.minutes}m</span>
                      {c.status === "active" && <DPill tone="lime">active</DPill>}
                      {c.status === "waiting" && <DPill tone="yellow">waiting</DPill>}
                    </div>
                  </div>
                );
              })}
            </div>
          </DCard>

          {/* Sites status */}
          <div className="space-y-5">
            <DCard 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">Your websites</div>
                  <div className="text-[12px] text-white/45 mt-0.5">Status across {window.Mock.websites.length} brands</div>
                </div>
                <button onClick={() => onGoTo("websites")} className="text-[12.5px] text-white/55 hover:text-white">All →</button>
              </div>
              <div className="p-2.5">
                {window.Mock.websites.map(w => {
                  const siteConvs = allConvs.filter(c => c.site === w.id);
                  const siteActive = siteConvs.filter(c => c.status === "active").length;
                  const siteOpen = siteConvs.filter(c => c.status !== "closed").length;
                  return (
                  <div key={w.id} className="flex items-center gap-3 p-3 rounded-xl hover:bg-white/[0.03]">
                    <div className="w-9 h-9 rounded-xl grid place-items-center font-bold text-[10px] text-ink-950" style={{ background: w.color }}>{w.initials}</div>
                    <div className="flex-1">
                      <div className="text-[13px] font-medium text-white/95">{w.name}</div>
                      <div className="text-[11px] text-white/40 font-mono">{w.domain}</div>
                    </div>
                    <div className="text-right">
                      <div className="text-[12px] text-white/85 font-mono tabular-nums">{siteActive} <span className="text-white/40">/ {siteOpen}</span></div>
                      <div className="flex items-center gap-1 text-[10.5px] mt-0.5 justify-end">
                        <span className={`w-1.5 h-1.5 rounded-full ${w.online ? "bg-lime" : "bg-zinc-500"}`}/>
                        <span className={w.online ? "text-lime" : "text-white/40"}>{w.online ? "Online" : "Offline"}</span>
                      </div>
                    </div>
                  </div>
                  );
                })}
              </div>
            </DCard>

            {/* Agents quick view */}
            <DCard 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">Team online</div>
                  <div className="text-[12px] text-white/45 mt-0.5">{onlineAgents} of {totalAgents} agents online</div>
                </div>
                <button onClick={() => onGoTo("agents")} className="text-[12.5px] text-white/55 hover:text-white">All →</button>
              </div>
              <div className="p-2.5">
                {window.Mock.agents.slice(0,4).map(a => (
                  <div key={a.id} className="flex items-center gap-3 p-2.5 rounded-xl hover:bg-white/[0.03]">
                    <DAvatar name={a.name} color={a.color} size={32} status={a.status} />
                    <div className="flex-1 min-w-0">
                      <div className="text-[13px] font-medium text-white/95">{a.name}</div>
                      <div className="text-[11px] text-white/45">{a.role}</div>
                    </div>
                    <div className="text-[11.5px] text-white/55 font-mono tabular-nums">{a.chats} chats</div>
                  </div>
                ))}
              </div>
            </DCard>
          </div>
        </div>

        {/* Volume chart + concerns */}
        <div className="grid grid-cols-1 lg:grid-cols-[1.4fr_1fr] gap-5">
          <DCard 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 — last 14 days</div>
                <div className="text-[12px] text-white/45 mt-0.5">Stacked by website</div>
              </div>
              <div className="flex gap-1.5">
                {window.Mock.websites.map(w => (
                  <span key={w.id} className="flex items-center gap-1 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">
              <VolumeChart />
            </div>
          </DCard>

          <DCard padded={false}>
            <div className="p-5 border-b border-white/[0.05]">
              <div className="text-[14px] font-medium text-white/95">Top concerns this week</div>
              <div className="text-[12px] text-white/45 mt-0.5">Distribution across all sites</div>
            </div>
            <div className="p-5 space-y-3.5">
              {(() => {
                // Real distribution computed from this user's (already scoped) conversations
                const convs = window.Mock.conversations || [];
                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], value: Math.round(100 * counts[id] / (convs.length || 1)) }))
                  .sort((a, b) => b.count - a.count).slice(0, 5);
                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"><DCon id={c.id} size={11}/> {meta.label}</div>
                        <div className="text-[11.5px] text-white/55 font-mono tabular-nums">{c.count} · {c.value}%</div>
                      </div>
                      <div className="h-1.5 rounded-full bg-white/[0.05] overflow-hidden">
                        <div className="h-full rounded-full" style={{ width: (100 * c.count / top) + "%", background: meta.tint }}/>
                      </div>
                    </div>
                  );
                });
              })()}
            </div>
          </DCard>
        </div>
      </div>
    </div>
  );
}

function VolumeChart() {
  // Real 14-day histogram of conversation activity, stacked by website.
  // Uses each conversation's last-activity timestamp from the scoped bootstrap.
  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() - 13 * dayMs;
  const days = Array.from({ length: 14 }, (_, 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(),
      counts: 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 = days.map(d => d.counts.reduce((a, b) => a + b, 0) + d.other);
  const max = Math.max(1, ...totals);
  if (!convs.length) return <div className="h-[180px] grid place-items-center text-[12px] text-white/35">No conversations yet.</div>;
  return (
    <div className="h-[180px] flex items-end gap-1.5">
      {days.map((d, i) => {
        const total = 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: (total ? Math.max((total / max) * 100, 4) : 0) + "%" }}>
              {d.counts.map((n, j) => n > 0 ? <div key={j} style={{ height: (n / total) * 100 + "%", background: sites[j].color }}/> : null)}
              {d.other > 0 && <div style={{ height: (d.other / total) * 100 + "%", background: "#C7B6FF" }}/>}
            </div>
            <div className="text-[9.5px] text-white/35">{d.label}</div>
          </div>
        );
      })}
    </div>
  );
}

window.Dashboard = Dashboard;
