// Dashboard view

function MetricCard({ label, value, unit, delta, spark, sparkColor }) {
  return (
    <div className="metric">
      <div className="metric-label">{label}</div>
      <div className="row" style={{ justifyContent: "space-between", alignItems: "flex-end" }}>
        <div className="metric-value">
          {value}{unit && <span className="unit">{unit}</span>}
        </div>
        {delta != null && (
          <span className={"metric-delta " + (delta >= 0 ? "up" : "down")}>
            {delta >= 0 ? "▲" : "▼"} {Math.abs(delta).toFixed(1)}%
          </span>
        )}
      </div>
      {spark && (
        <div className="metric-spark">
          <Sparkline data={spark} width={260} height={34} color={sparkColor || "var(--brand)"} />
        </div>
      )}
    </div>
  );
}

function Dashboard({ instances, onOpenInstance, onNav }) {
  const active = instances.filter(i => i.status === "active").length;
  const trial = instances.filter(i => i.status === "trial").length;
  const errored = instances.filter(i => i.status === "error").length;
  const totalTokens = instances.reduce((a, i) => a + i.tokensIn + i.tokensOut, 0);
  const totalCost = instances.reduce((a, i) => a + i.cost, 0);
  const totalMsgs = instances.reduce((a, i) => a + i.messages, 0);

  // Usage over time — synthesize 30 days
  const days = Array.from({ length: 30 }, (_, i) => i);
  const seriesIn = days.map((d) => 300_000 + Math.sin(d / 3) * 60_000 + Math.random() * 40_000 + d * 4_000);
  const seriesOut = days.map((d) => 80_000 + Math.cos(d / 4) * 18_000 + Math.random() * 12_000 + d * 1_400);
  const dayLabels = days.map((d) => {
    const dt = new Date(2026, 2, 22 + d);
    return `${dt.getDate()}.${dt.getMonth() + 1}`;
  });

  const recent = [...instances].sort((a, b) => b.createdAt.localeCompare(a.createdAt)).slice(0, 5);

  return (
    <div className="content full">
      <div className="page-head">
        <div>
          <h1 className="page-title">Dashboard</h1>
          <p className="page-sub">Agency overview · 12 active OpenClaw instances across your book</p>
        </div>
        <div className="row">
          <button className="btn"><Icon name="refresh" size={14}/> Refresh</button>
          <button className="btn primary" onClick={() => onNav("launch")}><Icon name="plus" size={14}/> Launch instance</button>
        </div>
      </div>

      <div className="grid-4 mb-22">
        <MetricCard
          label="Active instances"
          value={active}
          delta={8.3}
          spark={[8,9,9,10,10,11,10,11,12,12,11,12,12,12,12,12]}
        />
        <MetricCard
          label="Tokens this month"
          value={(totalTokens / 1_000_000).toFixed(2)}
          unit="M"
          delta={24.6}
          sparkColor="var(--violet)"
          spark={[22,28,30,26,35,42,38,45,48,52,56,61,58,64,70,72]}
        />
        <MetricCard
          label="Cost MTD"
          value={"€" + totalCost.toFixed(0)}
          delta={12.1}
          sparkColor="var(--amber)"
          spark={[40,55,70,82,95,110,120,142,160,180,205,230,258,290,325,358]}
        />
        <MetricCard
          label="Messages handled"
          value={fmtNum(totalMsgs)}
          delta={-2.4}
          sparkColor="var(--blue)"
          spark={[62,65,70,68,72,75,80,78,82,85,80,78,82,84,80,82]}
        />
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: 14, marginBottom: 22 }}>
        <div className="panel">
          <div className="panel-head">
            <h3>Token consumption</h3>
            <span className="sub">· last 30 days, all instances</span>
            <div className="right row gap-6">
              <span className="row gap-6" style={{ fontSize: 11, color: "var(--text-mute)" }}>
                <span style={{ width: 8, height: 8, borderRadius: 2, background: "var(--brand)" }}/> Input
              </span>
              <span className="row gap-6" style={{ fontSize: 11, color: "var(--text-mute)" }}>
                <span style={{ width: 8, height: 8, borderRadius: 2, background: "var(--violet)" }}/> Output
              </span>
            </div>
          </div>
          <div className="panel-body">
            <StackedArea seriesA={seriesIn} seriesB={seriesOut} labels={dayLabels} height={220}/>
          </div>
        </div>
        <div className="panel">
          <div className="panel-head">
            <h3>Instance health</h3>
          </div>
          <div className="panel-body col" style={{ gap: 14 }}>
            <HealthRow label="Active" count={active} total={instances.length} color="var(--brand)" />
            <HealthRow label="Trial" count={trial} total={instances.length} color="var(--amber)" />
            <HealthRow label="Provisioning" count={1} total={instances.length} color="var(--blue)" />
            <HealthRow label="Paused" count={instances.filter(i=>i.status==='paused').length} total={instances.length} color="var(--text-mute)" />
            <HealthRow label="Degraded" count={errored} total={instances.length} color="var(--rose)" />
            <HealthRow label="Archived" count={instances.filter(i=>i.status==='archived').length} total={instances.length} color="var(--text-mute)" />
            <div style={{ borderTop: "1px solid var(--border)", paddingTop: 12, marginTop: 4 }}>
              <div className="row" style={{ justifyContent: "space-between" }}>
                <span className="dim" style={{ fontSize: 12 }}>Uptime (agency avg, 30d)</span>
                <span className="mono" style={{ fontWeight: 600 }}>99.84%</span>
              </div>
              <div className="bar" style={{ marginTop: 6 }}><span style={{ width: "99.84%" }}/></div>
            </div>
          </div>
        </div>
      </div>

      <div className="panel mb-22">
        <div className="panel-head">
          <h3>Instances</h3>
          <span className="sub">· {instances.length} total</span>
          <div className="right row gap-6">
            <button className="btn sm"><Icon name="filter" size={13}/> Filter</button>
            <button className="btn sm"><Icon name="chevron-down" size={13}/> All statuses</button>
          </div>
        </div>
        <div className="panel-body">
          <div className="instance-grid">
            {instances.map((inst) => (
              <InstanceCard key={inst.id} inst={inst} onOpen={onOpenInstance} />
            ))}
          </div>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
        <div className="panel">
          <div className="panel-head"><h3>Recently launched</h3></div>
          <table className="table">
            <thead>
              <tr>
                <th>Instance</th>
                <th>Status</th>
                <th>Created</th>
                <th className="num">Cost MTD</th>
              </tr>
            </thead>
            <tbody>
              {recent.map((inst) => (
                <tr key={inst.id} style={{ cursor: "pointer" }} onClick={() => onOpenInstance(inst.id)}>
                  <td>
                    <div className="row gap-6">
                      <InstanceLogo inst={inst} size={22}/>
                      <div>
                        <div style={{ fontWeight: 500 }}>{inst.name}</div>
                        <div className="mono dim" style={{ fontSize: 11 }}>{inst.id}</div>
                      </div>
                    </div>
                  </td>
                  <td><StatusPill status={inst.status}/></td>
                  <td className="dim mono">{inst.createdAt}</td>
                  <td className="num">{fmtEur(inst.cost)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <div className="panel">
          <div className="panel-head"><h3>Needs attention</h3></div>
          <div className="panel-body col" style={{ gap: 10 }}>
            <AttnRow type="error" title="Nordflow Logistics" msg="Telegram webhook returned 502 · 14 min ago" cta="Investigate" onClick={()=>onOpenInstance('nordflow-logistics')}/>
            <AttnRow type="warn" title="Zentral Steuer" msg="Trial ends in 3 days · no billing method on file" cta="Convert" />
            <AttnRow type="warn" title="AlpinBau" msg="Anthropic key quota at 92% · consider rotating" cta="Manage keys" onClick={()=>onNav('keys')}/>
            <AttnRow type="info" title="Vinzenz Klinik" msg="Provisioning for 4 min · skills installing" cta="View" onClick={()=>onOpenInstance('vinzenz-klinik')}/>
          </div>
        </div>
      </div>
    </div>
  );
}

function HealthRow({ label, count, total, color }) {
  const pct = (count / total) * 100;
  return (
    <div>
      <div className="row" style={{ justifyContent: "space-between", fontSize: 12 }}>
        <span className="row gap-6"><span style={{ width: 8, height: 8, borderRadius: 2, background: color }}/> {label}</span>
        <span className="mono dim">{count}/{total}</span>
      </div>
      <div className="bar" style={{ marginTop: 6 }}><span style={{ width: `${pct}%`, background: color }}/></div>
    </div>
  );
}

function AttnRow({ type, title, msg, cta, onClick }) {
  const colorMap = { error: "var(--rose)", warn: "var(--amber)", info: "var(--blue)" };
  const iconMap = { error: "alert", warn: "alert", info: "clock" };
  return (
    <div className="row" style={{
      padding: "10px 12px",
      border: "1px solid var(--border)",
      borderRadius: 8,
      background: "var(--panel-2)",
      gap: 12,
    }}>
      <div style={{
        width: 28, height: 28, borderRadius: 7,
        background: `oklch(from ${colorMap[type]} l c h / 0.15)`,
        color: colorMap[type],
        display: "grid", placeItems: "center",
      }}>
        <Icon name={iconMap[type]} size={15}/>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontWeight: 500, fontSize: 12.5 }}>{title}</div>
        <div className="dim" style={{ fontSize: 11.5 }}>{msg}</div>
      </div>
      {cta && <button className="btn sm" onClick={onClick}>{cta}</button>}
    </div>
  );
}

window.Dashboard = Dashboard;
