// ============================================================================
// Top StatusBar + Sidebar
// ============================================================================

// /coin = 코인 전용 대시보드 스코프. 계정 목록을 코인(aster)만으로 받고(별도 localStorage 키),
// 메인(/)은 코인 제외(서버 기본 scope=mt5). 코인 계정은 /coin 에서만 보인다.
const DASH_COIN_SCOPE = (typeof location !== "undefined")
  && location.pathname.replace(/\/+$/, "").endsWith("/coin");
const DASH_ACCT_LS_KEY = DASH_COIN_SCOPE ? "v3ops_account_coin" : "v3ops_account";

const StatusBar = ({ bot, bridge }) => {
  // 코인(Aster) 계정은 live_v3_bot.py가 아니라 coin_bot.main이라 bot.status(프로세스 매칭)가
  // 항상 stopped로 잡힌다 → 코인이면 shim alive로 판정(OverallHero와 동일 코인-aware 분기).
  const isCoin = bridge?.venue === "aster";
  const isRunning = isCoin ? !!bridge.alive : bot.status === "running";
  const profileLabel = isCoin ? `coin/${bridge.botEnv || "testnet"}` : bot.profile;
  const [theme, setTheme] = React.useState(() => {
    if (typeof document !== "undefined") {
      return document.documentElement.dataset.theme || localStorage.getItem("v3ops_theme") || "dark";
    }
    return "dark";
  });
  React.useEffect(() => {
    if (typeof document === "undefined") return;
    document.documentElement.dataset.theme = theme;
    try { localStorage.setItem("v3ops_theme", theme); } catch (_) {}
  }, [theme]);
  const toggleTheme = () => setTheme((t) => t === "dark" ? "light" : "dark");

  // Multi-account selector — uses /api/accounts
  const [accounts, setAccounts] = React.useState([]);
  const [activeAccount, setActiveAccount] = React.useState(() => {
    try { return localStorage.getItem(DASH_ACCT_LS_KEY) || ""; } catch (_) { return ""; }
  });
  const accountValue = accounts.some((a) => a.accountKey === activeAccount)
    ? activeAccount
    : accounts[0]?.accountKey || "";
  React.useEffect(() => {
    const fetchAccounts = async () => {
      try {
        const res = await window.V3OPS_LIVE_DATA?.request?.("/api/accounts" + (DASH_COIN_SCOPE ? "?scope=coin" : ""));
        const nextAccounts = (res?.accounts || []).filter((a) => a?.accountKey && a.accountKey !== "__default__");
        if (!nextAccounts.length) return;
        setAccounts(nextAccounts);
        let stored = "";
        try { stored = localStorage.getItem(DASH_ACCT_LS_KEY) || ""; } catch (_) {}
        const nextAccount = nextAccounts.some((a) => a.accountKey === stored)
          ? stored
          : nextAccounts[0].accountKey;
        if (nextAccount !== stored) {
          try { localStorage.setItem(DASH_ACCT_LS_KEY, nextAccount); } catch (_) {}
          window.dispatchEvent(new CustomEvent("v3ops:account-change", {
            detail: { accountKey: nextAccount, resolvedAccountKey: nextAccount },
          }));
        }
        setActiveAccount(nextAccount);
      } catch (_) {}
    };
    fetchAccounts();
  }, []);
  const onAccountChange = (key) => {
    const selected = accounts.find((a) => a.accountKey === key) || accounts[0];
    if (!selected?.accountKey) return;
    const accountKey = selected.accountKey;
    setActiveAccount(accountKey);
    try { localStorage.setItem(DASH_ACCT_LS_KEY, accountKey); } catch (_) {}
    // Force a fresh /api/all with the new account selection
    window.dispatchEvent(new CustomEvent("v3ops:account-change", {
      detail: { accountKey, resolvedAccountKey: accountKey },
    }));
  };
  return (
    <header className="tb-statusbar">
      <div className="tb-brand">
        <svg width="20" height="20" viewBox="0 0 32 32" fill="none">
          <circle cx="16" cy="16" r="11" stroke="var(--accent)" strokeWidth="2" />
          <path d="M8 19 L12 16 L15 18 L20 12 L24 14" stroke="var(--accent)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
        </svg>
        <span>V3<span style={{ color: "var(--accent)" }}>&nbsp;Ops</span></span>
      </div>

      <div className="tb-statusbar-divider" />

      <div className="tb-status-item">
        <span className="tb-status-key">상태</span>
        <Dot status={isRunning ? "ok" : "fail"} pulse={isRunning} />
        <span className={`mono tb-status-strong ${isRunning ? "pnl-pos" : "pnl-neg"}`}>
          {isRunning ? "실행 중" : "중단"}
        </span>
      </div>
      <div className="tb-status-item">
        <span className="tb-status-key">프로파일</span>
        <span className="mono tb-status-strong">{profileLabel}</span>
      </div>
      {!isCoin && (
        <div className="tb-status-item">
          <span className="tb-status-key">매니페스트</span>
          <span className="mono tb-status-strong" title={bot.manifestId}>{(bot.manifestId || "").split("_").slice(-1)[0]}</span>
        </div>
      )}

      <div className="tb-statusbar-divider" />

      <div className="tb-status-item">
        <span className="tb-status-key">패리티</span>
        <span className={`mono tb-status-strong ${bot.parity === "ok" ? "pnl-pos" : "pnl-neg"}`}>
          {bot.parity === "ok" ? "정상" : "실패"}
        </span>
      </div>
      <div className="tb-status-item">
        <span className="tb-status-key">5분 봉</span>
        <span className="mono tb-status-strong">{fmt.time(bot.lastBar5m)}</span>
      </div>
      <div className="tb-status-item">
        <span className="tb-status-key">갱신</span>
        <span className="mono">{fmt.ago(bot.lastRefresh)}</span>
      </div>

      <div className="tb-spacer" />

      {accounts.length > 0 && (
        <div className="tb-status-item" title="계정 선택">
          <span className="tb-status-key">계정</span>
          <select
            className="tb-account-select mono"
            value={accountValue}
            onChange={(e) => onAccountChange(e.target.value)}
            style={{
              background: "var(--bg-2)",
              color: "var(--fg-1)",
              border: "1px solid var(--border-1)",
              borderRadius: 4,
              padding: "3px 6px",
              fontSize: 11,
              cursor: "pointer",
            }}
          >
            {accounts.map((a) => (
              <option key={a.accountKey} value={a.accountKey}>
                {a.accountMismatch
                  ? `${a.configuredAccountKey || a.accountKey} != ${a.actualAccountKey}`
                  : `${a.login || a.accountKey} · ${(a.equity || 0).toFixed(0)}`}
              </option>
            ))}
          </select>
        </div>
      )}

      {bot.warningCount > 0 && (
        <Badge kind="warn">
          <Icon name="alert" size={11} /> 경고 {bot.warningCount}건
        </Badge>
      )}
      <button
        className="tb-btn tb-btn-secondary tb-btn-icon"
        title="새로고침"
        onClick={() => { try { location.reload(); } catch(_) {} }}
      >
        <Icon name="refresh" size={14} />
      </button>
      <button
        className="tb-btn tb-btn-secondary tb-btn-icon"
        title={theme === "dark" ? "라이트 모드" : "다크 모드"}
        onClick={toggleTheme}
      >
        <Icon name={theme === "dark" ? "sun" : "moon"} size={14} />
      </button>
    </header>
  );
};

