// ============================================================
// 口座画面 (グループ管理)
// ============================================================
const T_a = window.TOKENS;

const AccountsScreen = ({ onNav, onRefresh }) => {
  const [filter, setFilter] = React.useState('all');
  const [showAdd, setShowAdd] = React.useState(false);

  const groups = window.GROUPS || [];
  const filtered = filter === 'all' ? window.ACCOUNTS : window.ACCOUNTS.filter(a => a.group === filter);

  const totalEquity = window.ACCOUNTS.reduce((s, a) => s + a.equityJpy, 0);
  const totalFloating = window.ACCOUNTS.reduce((s, a) => s + a.floatingJpy, 0);

  return (
    <div>
      <TopBar
        title="口座"
        sub={<span style={{ color: T_a.fg3 }}>{window.ACCOUNTS.length} 口座 · {groups.length} グループ</span>}
        right={
          <button onClick={onRefresh || (() => setShowAdd(true))} style={{
            width: 34, height: 34, borderRadius: 999, border: `1px solid ${T_a.info}`,
            background: T_a.info, display: 'flex', alignItems: 'center', justifyContent: 'center',
            cursor: 'pointer',
          }}>
            <Icon name="sync" size={18} color="#fff" stroke={2.5} />
          </button>
        }
      />

      <div style={{ padding: '16px 16px 100px', display: 'flex', flexDirection: 'column', gap: 16 }}>
        {/* 合計サマリー */}
        <Card padding={16}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <div>
              <div style={{ fontSize: 11, color: T_a.fg3, letterSpacing: 0.5, textTransform: 'uppercase', fontFamily: T_a.fontUi, fontWeight: 600, marginBottom: 4 }}>
                合計有効証拠金
              </div>
              <div style={{ fontFamily: T_a.fontMono, fontSize: 22, fontWeight: 700, color: T_a.fg, fontVariantNumeric: 'tabular-nums', letterSpacing: -0.5 }}>
                {window.fmt.jpy(totalEquity)}
              </div>
            </div>
            <div style={{ textAlign: 'right' }}>
              <div style={{ fontSize: 11, color: T_a.fg3, fontFamily: T_a.fontUi, marginBottom: 4 }}>含み損益</div>
              <PnL value={totalFloating} size={16} sign={true} />
            </div>
          </div>
        </Card>

        {/* グループフィルタ */}
        <div style={{ display: 'flex', gap: 6, overflowX: 'auto', paddingBottom: 2 }}>
          {[{ v: 'all', l: 'すべて' }, ...groups.map(g => ({ v: g, l: g }))].map(o => (
            <button key={o.v} onClick={() => setFilter(o.v)} style={{
              padding: '6px 12px', borderRadius: 999,
              background: filter === o.v ? T_a.raised : T_a.surface,
              color: filter === o.v ? T_a.fg : T_a.fg3,
              border: `1px solid ${filter === o.v ? T_a.line : T_a.lineSoft}`,
              fontSize: 12, fontWeight: 600, fontFamily: T_a.fontUi,
              cursor: 'pointer', whiteSpace: 'nowrap', flexShrink: 0,
            }}>
              {o.l}
            </button>
          ))}
          <button style={{
            padding: '6px 12px', borderRadius: 999,
            background: 'transparent', color: T_a.fg3,
            border: `1px dashed ${T_a.line}`,
            fontSize: 12, fontWeight: 500, fontFamily: T_a.fontUi,
            cursor: 'pointer', whiteSpace: 'nowrap', flexShrink: 0,
            display: 'inline-flex', alignItems: 'center', gap: 4,
          }}>
            <Icon name="sync" size={12} color={T_a.fg3} /> 更新
          </button>
        </div>

        {/* グループごと */}
        {window.ACCOUNTS.length === 0 ? (
          <Card padding={20} style={{ textAlign: 'center' }}>
            <Icon name="wallet" size={28} color={T_a.fg4} />
            <div style={{ marginTop: 10, fontSize: 13, color: T_a.fg2, fontFamily: T_a.fontUi }}>
              口座がまだ登録されていません
            </div>
            <div style={{ marginTop: 4, fontSize: 11, color: T_a.fg3, fontFamily: T_a.fontUi }}>
              HUBを起動すると自動で追加されます
            </div>
          </Card>
        ) : filter === 'all' ? (groups.length ? groups : ['未分類']).map(g => {
          const accs = window.ACCOUNTS.filter(a => a.group === g);
          if (accs.length === 0) return null;
          const gEquity = accs.reduce((s, a) => s + a.equityJpy, 0);
          const gPnl = accs.reduce((s, a) => s + a.todayPnl, 0);
          return (
            <div key={g}>
              <div style={{ padding: '0 4px', marginBottom: 8, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <div>
                  <div style={{ fontSize: 12, color: T_a.fg3, fontWeight: 600, letterSpacing: 0.5, textTransform: 'uppercase', fontFamily: T_a.fontUi }}>{g}</div>
                  <div style={{ fontSize: 10, color: T_a.fg4, fontFamily: T_a.fontMono, marginTop: 2 }}>
                    {accs.length}口座 · {window.fmt.jpy(gEquity, { compact: true })}
                  </div>
                </div>
                <PnL value={gPnl} size={12} sign={true} />
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                {accs.map(a => <AccountCardDetailed key={a.id} acc={a} />)}
              </div>
            </div>
          );
        }) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {filtered.map(a => <AccountCardDetailed key={a.id} acc={a} />)}
          </div>
        )}

        {/* 追加ボタン(空エリア用) */}
        <button style={{
          padding: '18px', borderRadius: 12,
          background: 'transparent', border: `1px dashed ${T_a.line}`,
          color: T_a.fg3, fontSize: 13, fontFamily: T_a.fontUi, fontWeight: 500,
          cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
        }} onClick={onRefresh}>
          <Icon name="plus" size={16} color={T_a.fg3} />
          HUBから再同期
        </button>
      </div>

      {showAdd && <AddAccountSheet onClose={() => setShowAdd(false)} />}
    </div>
  );
};

// ─────────────────────────────────────────
// 詳細口座カード
// ─────────────────────────────────────────
const AccountCardDetailed = ({ acc }) => {
  const [menu, setMenu] = React.useState(false);
  return (
    <div style={{
      background: T_a.surface, border: `1px solid ${T_a.line}`,
      borderRadius: 14, padding: 14, position: 'relative',
    }}>
      {/* 上段 */}
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10, marginBottom: 12 }}>
        <StatusDot status={acc.status} />
        <div style={{ flex: 1 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
            <span style={{ fontSize: 15, fontWeight: 700, color: T_a.fg, fontFamily: T_a.fontUi }}>
              {acc.broker}
            </span>
            <Badge tone={acc.type === 'MT5' ? 'mt5' : 'mt4'} size="xs">{acc.type}</Badge>
            <Badge size="xs">{acc.currency}</Badge>
          </div>
          <div style={{ fontSize: 11, color: T_a.fg3, fontFamily: T_a.fontMono, marginTop: 3 }}>
            #{acc.number} · 最終同期 {window.fmt.ago(acc.lastSync)}
          </div>
        </div>
        <button onClick={() => setMenu(!menu)} style={{ background: 'transparent', border: 'none', cursor: 'pointer', padding: 4 }}>
          <Icon name="more" size={18} color={T_a.fg3} />
        </button>
      </div>

      {/* 数値グリッド */}
      <div style={{
        display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 1,
        background: T_a.line, borderRadius: 8, overflow: 'hidden',
      }}>
        {[
          { l: '残高', v: window.fmt.jpy(acc.balanceJpy, { compact: true }), c: T_a.fg },
          { l: '有効証拠金', v: window.fmt.jpy(acc.equityJpy, { compact: true }), c: T_a.fg },
          {
            l: '維持率',
            v: acc.hasPosition ? window.fmt.marginLevel(acc.marginLevel) : '—',
            c: acc.hasPosition ? (acc.marginLevel < 500 ? T_a.warn : T_a.fg) : T_a.fg3,
            sub: acc.hasPosition ? null : 'ポジションなし',
          },
        ].map((m, i) => (
          <div key={i} style={{ background: T_a.bg, padding: '10px 12px' }}>
            <div style={{ fontSize: 10, color: T_a.fg3, fontFamily: T_a.fontUi, letterSpacing: 0.3, marginBottom: 3 }}>{m.l}</div>
            <div style={{ fontFamily: T_a.fontMono, fontSize: 13, fontWeight: 600, color: m.c, fontVariantNumeric: 'tabular-nums' }}>{m.v}</div>
            {m.sub && <div style={{ fontSize: 9, color: T_a.fg4, marginTop: 1, fontFamily: T_a.fontUi }}>{m.sub}</div>}
          </div>
        ))}
      </div>

      {/* 損益行 */}
      <div style={{
        marginTop: 10, padding: '8px 12px',
        background: T_a.bg, borderRadius: 8,
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
      }}>
        <div style={{ fontSize: 11, color: T_a.fg3, fontFamily: T_a.fontUi }}>
          今日 / 今月 / 累計
        </div>
        <div style={{ display: 'flex', gap: 12 }}>
          <PnL value={acc.todayPnl} size={12} sign={true} />
          <PnL value={acc.monthPnl} size={12} sign={true} />
          <PnL value={acc.totalPnl} size={12} sign={true} />
        </div>
      </div>

      {menu && (
        <div style={{
          position: 'absolute', top: 40, right: 10, zIndex: 20,
          background: T_a.elevated, border: `1px solid ${T_a.line}`,
          borderRadius: 10, boxShadow: '0 12px 32px rgba(0,0,0,0.5)',
          minWidth: 180, overflow: 'hidden',
        }}>
          {[
            { i: 'tag', l: 'グループ変更' },
            { i: 'edit', l: '表示名を編集' },
            { i: 'sync', l: '再同期' },
            { i: 'trash', l: '削除', danger: true },
          ].map((it, i) => (
            <div key={i} onClick={() => setMenu(false)} style={{
              padding: '11px 14px', display: 'flex', alignItems: 'center', gap: 10,
              cursor: 'pointer', borderTop: i > 0 ? `1px solid ${T_a.lineSoft}` : 'none',
              color: it.danger ? T_a.loss : T_a.fg,
              fontSize: 13, fontFamily: T_a.fontUi, fontWeight: 500,
            }}>
              <Icon name={it.i} size={15} color={it.danger ? T_a.loss : T_a.fg2} />
              {it.l}
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

// ─────────────────────────────────────────
// 追加シート
// ─────────────────────────────────────────
const AddAccountSheet = ({ onClose }) => (
  <div style={{
    position: 'absolute', inset: 0, zIndex: 200,
    background: 'rgba(0,0,0,0.6)', backdropFilter: 'blur(8px)',
    display: 'flex', alignItems: 'flex-end',
  }} onClick={onClose}>
    <div onClick={e => e.stopPropagation()} style={{
      width: '100%', background: T_a.elevated,
      borderTopLeftRadius: 20, borderTopRightRadius: 20,
      padding: '18px 16px 34px',
      borderTop: `1px solid ${T_a.line}`,
    }}>
      <div style={{ width: 36, height: 4, background: T_a.line, borderRadius: 2, margin: '0 auto 16px' }} />
      <div style={{ fontSize: 18, fontWeight: 700, color: T_a.fg, fontFamily: T_a.fontUi, marginBottom: 4 }}>
        口座を追加
      </div>
      <div style={{ fontSize: 12, color: T_a.fg3, fontFamily: T_a.fontUi, marginBottom: 18, lineHeight: 1.5 }}>
        MT4/MT5 で Collector を起動すると自動で検出されます。手動追加が必要な場合のみ以下から:
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {[
          { i: 'sync', l: 'HUBから同期', s: '推奨' },
          { i: 'edit', l: '手動で口座番号を入力', s: 'テスト用' },
        ].map((o, i) => (
          <div key={i} style={{
            padding: 14, background: T_a.surface, border: `1px solid ${T_a.line}`,
            borderRadius: 12, display: 'flex', alignItems: 'center', gap: 12, cursor: 'pointer',
          }} onClick={onClose}>
            <div style={{ width: 36, height: 36, borderRadius: 10, background: T_a.raised, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Icon name={o.i} size={18} color={T_a.fg2} />
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 600, color: T_a.fg, fontFamily: T_a.fontUi }}>{o.l}</div>
              <div style={{ fontSize: 11, color: T_a.fg3, fontFamily: T_a.fontUi, marginTop: 2 }}>{o.s}</div>
            </div>
            <Icon name="chevR" size={14} color={T_a.fg4} />
          </div>
        ))}
      </div>
    </div>
  </div>
);

Object.assign(window, { AccountsScreen, AccountCardDetailed, AddAccountSheet });
