/* global React, STRATEGIES, TICKERS, ORDERS_SEED, AUDIT_SEED, WEBHOOKS_SEED, krw, krwSigned, pct, sigQty, fmtPx */
const { useState } = React;

// 포트폴리오 매매 대상 추가/삭제 — 칩 + 입력 박스.
function PortfolioEditor({ s }) {
  const [draft, setDraft] = useState('');
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState(null);
  const portfolio = s.portfolio || [];

  const submit = async (next) => {
    setBusy(true);
    setErr(null);
    const error = await s.setPortfolio(next);
    setBusy(false);
    if (error) setErr(error);
    else setDraft('');
  };

  const remove = (sym) => {
    if (portfolio.length <= 1) {
      setErr('최소 1종목이 남아 있어야 합니다');
      return;
    }
    if (!confirm(`${sym.replace('KRW-', '')} 을(를) 포트폴리오에서 제거할까요?`)) return;
    submit(portfolio.filter(p => p !== sym));
  };

  const add = () => {
    const raw = draft.trim().toUpperCase();
    if (!raw) return;
    const normalized = raw.startsWith('KRW-') ? raw : `KRW-${raw}`;
    if (portfolio.includes(normalized)) {
      setErr('이미 포트폴리오에 있는 종목입니다');
      return;
    }
    submit([...portfolio, normalized]);
  };

  return (
    <div className="form-row">
      <div className="lbl">포트폴리오 종목</div>
      <div className="ctl" style={{ flexWrap: 'wrap', gap: 6 }}>
        {portfolio.map(sym => {
          const t = TICKERS.find(x => x.sym === sym);
          const open = t && (t.qty > 0 || t.slot);
          return (
            <span key={sym} className={`chip ${open ? 'on' : ''}`}
                  style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
              {sym.replace('KRW-', '')}
              <button type="button"
                      onClick={() => remove(sym)}
                      disabled={busy}
                      title={open ? '보유 중 — 봇이 다음 청산 시점에 정리' : '제거'}
                      style={{
                        appearance: 'none', border: 0, background: 'transparent',
                        color: 'var(--text-faint)', cursor: 'pointer',
                        padding: '0 2px', fontSize: 12, lineHeight: 1,
                      }}>×</button>
            </span>
          );
        })}
        <input value={draft}
               onChange={(e) => { setDraft(e.target.value); setErr(null); }}
               onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); add(); } }}
               placeholder="예: BTC 또는 KRW-DOGE"
               disabled={busy}
               style={{ width: 140 }} />
        <button type="button" className="btn primary sm"
                onClick={add} disabled={busy || !draft.trim()}>추가</button>
        {err && <span className="hint" style={{ color: 'var(--down)' }}>{err}</span>}
        {!err && <span className="hint">변경 즉시 반영 · 다음 틱부터 적용</span>}
      </div>
    </div>
  );
}

// =============== STRATEGY PAGE ===============
const PARAMS_BY_STRAT = {
  volatility_breakout:        [{ k: 'K', v: '0.5', hint: 'breakout factor (0.3 ~ 0.7)' }, { k: 'lookback', v: '1', hint: 'days' }],
  sma200_regime:              [{ k: 'MA period', v: '200' }, { k: 'sell on break', v: 'true' }],
  atr_channel_breakout:       [{ k: 'ATR period', v: '14' }, { k: 'mult', v: '2.0' }],
  ema_adx_atr_trend:          [{ k: 'EMA fast', v: '12' }, { k: 'EMA slow', v: '26' }, { k: 'ADX min', v: '22' }],
  ad_turtle:                  [{ k: 'donchian high', v: '20' }, { k: 'donchian low', v: '10' }],
  sma200_ema_adx_composite:   [{ k: 'SMA filter', v: '200' }, { k: 'EMA fast', v: '12' }, { k: 'EMA slow', v: '26' }, { k: 'ADX min', v: '22' }],
};

