// メインアプリ
const { useState: useStateApp, useEffect: useEffectApp } = React;

function App() {
  const data = window.APP_DATA;
  const [route, setRoute] = useStateApp({ screen: "dashboard", param: null });
  const [branchFilter, setBranchFilter] = useStateApp("");

  const navigate = (screen, param = null) => setRoute({ screen, param });

  const navItems = [
    { id: "dashboard", label: "ダッシュボード", icon: <Icon.dash /> },
    { id: "vehicles", label: "車両一覧", icon: <Icon.car />, count: data.totals.vehicles },
    { id: "drivers", label: "ドライバー", icon: <Icon.user />, count: data.totals.drivers },
    { id: "cards", label: "カード", icon: <Icon.card />, count: data.totals.cards },
    { id: "expenses", label: "経費（Phase 2）", icon: <Icon.coin />, badge: "β" },
    { id: "import", label: "マスター取込", icon: <Icon.upload /> },
    { id: "settings", label: "設定", icon: <Icon.settings /> },
  ];

  const screenTitle = {
    dashboard: { title: "ダッシュボード", sub: "車両・ドライバー・カードの全体サマリー" },
    vehicles: { title: "車両一覧", sub: `登録車両 ${fmtN(data.totals.vehicles)} 台` },
    "vehicle-detail": { title: "車両詳細", sub: route.param },
    drivers: { title: "ドライバー一覧", sub: `${fmtN(data.totals.drivers)} 名` },
    cards: { title: "カード一覧", sub: "ガソリン4系統 / ETC2系統" },
    expenses: { title: "経費ダッシュボード", sub: "月次経費の可視化（Phase 2）" },
    import: { title: "マスター取込", sub: "Excel 8ファイルを一括取込" },
    settings: { title: "設定 / ユーザー管理", sub: "利用者・権限の管理" },
  }[route.screen] || { title: "", sub: "" };

  // 現在のアクティブな上位ナビ
  const activeNav = route.screen === "vehicle-detail" ? "vehicles" : route.screen;

  return (
    <div style={{ display: "flex", height: "100vh", background: "var(--bg)" }}>
      {/* サイドバー */}
      <aside style={{
        width: 220, background: "#0F2A4A", color: "#C7D2E2",
        display: "flex", flexDirection: "column", flexShrink: 0,
      }}>
        <div style={{
          padding: "18px 18px 16px", borderBottom: "1px solid rgba(255,255,255,.08)",
          display: "flex", flexDirection: "column", gap: 4,
        }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <div style={{
              width: 28, height: 28, background: "#2563EB", borderRadius: 6,
              display: "flex", alignItems: "center", justifyContent: "center", color: "#fff",
            }}>
              <Icon.car />
            </div>
            <span style={{ color: "#fff", fontWeight: 700, fontSize: 13, letterSpacing: "0.02em" }}>JAP24 Fleet</span>
          </div>
          <span style={{ fontSize: 10.5, color: "#7E92AE", marginLeft: 36 }}>車両・カード管理</span>
        </div>

        <nav style={{ padding: "12px 8px", display: "flex", flexDirection: "column", gap: 2, flex: 1 }}>
          {navItems.map(item => {
            const active = activeNav === item.id;
            return (
              <button key={item.id} onClick={() => navigate(item.id)} style={{
                display: "flex", alignItems: "center", gap: 10,
                padding: "8px 10px", border: "none", borderRadius: 6,
                background: active ? "rgba(37, 99, 235, 0.2)" : "transparent",
                color: active ? "#fff" : "#C7D2E2",
                cursor: "pointer", fontSize: 12.5, fontWeight: active ? 600 : 500,
                fontFamily: "inherit", textAlign: "left",
                position: "relative",
              }}
              onMouseEnter={e => !active && (e.currentTarget.style.background = "rgba(255,255,255,.06)")}
              onMouseLeave={e => !active && (e.currentTarget.style.background = "transparent")}
              >
                {active && <span style={{ position: "absolute", left: -8, top: 6, bottom: 6, width: 3, background: "#2563EB", borderRadius: 3 }} />}
                <span style={{ color: active ? "#fff" : "#9BAEC6", display: "flex" }}>{item.icon}</span>
                <span style={{ flex: 1 }}>{item.label}</span>
                {item.count != null && (
                  <span style={{ fontSize: 10.5, color: "#7E92AE", fontFamily: "var(--font-num)" }}>{fmtN(item.count)}</span>
                )}
                {item.badge && (
                  <span style={{ fontSize: 9, padding: "1px 6px", borderRadius: 3, background: "rgba(255,255,255,.1)", color: "#9BAEC6" }}>{item.badge}</span>
                )}
              </button>
            );
          })}
        </nav>

        {/* ユーザー */}
        <div style={{
          padding: "12px 14px", borderTop: "1px solid rgba(255,255,255,.08)",
          display: "flex", alignItems: "center", gap: 10,
        }}>
          <div style={{
            width: 30, height: 30, borderRadius: "50%", background: "#2563EB",
            display: "flex", alignItems: "center", justifyContent: "center",
            color: "#fff", fontSize: 11, fontWeight: 700,
          }}>K</div>
          <div style={{ display: "flex", flexDirection: "column", minWidth: 0, flex: 1 }}>
            <span style={{ color: "#fff", fontSize: 12, fontWeight: 600 }}>河野 美咲</span>
            <span style={{ color: "#7E92AE", fontSize: 10.5 }}>管理者 · 本社</span>
          </div>
        </div>
      </aside>

      {/* メイン */}
      <main style={{ flex: 1, display: "flex", flexDirection: "column", minWidth: 0, overflow: "hidden" }}>
        {/* 上部バー */}
        <header style={{
          height: 56, background: "#fff", borderBottom: "1px solid var(--border)",
          display: "flex", alignItems: "center", padding: "0 24px", gap: 16, flexShrink: 0,
        }}>
          <div style={{ display: "flex", flexDirection: "column", flex: 1, minWidth: 0 }}>
            <h1 style={{ fontSize: 15, fontWeight: 700, color: "var(--ink-1)", margin: 0, letterSpacing: "0.01em" }}>
              {screenTitle.title}
            </h1>
            <span style={{ fontSize: 11, color: "var(--ink-3)" }}>{screenTitle.sub}</span>
          </div>

          {/* 拠店フィルタ（常駐） */}
          <Select prefix="拠店フィルタ" value={branchFilter} onChange={setBranchFilter} placeholder="全拠店"
            options={data.branches.map(b => ({ value: b.id, label: b.name }))}
          />

          <SearchInput value="" onChange={() => {}} placeholder="グローバル検索" style={{ width: 220 }} />

          <button style={{
            width: 32, height: 32, border: "1px solid var(--border)", borderRadius: 6,
            background: "#fff", display: "flex", alignItems: "center", justifyContent: "center",
            cursor: "pointer", color: "var(--ink-2)", position: "relative",
          }}>
            <Icon.bell />
            <span style={{ position: "absolute", top: 5, right: 6, width: 7, height: 7, background: "#E25555", borderRadius: "50%" }} />
          </button>
        </header>

        {/* スクロール領域 */}
        <div style={{ flex: 1, overflow: "auto", padding: 24 }}>
          {route.screen === "dashboard" && <ScreenDashboard data={data} onNavigate={navigate} />}
          {route.screen === "vehicles" && <ScreenVehicles data={data} onNavigate={navigate} branchFilter={branchFilter} />}
          {route.screen === "vehicle-detail" && <ScreenVehicleDetail data={data} onNavigate={navigate} vehicleId={route.param} />}
          {route.screen === "cards" && <ScreenCards data={data} branchFilter={branchFilter} />}
          {route.screen === "expenses" && <ScreenExpenses data={data} />}
          {route.screen === "drivers" && <PlaceholderScreen title="ドライバー一覧" note="優先5画面の外。次フェーズで実装予定。" />}
          {route.screen === "import" && <PlaceholderScreen title="マスター取込" note="8つのExcelをドラッグ&ドロップで取込み。種別自動判定 / 重複検知 / 名寄せ候補プレビュー。" />}
          {route.screen === "settings" && <PlaceholderScreen title="設定 / ユーザー管理" note="利用者の追加と権限（管理者／参照／編集）を管理。" />}
        </div>
      </main>
    </div>
  );
}

function PlaceholderScreen({ title, note }) {
  return (
    <div style={{
      display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center",
      height: "100%", minHeight: 360, gap: 12,
      background: "#fff", border: "1px dashed var(--border)", borderRadius: 8,
    }}>
      <div style={{ width: 48, height: 48, borderRadius: "50%", background: "var(--bg-soft)", display: "flex", alignItems: "center", justifyContent: "center", color: "var(--ink-3)" }}>
        <Icon.upload />
      </div>
      <div style={{ fontSize: 14, fontWeight: 600, color: "var(--ink-1)" }}>{title}</div>
      <p style={{ fontSize: 12, color: "var(--ink-3)", margin: 0, maxWidth: 360, textAlign: "center", lineHeight: 1.6 }}>{note}</p>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
