// ダッシュボード画面
function ScreenDashboard({ data, onNavigate }) {
  const branchChartData = data.branches.map(b => ({
    label: b.short, value: data.branchVehicleCount[b.id] || 0,
  })).sort((a, b) => b.value - a.value);

  const expiringSoon = [...data.gasCards, ...data.etcCards]
    .filter(c => c.status === "期限間近")
    .slice(0, 5);

  const unlinked = data.vehicles.filter(v => v.status === "未紐付");

  const expenseTrend = data.expenseMonths.map(m => ({
    label: m.ym.slice(5) + "月",
    values: { gas: m.gas, etc: m.etc },
  }));

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      {/* KPI */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 12 }}>
        <KpiCard label="総車両数" value={fmtN(data.totals.vehicles)} unit="台" sub="登録車両 / 全拠店" />
        <KpiCard label="総ドライバー数" value={fmtN(data.totals.drivers)} unit="名" sub="社員番号付与済み" />
        <KpiCard label="総カード数" value={fmtN(data.totals.cards)} unit="枚" sub="ガソリン243 / ETC165" />
        <KpiCard label="期限間近のカード" value={fmtN(data.totals.expiringSoon)} unit="枚" sub="30日以内に期限切れ" delta="要確認" deltaKind="warn" />
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 16 }}>
        {/* 拠店別車両数 */}
        <SectionCard title="拠店別 車両数" action={
          <Button variant="ghost" onClick={() => onNavigate("vehicles")}>
            すべて表示 <Icon.chevron />
          </Button>
        }>
          <div style={{ columns: 2, columnGap: 28 }}>
            <BarChart
              data={branchChartData}
              format={(v) => `${v}台`}
            />
          </div>
        </SectionCard>

        {/* 経費トレンド (Phase 2 モック) */}
        <SectionCard title="月別経費トレンド" action={
          <Chip kind="muted">Phase 2 モック</Chip>
        }>
          <ColumnChart
            data={expenseTrend}
            stacks={[
              { key: "gas", label: "ガソリン", color: "#2563EB" },
              { key: "etc", label: "ETC", color: "#7CA8F1" },
            ]}
            height={140}
            formatY={(v) => `${(v / 10000).toFixed(0)}万`}
          />
        </SectionCard>
      </div>

      {/* 警告とアラート */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
        <SectionCard title="期限が近いカード (30日以内)" action={
          <Button variant="ghost" onClick={() => onNavigate("cards")}>
            カード一覧へ <Icon.chevron />
          </Button>
        } padding={false}>
          <DataTable
            columns={[
              { title: "種別", key: "kind", width: 110 },
              { title: "カード番号", render: r => <span style={{ fontFamily: "var(--font-num)" }}>{r.no}</span> },
              { title: "使用者", key: "user" },
              { title: "有効期限", numeric: true, align: "right", render: r => r.expiry },
            ]}
            rows={expiringSoon}
            denseRow={36}
          />
        </SectionCard>

        <SectionCard title="未紐付の警告" action={<Chip kind="warn"><Icon.warn /> {unlinked.length}件</Chip>} padding={false}>
          <div style={{ display: "flex", flexDirection: "column" }}>
            {unlinked.slice(0, 5).map((v, i) => (
              <div key={i}
                onClick={() => onNavigate("vehicle-detail", v.reg)}
                style={{
                  display: "flex", alignItems: "center", justifyContent: "space-between",
                  padding: "11px 18px", borderBottom: "1px solid var(--border-soft)",
                  cursor: "pointer",
                }}
                onMouseEnter={e => e.currentTarget.style.background = "#FBFCFE"}
                onMouseLeave={e => e.currentTarget.style.background = "transparent"}>
                <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
                  <span style={{ fontSize: 13, fontWeight: 600, color: "var(--ink-1)", fontFamily: "var(--font-num)" }}>{v.reg}</span>
                  <span style={{ fontSize: 11, color: "var(--ink-3)" }}>
                    {v.model} · {data.branches.find(b => b.id === v.branch)?.name}
                  </span>
                </div>
                <div style={{ display: "flex", gap: 6, alignItems: "center" }}>
                  {!v.driver && <Chip kind="warn">担当者未割当</Chip>}
                  {!v.gas && <Chip kind="warn">G未紐付</Chip>}
                  {!v.etc && <Chip kind="warn">E未紐付</Chip>}
                  <Icon.chevron />
                </div>
              </div>
            ))}
          </div>
        </SectionCard>
      </div>

      {/* 補足: クイックアクション */}
      <SectionCard title="クイックアクション">
        <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
          <Button variant="primary" icon={<Icon.plus />}>新規車両を登録</Button>
          <Button icon={<Icon.user />}>ドライバーを登録</Button>
          <Button icon={<Icon.card />}>カードを追加</Button>
          <Button icon={<Icon.upload />} onClick={() => onNavigate("import")}>マスター取込</Button>
          <Button variant="ghost" icon={<Icon.download />}>月次レポートCSV</Button>
        </div>
      </SectionCard>
    </div>
  );
}

window.ScreenDashboard = ScreenDashboard;