function StrategyPage({ s }) {
  const sel = STRATEGIES.find(x => x.id === s.activeStrat);
  const params = PARAMS_BY_STRAT[s.activeStrat] || [];
  return (
    <div className="page">
      <h2>전략 · 선택 &amp; 파라미터</h2>
      <div className="subtitle">6개 전략 중 1개 선택 · 변경은 다음 틱부터 즉시 반영 (재시작 불필요)</div>

      <div className="strat-grid">
        {STRATEGIES.map(st => (
          <div key={st.id}
               className={`strat-card ${s.activeStrat === st.id ? 'selected' : ''}`}
               onClick={() => s.setActiveStrat(st.id)}>
            {st.recommended && <span className="badge">권장</span>}
            <div>
              <div className="id">{st.code} · {st.sub}</div>
              <div className="name">{st.name}</div>
            </div>
            <div className="desc">{st.desc}</div>
            <div className="stats">
              <div className="stat">
                <div className="lbl">손익 30일</div>
                <div className={`val ${st.pnl30d >= 0 ? 'up' : 'down'}`}>{pct(st.pnl30d, 1)}</div>
              </div>
              <div className="stat">
                <div className="lbl">샤프</div>
                <div className="val">{st.sharpe.toFixed(2)}</div>
              </div>
              <div className="stat">
                <div className="lbl">승률</div>
                <div className="val">{st.winRate}%</div>
              </div>
            </div>
          </div>
        ))}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 14 }}>
        <div>
          <div className="cell-head" style={{ borderTop: '1px solid var(--border)', borderBottom: '1px solid var(--border)' }}>
            <h3>파라미터 · {sel.code}</h3>
            <span className="meta">{sel.sub}</span>
            <div className="actions">
              <button className="btn ghost sm">초기화</button>
              <button className="btn primary sm">적용</button>
            </div>
          </div>
          <div>
            {params.map(p => (
              <div className="form-row" key={p.k}>
                <div className="lbl">{p.k}</div>
                <div className="ctl">
                  <input defaultValue={p.v} />
                  <span className="hint">{p.hint || ''}</span>
                </div>
              </div>
            ))}
            <div className="form-row">
              <div className="lbl">관찰 주기</div>
              <div className="ctl"><input defaultValue="30" /><span className="hint">분 (텔레그램 리포트)</span></div>
            </div>
            <PortfolioEditor s={s} />
          </div>
        </div>

        <div>
          <div className="cell-head" style={{ borderTop: '1px solid var(--border)', borderBottom: '1px solid var(--border)' }}>
            <h3>Walk-Forward 검증</h3>
            <span className="meta">최근 실행 · 6시간 전</span>
          </div>
          <div style={{ padding: '10px 12px', fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--text-dim)' }}>
            <div className="form-row" style={{ borderBottom: '1px solid var(--border)' }}>
              <div className="lbl">안정성</div>
              <div className="ctl">
                <span className="tag up">통과</span>
                <span className="hint">σ(IS) / σ(OOS) = 0.84</span>
              </div>
            </div>
            <div className="form-row" style={{ borderBottom: '1px solid var(--border)' }}>
              <div className="lbl">전략 알파</div>
              <div className="ctl">
                <span className="tag up">통과</span>
                <span className="hint">+1.8% vs equal_weight</span>
              </div>
            </div>
            <div className="form-row" style={{ borderBottom: '1px solid var(--border)' }}>
              <div className="lbl">증분 알파</div>
              <div className="ctl">
                <span className="tag warn">한계</span>
                <span className="hint">+0.4% vs btc_only</span>
              </div>
            </div>
            <div className="form-row" style={{ borderBottom: '1px solid var(--border)' }}>
              <div className="lbl">IS CAGR</div>
              <div className="ctl"><span className="hot up-color">+18.4%</span></div>
            </div>
            <div className="form-row" style={{ borderBottom: '1px solid var(--border)' }}>
              <div className="lbl">OOS CAGR</div>
              <div className="ctl"><span className="hot up-color">+12.1%</span></div>
            </div>
            <div className="form-row" style={{ borderBottom: '1px solid var(--border)' }}>
              <div className="lbl">최대 낙폭</div>
              <div className="ctl"><span className="hot down-color">−8.7%</span></div>
            </div>
            <div className="form-row">
              <div className="lbl">권고</div>
              <div className="ctl">
                <span className="tag accent">페이퍼 OK</span>
                <span className="hint">실거래: 30일 페이퍼 검증 대기</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// =============== POSITIONS PAGE (full table + per-symbol detail stub) ===============
function PositionsPage({ s }) {
  return (
    <div className="page">
      <h2>포지션 &amp; 관심 종목</h2>
      <div className="subtitle">진입 · 현재가 · 손익 · 손절 · 종목별 전략별</div>
      <div style={{ border: '1px solid var(--border)' }}>
        <table className="t">
          <thead>
            <tr>
              <th>종목</th>
              <th>이름</th>
              <th>슬롯</th>
              <th>전략</th>
              <th>WF</th>
              <th>현재가</th>
              <th>수량</th>
              <th>진입가</th>
              <th>손익</th>
              <th>수익률</th>
              <th>평가액</th>
            </tr>
          </thead>
          <tbody>
            {s.tickers.length === 0 && (
              <tr><td colSpan={11} className="muted" style={{ textAlign: 'center', padding: 20 }}>표시할 종목 없음</td></tr>
            )}
            {s.tickers.map(t => {
              const open = (t.qty || 0) > 0;
              const stale = !!t.price_stale;
              const upnl = open && !stale ? (t.price - t.entry) * t.qty : 0;
              const upnlPct = open && !stale && t.entry > 0 ? ((t.price - t.entry) / t.entry) * 100 : 0;
              const stratCode = STRATEGIES.find(x => x.id === t.strat)?.code;
              return (
                <tr key={t.sym}>
                  <td className="strong">{t.sym}</td>
                  <td className="muted" style={{ textAlign: 'left' }}>{t.name}</td>
                  <td>{t.slot ? `#${t.slot}` : <span className="muted">—</span>}</td>
                  <td className="tag">{stratCode || <span className="muted">—</span>}</td>
                  <td className={t.wf != null && t.wf >= 1 ? 'up' : 'muted'}>
                    {t.wf != null ? Number(t.wf).toFixed(2) : '—'}
                  </td>
                  <td className={stale ? 'muted' : 'strong'}>
                    {Math.round(Number(t.price || 0)).toLocaleString()}{stale ? ' ·' : ''}
                  </td>
                  <td>{open ? sigQty(t.qty) : <span className="muted">—</span>}</td>
                  <td>{open ? fmtPx(t.entry) : <span className="muted">—</span>}</td>
                  <td className={open && !stale ? (upnl >= 0 ? 'up' : 'down') : 'muted'}>
                    {open && !stale ? krwSigned(Math.round(upnl)) : '—'}
                  </td>
                  <td className={open && !stale ? (upnl >= 0 ? 'up' : 'down') : 'muted'}>
                    {open && !stale ? pct(upnlPct) : '—'}
                  </td>
                  <td>{open ? krw(Math.round(t.qty * t.price)) : <span className="muted">—</span>}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// =============== ORDERS PAGE ===============
function OrdersPage({ s }) {
  return (
    <div className="page">
      <h2>주문 · 24시간 스트림</h2>
      <div className="subtitle">체결 {s.orders.length}건 · 오류 0 · UUID 멱등</div>
      <div style={{ border: '1px solid var(--border)' }}>
        <table className="t">
          <thead>
            <tr><th>시간</th><th>방향</th><th>종목</th><th>전략</th><th>가격</th><th>수량</th><th>금액</th><th>상태</th><th>UUID</th></tr>
          </thead>
          <tbody>
            {s.orders.length === 0 && (
              <tr><td colSpan={9} className="muted" style={{ textAlign: 'center', padding: 20 }}>주문 내역 없음</td></tr>
            )}
            {s.orders.map((o, i) => (
              <tr key={o.uuid || i}>
                <td className="muted">{o.ts}</td>
                <td className={o.side === 'BUY' ? 'up' : 'down'} style={{ fontWeight: 600 }}>{o.side === 'BUY' ? '매수' : '매도'}</td>
                <td className="strong">{o.sym}</td>
                <td className="tag">{o.strat || <span className="muted">—</span>}</td>
                <td>{fmtPx(o.px)}</td>
                <td>{sigQty(o.qty)}</td>
                <td>{krw(Math.round(o.krw || 0))}</td>
                <td><span className={`tag ${o.status === 'CANCEL' ? 'muted' : 'up'}`}>{o.status}</span></td>
                <td className="muted" style={{ fontSize: 9 }}>{(o.uuid || '').slice(0, 13) || '—'}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// =============== WEBHOOKS PAGE ===============
function WebhooksPage({ s }) {
  const hooks = s.webhooks || [];
  const latest = hooks[0];
  const statusClass = (status) => {
    const v = String(status || '').toLowerCase();
    if (v === 'accepted' || v === 'executed') return 'up';
    if (v === 'duplicate') return 'accent';
    if (v === 'failed' || v === 'rejected') return 'down';
    return 'warn';
  };
  return (
    <div className="page">
      <h2>TradingView 웹훅</h2>
      <div className="subtitle">
        최근 수신 {hooks.length}건 · secret/allowlist/stale/idempotency 통과 이벤트만 표시 · 현재 단계는 주문 미연결
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10, marginBottom: 12 }}>
        <div className="kpi" style={{ border: '1px solid var(--border)' }}>
          <div className="k">마지막 수신</div>
          <div className="v accent" style={{ fontSize: 22 }}>{latest ? latest.ts : '—'}</div>
          <div className="sub">{latest ? `${latest.market} · ${latest.action}` : '아직 수신 없음'}</div>
        </div>
        <div className="kpi" style={{ border: '1px solid var(--border)' }}>
          <div className="k">최근 중복 감지</div>
          <div className="v" style={{ fontSize: 22 }}>
            {hooks.filter(h => Number(h.seen_count || 1) > 1).length}
          </div>
          <div className="sub">같은 event_id 재수신 건수</div>
        </div>
        <div className="kpi" style={{ border: '1px solid var(--border)' }}>
          <div className="k">실행 연결</div>
          <div className="v" style={{ fontSize: 22, color: 'var(--warn)' }}>OFF</div>
          <div className="sub">Phase 1: 수신/저장만</div>
        </div>
      </div>

      <div style={{ border: '1px solid var(--border)' }}>
        <table className="t">
          <thead>
            <tr>
              <th>수신</th>
              <th>상태</th>
              <th>액션</th>
              <th>마켓</th>
              <th>TF</th>
              <th>가격</th>
              <th>Seen</th>
              <th>Event ID</th>
            </tr>
          </thead>
          <tbody>
            {hooks.length === 0 && (
              <tr><td colSpan={8} className="muted" style={{ textAlign: 'center', padding: 20 }}>웹훅 수신 내역 없음</td></tr>
            )}
            {hooks.map((h, i) => (
              <tr key={h.event_id || i}>
                <td className="muted">{h.ts || '—'}</td>
                <td><span className={`tag ${statusClass(h.status)}`}>{h.status || '—'}</span></td>
                <td className={h.action === 'BUY' ? 'up' : 'down'} style={{ fontWeight: 600 }}>{h.action || '—'}</td>
                <td className="strong">{h.market || '—'}</td>
                <td>{h.timeframe || '—'}</td>
                <td>{h.price != null ? fmtPx(h.price) : <span className="muted">—</span>}</td>
                <td className={Number(h.seen_count || 1) > 1 ? 'up' : 'muted'}>{h.seen_count || 1}</td>
                <td className="muted" style={{ textAlign: 'left', fontSize: 9 }}>{h.event_id || '—'}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// =============== RISK PAGE ===============
function RiskPage({ s }) {
  const r = s.risk || {};
  const rows = [
    { k: 'max_position_ratio', v: (r.max_position_ratio ?? 0).toFixed(2), hint: '1슬롯 투입 = 총자본 × 비율' },
    { k: 'max_concurrent_positions', v: String(r.max_concurrent_positions ?? '—'), hint: '동시 보유 상한' },
    { k: 'daily_loss_limit_pct', v: (r.daily_loss_limit_pct ?? 0).toFixed(2), hint: '포트폴리오 합산 기준 (%)' },
    { k: 'per_position_stop_pct', v: (r.stop_loss_pct ?? 0).toFixed(2), hint: '진입가 기준 종목별 손절 (%)' },
    { k: 'min_order_krw', v: krw(r.min_order_krw ?? 0), hint: '업비트 floor' },
    { k: 'paper_capital', v: krw(r.paper_initial_krw ?? 0), hint: '가상 자본 (paper 기준선)' },
    { k: 'kill_switch', v: s.killSwitch ? 'ON' : 'OFF', hint: '신규 진입 차단 (청산은 정상)' },
  ];
  return (
    <div className="page">
      <h2>리스크 설정</h2>
      <div className="subtitle">변경 시 다음 틱부터 즉시 반영 · 감사 로그 기록</div>
      <div style={{ border: '1px solid var(--border)', marginBottom: 14 }}>
        {rows.map(r => (
          <div className="form-row" key={r.k}>
            <div className="lbl">{r.k}</div>
            <div className="ctl">
              {r.k === 'kill_switch' ? (
                <button className={'btn sm ' + (s.killSwitch ? 'warn' : 'ghost')}
                        onClick={() => s.setKillSwitch(!s.killSwitch)}>
                  <span className={`dot ${s.killSwitch ? 'warn' : 'mute'}`} />{r.v}
                </button>
              ) : (
                <input defaultValue={r.v} />
              )}
              <span className="hint">{r.hint}</span>
            </div>
          </div>
        ))}
      </div>
      <h2>오늘 리스크 사용량</h2>
      <div className="subtitle">실시간 집계</div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10 }}>
        <div className="kpi" style={{ border: '1px solid var(--border)' }}>
          <div className="k">일일 손실 소진</div>
          <div className={'v ' + (s.lossUsedPct > 60 ? 'down' : 'accent')}>{Math.round(s.lossUsedPct)}%</div>
          <div className="sub">한도 {krw(Math.abs(Math.round(s.dailyLossLimit)))} ({pct(-Math.abs(s.dailyLossLimitPct), 1)})</div>
        </div>
        <div className="kpi" style={{ border: '1px solid var(--border)' }}>
          <div className="k">운용 자본</div>
          <div className="v">{krw(Math.round(s.positionValue))}</div>
          <div className="sub">전체 자산의 {s.totalEquity > 0 ? Math.round(s.positionValue / s.totalEquity * 100) : 0}%</div>
        </div>
        <div className="kpi" style={{ border: '1px solid var(--border)' }}>
          <div className="k">슬롯 사용률</div>
          <div className={'v ' + (s.slotsUsed > s.slotsMax ? 'down' : 'accent')}>{s.slotsUsed}/{s.slotsMax}</div>
          <div className="sub">
            {s.slotsMax > 0 ? Math.round((s.slotsUsed / s.slotsMax) * 100) : 0}%
            {s.slotsUsed > s.slotsMax && ' · 상한 초과'}
          </div>
        </div>
      </div>
    </div>
  );
}

// =============== AUDIT PAGE ===============
function AuditPage({ s }) {
  const log = s.audit || [];
  return (
    <div className="page">
      <h2>감사 로그</h2>
      <div className="subtitle">설정 변경 이력 · API 키 자동 마스킹</div>
      <div style={{ border: '1px solid var(--border)' }}>
        <table className="t">
          <thead><tr><th>시간</th><th>종류</th><th>메시지</th></tr></thead>
          <tbody>
            {log.length === 0 && (
              <tr><td colSpan={3} className="muted" style={{ textAlign: 'center', padding: 20 }}>기록 없음</td></tr>
            )}
            {log.map((a, i) => (
              <tr key={i}>
                <td className="muted">{a.ts}</td>
                <td className="tag">{a.kind}</td>
                <td className="strong" style={{ textAlign: 'left' }}>{a.msg}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}


// =============== SETTINGS PAGE ===============
function SettingsPage({ s }) {
  const settingsLinks = [
    {
      title: 'API 키 / Telegram',
      desc: 'Upbit Access·Secret 저장, 연결 테스트, 보유 코인 조회, Telegram 테스트 메시지 전송',
      href: '/settings/api-keys',
      primary: true,
      tags: ['마스킹', 'Fernet 암호화', '보유 코인'],
    },
    {
      title: '전략 설정',
      desc: '전략 이름과 파라미터를 기존 검증 규칙으로 편집',
      href: '/settings/strategy',
      tags: ['런타임 반영'],
    },
    {
      title: '리스크 설정',
      desc: '일일 손실 한도, 슬롯, 포지션 한도를 보수적으로 조정',
      href: '/settings/risk',
      tags: ['킬스위치', '한도'],
    },
    {
      title: '포트폴리오 설정',
      desc: '거래 대상 종목 목록을 DB 설정 기준으로 관리',
      href: '/settings/portfolio',
      tags: ['KRW 마켓', '종목 목록'],
    },
    {
      title: '스케줄 설정',
      desc: 'paper/live 모드와 자동 실행 스케줄을 관리',
      href: '/settings/schedule',
      tags: ['paper/live', '스케줄'],
    },
    {
      title: '감사 로그',
      desc: '설정 변경 이력과 마스킹된 운영 이벤트 확인',
      href: '/settings/audit',
      tags: ['AuditLog', '마스킹'],
    },
  ];

  return (
    <div className="page">
      <h2>설정 · 연동</h2>
      <div className="subtitle">터미널에서 누락됐던 기존 설정 화면으로 바로 이동 · 민감값은 기존 Jinja 라우터의 마스킹/암호화 계약을 그대로 사용</div>
      <div className="strat-grid">
        {settingsLinks.map(link => (
          <a key={link.href}
             className={`strat-card ${link.primary ? 'selected' : ''}`}
             href={link.href}
             style={{ textDecoration: 'none', color: 'inherit' }}>
            {link.primary && <span className="badge">필수</span>}
            <div>
              <div className="id">설정</div>
              <div className="name">{link.title}</div>
            </div>
            <div className="desc">{link.desc}</div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
              {link.tags.map(tag => <span key={tag} className="chip">{tag}</span>)}
            </div>
          </a>
        ))}
      </div>
      <div style={{ marginTop: 14, border: '1px solid var(--border)', padding: 12, background: 'var(--bg-1)' }}>
        <div className="strong">현재 상태</div>
        <div className="subtitle" style={{ marginTop: 4 }}>
          {s.mode === 'live' ? '실거래 모드' : '페이퍼 모드'} · {s.running ? '스케줄 실행중' : '스케줄 정지'}
          {s.killSwitch ? ' · 킬스위치 ON' : ''}
        </div>
        <div className="hint">API 키 저장 화면은 빈 입력 시 기존 값을 유지하고, 저장값이 없으면 .env 값을 fallback으로 사용합니다.</div>
      </div>
    </div>
  );
}

Object.assign(window, { StrategyPage, PositionsPage, OrdersPage, RiskPage, AuditPage, SettingsPage });