const Sidebar = ({ active = "overview", onNav }) => {
  const items = [
    { id: "overview",   label: "개요",        icon: "dashboard" },
    { id: "positions",  label: "포지션",      icon: "coins" },
    { id: "grid",       label: "그리드",      icon: "trend" },
    { id: "liveDaily",  label: "일별 성과",   icon: "calendar" },
    { id: "entryBlocks", label: "진입 차단",   icon: "alert" },
    { id: "compare",    label: "비교",           icon: "trend" },
    { id: "db",         label: "DB 상태",       icon: "db" },
    { id: "ledger",     label: "Live 로그",      icon: "list" },
  ];
  return (
    <aside className="tb-sidebar">
      <nav>
        {items.map((it) => (
          <button
            key={it.id}
            className={`tb-nav-item ${active === it.id ? "active" : ""}`}
            onClick={() => onNav?.(it.id)}
          >
            <Icon name={it.icon} size={16} />
            <span>{it.label}</span>
          </button>
        ))}
      </nav>
      <div className="tb-sidebar-foot">
        <div className="label-caps" style={{ marginBottom: 6 }}>활성 Manifest</div>
        <div className="mono" style={{ fontSize: 11, color: "var(--fg-1)" }}>v3_full_nocap_20_2p0</div>
        <div className="mono" style={{ fontSize: 10, color: "var(--fg-3)", marginTop: 2 }}>20260430T073838Z</div>
      </div>
    </aside>
  );
};

Object.assign(window, { StatusBar, Sidebar });
