// ============================================================
// カレンダー画面 (日別損益グリッド + 参考値表示)
// ============================================================
const T_c = window.TOKENS;

const CalendarScreen = ({ onNav, onRefresh }) => {
  const today = new Date();
  const [month, setMonth] = React.useState(() => {
    const latest = (window.DAILY || []).slice().sort((a, b) => String(b.date).localeCompare(String(a.date)))[0];
    if (latest) return { y: latest.year, m: latest.month - 1 };
    return { y: today.getFullYear(), m: today.getMonth() };
  });
  const [selected, setSelected] = React.useState(null);
  const [filter, setFilter] = React.useState('all');

  const days = window.DAILY.filter(d => d.year === month.y && (d.month - 1) === month.m);
  const monthPnl = days.reduce((s, d) => s + d.pnl, 0);
  const winDays = days.filter(d => d.pnl > 0).length;
  const lossDays = days.filter(d => d.pnl < 0).length;
  const totalTrades = days.reduce((s, d) => s + d.trades, 0);
  const winRate = totalTrades > 0 ? (winDays / (winDays + lossDays) * 100) : 0;
  // 月間最大DD
  let peak = 0, maxDd = 0, running = 0;
  days.forEach(d => {
    running += d.pnl;
    if (running > peak) peak = running;
    if (peak - running > maxDd) maxDd = peak - running;
  });

  const monthName = ['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月'][month.m];

  // カレンダーグリッド作成(月曜始まり)
  const firstDay = new Date(month.y, month.m, 1);
  // JS: 日=0,月=1,...,土=6 → 月曜始まりに変換
  const startDow = (firstDay.getDay() + 6) % 7; // 月=0, 火=1, ... 日=6
  const lastDate = new Date(month.y, month.m + 1, 0).getDate();
  const cells = [];
  for (let i = 0; i < startDow; i++) cells.push(null);
  for (let d = 1; d <= lastDate; d++) {
    const entry = days.find(x => x.day === d);
    // 月曜始まりでの曜日(0=月 ... 5=土, 6=日)
    const jsDow = new Date(month.y, month.m, d).getDay();
    const mondayDow = (jsDow + 6) % 7;
    cells.push({
      day: d,
      pnl: entry?.pnl || 0,
      dayDd: entry?.dayDd || 0,
      trades: entry?.trades || 0,
      mondayDow,
      isToday: d === today.getDate() && month.m === today.getMonth() && month.y === today.getFullYear(),
    });
  }
  // 週単位に分割 (月〜日)
  const weeks = [];
  let cur = [];
  cells.forEach((c, i) => {
    cur.push(c);
    if (cur.length === 7) {
      weeks.push(cur);
      cur = [];
    }
  });
  if (cur.length > 0) {
    while (cur.length < 7) cur.push(null);
    weeks.push(cur);
  }

  return (
    <div>
      <TopBar
        title="カレンダー"
        sub={<span style={{ color: T_c.fg3 }}>日別・EA別損益</span>}
        right={
          <button onClick={onRefresh} style={{
            width: 34, height: 34, borderRadius: 999, border: `1px solid ${T_c.line}`,
            background: T_c.surface, display: 'flex', alignItems: 'center', justifyContent: 'center',
            cursor: 'pointer',
          }}>
            <Icon name="filter" size={14} color={T_c.fg2} />
          </button>
        }
      />

      <div style={{ padding: '16px 12px 100px', display: 'flex', flexDirection: 'column', gap: 16 }}>

        {/* フィルタ(EA別) */}
        <div style={{ display: 'flex', gap: 6, overflowX: 'auto', padding: '0 4px' }}>
          {[{ v: 'all', l: 'すべてのEA', c: T_c.fg }, ...window.MAGICS.map(m => ({ v: m.magic, l: m.name || `#${m.magic}`, c: m.color }))].map(o => (
            <button key={o.v} onClick={() => setFilter(o.v)} style={{
              padding: '6px 12px', borderRadius: 999,
              background: filter === o.v ? T_c.raised : T_c.surface,
              color: filter === o.v ? T_c.fg : T_c.fg3,
              border: `1px solid ${filter === o.v ? T_c.line : T_c.lineSoft}`,
              fontSize: 11, fontWeight: 600, fontFamily: T_c.fontUi,
              cursor: 'pointer', whiteSpace: 'nowrap', flexShrink: 0,
              display: 'inline-flex', alignItems: 'center', gap: 5,
            }}>
              {o.v !== 'all' && <span style={{ width: 6, height: 6, borderRadius: 999, background: o.c }} />}
              {o.l}
            </button>
          ))}
        </div>

        {/* 月間サマリー(参考画像のヘッダ相当) */}
        <div style={{ padding: '0 4px' }}>
          <Card padding={16}>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginBottom: 12 }}>
              <div>
                <div style={{ fontSize: 10, color: T_c.fg3, letterSpacing: 0.4, textTransform: 'uppercase', fontFamily: T_c.fontUi, fontWeight: 600, marginBottom: 4 }}>取引数</div>
                <div style={{ fontFamily: T_c.fontMono, fontSize: 20, fontWeight: 700, color: T_c.fg, letterSpacing: -0.4, fontVariantNumeric: 'tabular-nums' }}>
                  {totalTrades.toLocaleString()}
                </div>
              </div>
              <div style={{ textAlign: 'right' }}>
                <div style={{ fontSize: 10, color: T_c.fg3, letterSpacing: 0.4, textTransform: 'uppercase', fontFamily: T_c.fontUi, fontWeight: 600, marginBottom: 4 }}>勝率</div>
                <div style={{ fontFamily: T_c.fontMono, fontSize: 20, fontWeight: 700, color: T_c.fg, letterSpacing: -0.4, fontVariantNumeric: 'tabular-nums' }}>
                  {winRate.toFixed(1)}%
                </div>
              </div>
            </div>
            <div style={{ borderTop: `1px solid ${T_c.lineSoft}`, paddingTop: 12, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
              <div>
                <div style={{ fontSize: 10, color: T_c.fg3, letterSpacing: 0.4, textTransform: 'uppercase', fontFamily: T_c.fontUi, fontWeight: 600, marginBottom: 4 }}>月間純損益</div>
                <PnL value={monthPnl} size={20} sign={true} weight={700} />
              </div>
              <div style={{ textAlign: 'right' }}>
                <div style={{ fontSize: 10, color: T_c.fg3, letterSpacing: 0.4, textTransform: 'uppercase', fontFamily: T_c.fontUi, fontWeight: 600, marginBottom: 4 }}>月間DD</div>
                <div style={{ fontFamily: T_c.fontMono, fontSize: 20, fontWeight: 700, color: T_c.loss, letterSpacing: -0.4, fontVariantNumeric: 'tabular-nums' }}>
                  -{maxDd.toLocaleString('ja-JP')}
                </div>
              </div>
            </div>
          </Card>
        </div>

        {/* 月切替 */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 20, padding: '0 4px' }}>
          <button onClick={() => setMonth(m => m.m === 0 ? { y: m.y - 1, m: 11 } : { ...m, m: m.m - 1 })} style={{
            background: T_c.surface, border: `1px solid ${T_c.line}`, borderRadius: 999,
            width: 32, height: 32, display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
          }}>
            <Icon name="chevL" size={14} color={T_c.fg2} />
          </button>
          <div style={{ fontSize: 16, fontWeight: 700, color: T_c.fg, fontFamily: T_c.fontUi, letterSpacing: -0.3, minWidth: 140, textAlign: 'center' }}>
            {month.y}年 {monthName}
          </div>
          <button onClick={() => setMonth(m => m.m === 11 ? { y: m.y + 1, m: 0 } : { ...m, m: m.m + 1 })} style={{
            background: T_c.surface, border: `1px solid ${T_c.line}`, borderRadius: 999,
            width: 32, height: 32, display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
          }}>
            <Icon name="chevR" size={14} color={T_c.fg2} />
          </button>
        </div>

        {/* カレンダーグリッド */}
        <div style={{
          background: T_c.surface, border: `1px solid ${T_c.line}`,
          borderRadius: 12, padding: '10px 6px', overflow: 'hidden',
        }}>
          {/* 曜日ヘッダ (月〜日) */}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 3, marginBottom: 6 }}>
            {['月','火','水','木','金','土','日'].map((d, i) => (
              <div key={d} style={{
                textAlign: 'center', fontSize: 10, fontFamily: T_c.fontUi,
                color: i === 5 ? T_c.info + 'CC' : i === 6 ? T_c.loss + 'CC' : T_c.fg3,
                fontWeight: 600, padding: '4px 0',
              }}>{d}</div>
            ))}
          </div>

          {/* 週ごと */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
            {weeks.map((week, wi) => {
              return (
                <div key={wi} style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 3, alignItems: 'stretch' }}>
                  {week.map((c, ci) => {
                    if (!c) return <div key={ci} style={{ background: 'transparent' }} />;
                    const isSel = selected?.day === c.day;
                    const hasPnl = c.pnl !== 0;
                    const isProfit = c.pnl > 0;
                    const pnlColor = isProfit ? T_c.profit : hasPnl ? T_c.loss : T_c.fg4;
                    // 損益額の絶対値マーカー(黄色/緑ドット):利益率で使い分け
                    let dotColor = null;
                    if (hasPnl) {
                      if (isProfit) {
                        dotColor = c.pnl > 40000 ? T_c.warn : T_c.profit;
                      } else {
                        dotColor = T_c.loss;
                      }
                    }
                    return (
                      <div key={ci} onClick={() => setSelected(c)} style={{
                        background: isSel ? T_c.raised : T_c.bg,
                        border: `1px solid ${isSel ? T_c.info : T_c.lineSoft}`,
                        borderRadius: 6, cursor: 'pointer',
                        padding: '5px 3px 5px', minHeight: 64,
                        display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
                        overflow: 'hidden', transition: 'border 0.15s',
                      }}>
                        {/* 上段: 日付 + ドット */}
                        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 2, padding: '0 2px' }}>
                          <span style={{
                            fontSize: 11, fontWeight: c.isToday ? 700 : 500,
                            color: c.isToday ? T_c.info : (ci === 6 ? T_c.loss + 'CC' : ci === 5 ? T_c.info + 'CC' : T_c.fg2),
                            fontFamily: T_c.fontMono,
                            lineHeight: 1,
                          }}>{c.day}</span>
                          {dotColor && (
                            <span style={{
                              width: 4, height: 4, borderRadius: 999, background: dotColor,
                              flexShrink: 0,
                            }} />
                          )}
                        </div>
                        {/* 中段: 損益 (生数字 3桁区切り) */}
                        {hasPnl ? (
                          <div style={{
                            fontSize: 10, fontWeight: 600, fontFamily: T_c.fontMono,
                            color: pnlColor, lineHeight: 1.1, letterSpacing: -0.5,
                            fontVariantNumeric: 'tabular-nums',
                            textAlign: 'center',
                            whiteSpace: 'nowrap',
                          }}>
                            {isProfit ? '+' : ''}{c.pnl.toLocaleString('ja-JP')}
                          </div>
                        ) : <div style={{ height: 11 }} />}
                        {/* 下段: 参考DD値（グレー、生数字） */}
                        {hasPnl ? (
                          <div style={{
                            fontSize: 9, fontFamily: T_c.fontMono,
                            color: T_c.fg4, lineHeight: 1.1, letterSpacing: -0.4,
                            fontVariantNumeric: 'tabular-nums',
                            textAlign: 'center',
                            whiteSpace: 'nowrap',
                          }}>
                            {c.dayDd.toLocaleString('ja-JP')}
                          </div>
                        ) : <div style={{ height: 10 }} />}
                      </div>
                    );
                  })}
                </div>
              );
            })}
          </div>

          {/* 月間合計フッタ */}
          <div style={{
            marginTop: 10, paddingTop: 10,
            borderTop: `1px solid ${T_c.lineSoft}`,
            display: 'flex', justifyContent: 'space-between', alignItems: 'center',
            padding: '10px 4px 2px',
          }}>
            <span style={{ fontSize: 11, color: T_c.fg3, fontFamily: T_c.fontUi, fontWeight: 600, letterSpacing: 0.3 }}>
              月間合計
            </span>
            <span style={{
              fontFamily: T_c.fontMono, fontSize: 15, fontWeight: 700,
              color: monthPnl > 0 ? T_c.profit : monthPnl < 0 ? T_c.loss : T_c.fg,
              letterSpacing: -0.3, fontVariantNumeric: 'tabular-nums',
            }}>
              {monthPnl > 0 ? '+' : ''}{monthPnl.toLocaleString('ja-JP')}
            </span>
          </div>
        </div>

        {/* 凡例 */}
        <div style={{
          padding: '0 6px', display: 'flex', gap: 14, flexWrap: 'wrap',
          fontSize: 10, color: T_c.fg3, fontFamily: T_c.fontUi,
        }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}>
            <span style={{ color: T_c.profit, fontFamily: T_c.fontMono, fontWeight: 600 }}>+12.3k</span>
            日次損益
          </span>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}>
            <span style={{ color: T_c.fg4, fontFamily: T_c.fontMono }}>-45.2k</span>
            日中最大DD
          </span>
        </div>

        {/* 選択日の詳細 */}
        {selected && (
          <div style={{ padding: '0 4px' }}>
            <SectionHead title={`${month.y}/${month.m + 1}/${selected.day} の内訳`} />
            <Card padding={16}>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10, marginBottom: 14 }}>
                <div>
                  <div style={{ fontSize: 9, color: T_c.fg3, letterSpacing: 0.3, textTransform: 'uppercase', fontFamily: T_c.fontUi, fontWeight: 600, marginBottom: 3 }}>純損益</div>
                  <PnL value={selected.pnl} size={17} sign={true} weight={700} />
                </div>
                <div>
                  <div style={{ fontSize: 9, color: T_c.fg3, letterSpacing: 0.3, textTransform: 'uppercase', fontFamily: T_c.fontUi, fontWeight: 600, marginBottom: 3 }}>日中DD</div>
                  <div style={{ fontFamily: T_c.fontMono, fontSize: 17, fontWeight: 700, color: T_c.loss, letterSpacing: -0.3, fontVariantNumeric: 'tabular-nums' }}>
                    {selected.dayDd ? selected.dayDd.toLocaleString('ja-JP') : '0'}
                  </div>
                </div>
                <div>
                  <div style={{ fontSize: 9, color: T_c.fg3, letterSpacing: 0.3, textTransform: 'uppercase', fontFamily: T_c.fontUi, fontWeight: 600, marginBottom: 3 }}>取引数</div>
                  <div style={{ fontFamily: T_c.fontMono, fontSize: 17, fontWeight: 700, color: T_c.fg, letterSpacing: -0.3, fontVariantNumeric: 'tabular-nums' }}>
                    {selected.trades}
                  </div>
                </div>
              </div>
              <div style={{ borderTop: `1px solid ${T_c.lineSoft}`, paddingTop: 12, display: 'flex', flexDirection: 'column', gap: 8 }}>
                <div style={{ fontSize: 10, color: T_c.fg3, letterSpacing: 0.3, textTransform: 'uppercase', fontFamily: T_c.fontUi, fontWeight: 600 }}>EA別</div>
                {window.MAGICS.slice(0, 3).map((m, i) => {
                  const eaPnl = Math.round(selected.pnl * [0.5, 0.3, 0.2][i]);
                  return (
                    <div key={m.magic} style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                      <div style={{ width: 4, height: 20, background: m.color, borderRadius: 2 }} />
                      <div style={{ flex: 1, fontSize: 12, color: T_c.fg2, fontFamily: T_c.fontUi }}>
                        {m.name || <span style={{ color: T_c.fg3 }}>Magic #{m.magic}</span>}
                      </div>
                      <PnL value={eaPnl} size={12} sign={true} />
                    </div>
                  );
                })}
              </div>
            </Card>
          </div>
        )}

      </div>
    </div>
  );
};

// ─────────────────────────────────────────
// コンパクト数値フォーマッタ (+32,453 / -49k / -369k のような表示)
// 参考画像に合わせて、桁数が多い時は千円単位で。カレンダーセルは狭いので短縮を優先。
// ─────────────────────────────────────────
function formatCompact(n) {
  if (n === 0) return '0';
  const abs = Math.abs(n);
  const sign = n < 0 ? '-' : '';
  // セル幅が狭いため、1万以上は全て k 表記に短縮
  //   99,999 以下 → "27k" / "9.8k"
  //   100,000 以上 → "164k"
  if (abs >= 10000) {
    const k = abs / 1000;
    // 100k以上は整数、それ未満は小数第1位まで(ただし整数と同じ値なら省略)
    if (k >= 100) {
      return sign + Math.round(k).toLocaleString('ja-JP') + 'k';
    }
    const rounded = Math.round(k * 10) / 10;
    return sign + (Number.isInteger(rounded) ? rounded : rounded.toFixed(1)) + 'k';
  }
  return sign + abs.toLocaleString('ja-JP');
}

Object.assign(window, { CalendarScreen });
