// カード一覧画面
function ScreenCards({ data, branchFilter }) {
  const [tab, setTab] = useState("gas");
  const [filterKind, setFilterKind] = useState("");
  const [filterStatus, setFilterStatus] = useState("");
  const [filterExpiry, setFilterExpiry] = useState("");

  const driverMap = useMemo(() => Object.fromEntries(data.drivers.map(d => [d.no, d])), [data.drivers]);

  const allCards = tab === "gas" ? data.gasCards : data.etcCards;
  const kindOptions = tab === "gas"
    ? ["宇佐美", "ENEOSウィング", "山分", "ORIX"]
    : ["NEXCO西日本", "三井住友"];

  const rows = allCards.filter(c => {
    if (filterKind && c.kind !== filterKind) return false;
    if (filterStatus && c.status !== filterStatus) return false;
    if (branchFilter) {
      const d = driverMap[c.empNo];
      if (d?.branch !== branchFilter) return false;
    }
    if (filterExpiry) {
      // モック: filterExpiry には "30" "90" "expired" のいずれか
      const daysTo = Math.round((new Date(c.expiry) - new Date("2026-05-20")) / 86400000);
      if (filterExpiry === "30" && daysTo > 30) return false;
      if (filterExpiry === "90" && daysTo > 90) return false;
      if (filterExpiry === "expired" && daysTo >= 0) return false;
    }
    return true;
  });

  const counts = {
    total: allCards.length,
    soon: allCards.filter(c => c.status === "期限間近").length,
    expired: allCards.filter(c => c.status === "期限切れ").length,
  };

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
      {/* タブ */}
      <div style={{
        background: "#fff", border: "1px solid var(--border)", borderRadius: 8,
        display: "flex", alignItems: "center", padding: "0 8px",
      }}>
        {[{ id: "gas", label: "ガソリンカード", count: data.gasCards.length },
          { id: "etc", label: "ETCカード", count: data.etcCards.length }].map(t => (
          <button key={t.id} onClick={() => { setTab(t.id); setFilterKind(""); }} style={{
            padding: "14px 18px", fontSize: 13, fontWeight: 600,
            background: "transparent", border: "none", cursor: "pointer",
            color: tab === t.id ? "var(--accent)" : "var(--ink-2)",
            borderBottom: tab === t.id ? "2px solid var(--accent)" : "2px solid transparent",
            marginBottom: -1, fontFamily: "inherit",
            display: "inline-flex", alignItems: "center", gap: 8,
          }}>
            {t.label}
            <span style={{
              fontSize: 11, color: tab === t.id ? "var(--accent)" : "var(--ink-3)",
              background: tab === t.id ? "#E5EEFC" : "var(--bg-soft)",
              padding: "2px 7px", borderRadius: 999, fontFamily: "var(--font-num)",
            }}>{t.count}</span>
          </button>
        ))}
        <div style={{ marginLeft: "auto", display: "flex", gap: 16, padding: "0 14px", fontSize: 12 }}>
          <span style={{ color: "var(--ink-3)" }}>有効 <span style={{ color: "var(--ink-1)", fontWeight: 600, fontFamily: "var(--font-num)" }}>{counts.total - counts.expired}</span></span>
          <span style={{ color: "var(--ink-3)" }}>期限間近 <span style={{ color: "#8A6100", fontWeight: 600, fontFamily: "var(--font-num)" }}>{counts.soon}</span></span>
          <span style={{ color: "var(--ink-3)" }}>期限切れ <span style={{ color: "#A41F1F", fontWeight: 600, fontFamily: "var(--font-num)" }}>{counts.expired}</span></span>
        </div>
      </div>

      {/* フィルタ */}
      <div style={{
        background: "#fff", border: "1px solid var(--border)", borderRadius: 8,
        padding: "12px 16px", display: "flex", flexWrap: "wrap", gap: 10, alignItems: "center",
      }}>
        <Select prefix="種別" value={filterKind} onChange={setFilterKind} placeholder="すべて"
          options={kindOptions.map(k => ({ value: k, label: k }))} />
        <Select prefix="状態" value={filterStatus} onChange={setFilterStatus} placeholder="すべて"
          options={[
            { value: "有効", label: "有効" }, { value: "期限間近", label: "期限間近" },
            { value: "期限切れ", label: "期限切れ" }, { value: "停止", label: "停止" },
          ]} />
        <Select prefix="期限" value={filterExpiry} onChange={setFilterExpiry} placeholder="すべて"
          options={[
            { value: "30", label: "30日以内" }, { value: "90", label: "90日以内" }, { value: "expired", label: "期限切れ" },
          ]} />
        <div style={{ marginLeft: "auto", display: "flex", gap: 8 }}>
          <span style={{ fontSize: 12, color: "var(--ink-3)", alignSelf: "center" }}>{fmtN(rows.length)} 件</span>
          <Button variant="danger">期限切れカードを一括停止</Button>
          <Button icon={<Icon.download />}>CSV</Button>
          <Button variant="primary" icon={<Icon.plus />}>新規カード</Button>
        </div>
      </div>

      {/* テーブル */}
      {tab === "gas" ? (
        <DataTable
          columns={[
            { title: "", render: () => <input type="checkbox" />, width: 30 },
            { title: "種別", render: r => <Chip kind="info">{r.kind}</Chip>, width: 130 },
            { title: "カード番号", render: r => <span style={{ fontFamily: "var(--font-num)", fontWeight: 600 }}>{r.no}</span>, minWidth: 180 },
            { title: "有効期限", render: r => (
              <span style={{
                fontFamily: "var(--font-num)",
                color: r.status === "期限切れ" ? "#A41F1F" : r.status === "期限間近" ? "#8A6100" : "var(--ink-1)",
                fontWeight: 600,
              }}>{r.expiry}</span>
            ), width: 110, numeric: true, align: "right" },
            { title: "使用者", key: "user", minWidth: 100 },
            { title: "社員番号", render: r => r.empNo, numeric: true, width: 80 },
            { title: "陸運局番号", render: r => <span style={{ fontFamily: "var(--font-num)" }}>{r.riku}</span>, width: 100 },
            { title: "車番", render: r => <span style={{ fontFamily: "var(--font-num)" }}>{r.vehicle}</span>, minWidth: 150 },
            { title: "ステータス", render: r => <StatusChip status={r.status} />, width: 100 },
          ]}
          rows={rows}
        />
      ) : (
        <DataTable
          columns={[
            { title: "", render: () => <input type="checkbox" />, width: 30 },
            { title: "種別", render: r => <Chip kind="info">{r.kind}</Chip>, width: 130 },
            { title: "カード番号", render: r => <span style={{ fontFamily: "var(--font-num)", fontWeight: 600 }}>{r.no}</span>, minWidth: 200 },
            { title: "有効期限", render: r => (
              <span style={{
                fontFamily: "var(--font-num)",
                color: r.status === "期限切れ" ? "#A41F1F" : r.status === "期限間近" ? "#8A6100" : "var(--ink-1)",
                fontWeight: 600,
              }}>{r.expiry}</span>
            ), width: 110, numeric: true, align: "right" },
            { title: "社員番号", render: r => r.empNo, numeric: true, width: 80 },
            { title: "使用者", key: "user", minWidth: 110 },
            { title: "車番", render: r => <span style={{ fontFamily: "var(--font-num)" }}>{r.vehicle}</span>, minWidth: 160 },
            { title: "ステータス", render: r => <StatusChip status={r.status} />, width: 100 },
          ]}
          rows={rows}
        />
      )}
    </div>
  );
}

window.ScreenCards = ScreenCards;
