// Small UI components for the stock app. Globals: I18N, t, MOCK_*

// ─── Icons ───────────────────────────────────────────────────
const Icon = {
  arrowUp: (props) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" {...props}><path d="M7 14l5-5 5 5"/></svg>,
  arrowDown: (props) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" {...props}><path d="M7 10l5 5 5-5"/></svg>,
  refresh: (props) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" width="14" height="14" {...props}><path d="M3 12a9 9 0 0 1 15.5-6.3L21 8"/><path d="M21 3v5h-5"/><path d="M21 12a9 9 0 0 1-15.5 6.3L3 16"/><path d="M8 16H3v5"/></svg>,
  back: (props) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" width="18" height="18" {...props}><path d="M15 18l-6-6 6-6"/></svg>,
  shield: (props) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...props}><path d="M12 2L4 6v6c0 5 3.5 9 8 10 4.5-1 8-5 8-10V6l-8-4z"/></svg>,
  alert: (props) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...props}><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="13"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>,
  calendar: (props) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...props}><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>,
  star: (props) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...props}><polygon points="12 2 15 9 22 9.5 17 14.5 18.5 22 12 18.5 5.5 22 7 14.5 2 9.5 9 9 12 2"/></svg>,
  bell: (props) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...props}><path d="M18 8a6 6 0 0 0-12 0c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.7 21a2 2 0 0 1-3.4 0"/></svg>,
  x: (props) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...props}><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>,
  chevR: (props) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...props}><path d="M9 18l6-6-6-6"/></svg>,
  chevD: (props) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...props}><path d="M6 9l6 6 6-6"/></svg>,
  check: (props) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" {...props}><polyline points="20 6 9 17 4 12"/></svg>,
  home: (props) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...props}><path d="M3 9.5L12 3l9 6.5V21H3z"/></svg>,
  briefcase: (props) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...props}><rect x="2" y="7" width="20" height="14" rx="2"/><path d="M8 7V5a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>,
  layers: (props) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...props}><polygon points="12 2 2 7 12 12 22 7 12 2"/><polyline points="2 17 12 22 22 17"/><polyline points="2 12 12 17 22 12"/></svg>,
  gear: (props) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...props}><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>,
  trend: (props) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...props}><polyline points="23 6 13.5 15.5 8.5 10.5 1 18"/><polyline points="17 6 23 6 23 12"/></svg>,
  zap: (props) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...props}><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>,
  target: (props) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...props}><circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="6"/><circle cx="12" cy="12" r="2"/></svg>,
};

// ─── Formatters ──────────────────────────────────────────────
const fmt = {
  pct: (v, opts={}) => {
    const sign = opts.signed && v > 0 ? '+' : '';
    return sign + v.toFixed(opts.dp ?? 2) + '%';
  },
  pctFromUnit: (v, opts={}) => fmt.pct(v * 100, opts),
  price: (v, currency='USD') => {
    const sym = { USD: '$', CNY: '¥', USDT: '' }[currency] || '';
    const suf = currency === 'USDT' ? ' USDT' : '';
    const dp = v >= 1000 ? 2 : v >= 1 ? 2 : 4;
    return sym + v.toLocaleString('en-US', { minimumFractionDigits: dp, maximumFractionDigits: dp }) + suf;
  },
  num: (v) => v.toLocaleString('en-US'),
};

// ─── Market icon ─────────────────────────────────────────────
function MarketIcon({ market }) {
  const map = { us: { label: 'US', color: 'var(--src-tech)' }, cn: { label: 'A', color: 'var(--up)' }, crypto: { label: '₿', color: 'var(--accent)' }, th: { label: 'TH', color: 'var(--src-pro, #34c759)' } };
  const m = map[market] || { label: market || '?', color: 'var(--text-3)' };
  return <div className="rec-mkt" style={{ color: m.color, borderColor: 'color-mix(in oklch, ' + m.color + ' 40%, var(--border))' }}>{m.label}</div>;
}

// ─── ChangePct (color + arrow) ───────────────────────────────
function ChangePct({ value, large=false }) {
  const up = value >= 0;
  const cls = up ? 'up' : 'down';
  const Arrow = up ? Icon.arrowUp : Icon.arrowDown;
  return (
    <span className={'ch ' + cls} aria-label={(up ? 'up ' : 'down ') + Math.abs(value) + ' percent'}>
      <Arrow width={large ? 14 : 11} height={large ? 14 : 11} />
      {fmt.pct(Math.abs(value), { dp: 2 })}
    </span>
  );
}

// ─── Risk chip ───────────────────────────────────────────────
function RiskChip({ level, lossProb }) {
  const labels = { low: '●', medium: '●●', high: '●●●' };
  return (
    <span className={'chip ' + level} role="status" aria-label={t('risk.' + level)}>
      <span style={{ fontSize: 8, letterSpacing: -1 }}>{labels[level]}</span>
      {t('risk.' + level)}
      {lossProb != null && <span style={{ opacity: 0.7, marginLeft: 2 }}>· {fmt.pctFromUnit(lossProb, { dp: 0 })}</span>}
    </span>
  );
}

// ─── Win rate badge ──────────────────────────────────────────
function WinRateBadge({ winRate, sampleSize, showWarn=true }) {
  const warn = sampleSize < 30;
  return (
    <span className={'win-badge' + (warn && showWarn ? ' warn' : '')}>
      {warn && showWarn && <Icon.alert width="11" height="11" />}
      <span className="pct">{fmt.pctFromUnit(winRate, { dp: 0 })}</span>
      <span className="n">· n={sampleSize}</span>
    </span>
  );
}

// ─── Three-source mini (for cards) ───────────────────────────
function ThreeSourceMini({ scores }) {
  const items = [
    { k: 'tech', label: t('recommendation.score_technical'), v: scores.technical },
    { k: 'ai', label: t('recommendation.score_ai'), v: scores.ai },
    { k: 'expert', label: t('recommendation.score_expert'), v: scores.expert },
  ];
  return (
    <div className="three-src-mini">
      {items.map(it => (
        <div key={it.k} className={'src-cell ' + it.k}>
          <div className="label">{it.label}</div>
          <div className="val">{it.v}<span style={{ color: 'var(--text-4)', fontSize: 11, fontWeight: 500, marginLeft: 2 }}>/100</span></div>
        </div>
      ))}
    </div>
  );
}

// ─── Three-source big (detail page) ──────────────────────────
function ThreeSourceBig({ scores, reasoning }) {
  const items = [
    { k: 'tech', label: t('recommendation.score_technical'), v: scores.technical, r: reasoning.technical },
    { k: 'ai', label: t('recommendation.score_ai'), v: scores.ai, r: reasoning.ai },
    { k: 'expert', label: t('recommendation.score_expert'), v: scores.expert, r: reasoning.expert },
  ];
  return (
    <div className="three-src-big">
      {items.map(it => (
        <div key={it.k} className={'src-card ' + it.k}>
          <div className="head">
            <span className="lab">
              <span style={{ width: 6, height: 6, borderRadius: 999, background: 'currentColor', display: 'inline-block' }} />
              {it.label}
            </span>
          </div>
          <div className="pct">{it.v}<span className="max"> /100</span></div>
          <div className="reason">{it.r}</div>
        </div>
      ))}
    </div>
  );
}

// ─── Fusion ring (big — detail page) ─────────────────────────
function FusionRing({ score, size=92 }) {
  const r = (size - 10) / 2;
  const c = 2 * Math.PI * r;
  const off = c * (1 - score / 100);
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} aria-label={`fusion ${score}/100`}>
      <defs>
        <linearGradient id="ring-grad" x1="0%" x2="100%">
          <stop offset="0%" stopColor="var(--src-tech)"/>
          <stop offset="50%" stopColor="var(--src-ai)"/>
          <stop offset="100%" stopColor="var(--src-expert)"/>
        </linearGradient>
      </defs>
      <circle cx={size/2} cy={size/2} r={r} fill="none" stroke="var(--bg-3)" strokeWidth="6"/>
      <circle cx={size/2} cy={size/2} r={r} fill="none" stroke="url(#ring-grad)" strokeWidth="6"
              strokeLinecap="round" strokeDasharray={c} strokeDashoffset={off}
              transform={`rotate(-90 ${size/2} ${size/2})`}/>
      <text x="50%" y="48%" textAnchor="middle" dominantBaseline="middle"
            style={{ fontFamily: 'var(--font-mono)', fontWeight: 700, fontSize: size*0.32, fill: 'var(--text-0)' }}>{score}</text>
      <text x="50%" y="68%" textAnchor="middle" style={{ fontSize: 9, fill: 'var(--text-3)' }}>/ 100</text>
    </svg>
  );
}

// ─── States ──────────────────────────────────────────────────
function EmptyState({ market }) {
  const marketLabel = t('dashboard.market_' + market);
  return (
    <div style={{ textAlign: 'center', padding: '40px 24px', color: 'var(--text-3)' }}>
      <svg width="48" height="48" viewBox="0 0 64 64" fill="none" stroke="currentColor" strokeWidth="1.5" style={{ opacity: 0.5, marginBottom: 12 }}>
        <rect x="8" y="14" width="48" height="40" rx="4"/>
        <line x1="8" y1="24" x2="56" y2="24"/>
        <circle cx="32" cy="38" r="6"/>
        <line x1="36" y1="42" x2="42" y2="48"/>
      </svg>
      <div style={{ fontSize: 14, color: 'var(--text-1)', marginBottom: 4 }}>{t('dashboard.empty', { market: marketLabel })}</div>
      <div style={{ fontSize: 12 }}>{t('dashboard.empty_subtitle', { minutes: 18 })}</div>
    </div>
  );
}

function LoadingSkeleton() {
  return (
    <div style={{ padding: '0 16px' }}>
      {[0,1,2].map(i => (
        <div key={i} style={{ background: 'var(--bg-1)', border: '1px solid var(--border)', borderRadius: 12, padding: 14, marginBottom: 10 }}>
          <div style={{ display: 'flex', gap: 10, marginBottom: 12 }}>
            <div className="skel" style={{ width: 26, height: 26, borderRadius: 6 }} />
            <div style={{ flex: 1 }}>
              <div className="skel" style={{ height: 14, width: '40%', marginBottom: 6 }} />
              <div className="skel" style={{ height: 10, width: '60%' }} />
            </div>
            <div className="skel" style={{ width: 60, height: 14 }} />
          </div>
          <div className="skel" style={{ height: 6, marginBottom: 10 }} />
          <div style={{ display: 'flex', gap: 8 }}>
            <div className="skel" style={{ flex: 1, height: 36 }} />
            <div className="skel" style={{ flex: 1, height: 36 }} />
            <div className="skel" style={{ flex: 1, height: 36 }} />
          </div>
        </div>
      ))}
    </div>
  );
}

// ─── Tabs ────────────────────────────────────────────────────
function MarketTabs({ value, onChange }) {
  const opts = [
    { id: 'us', label: t('dashboard.market_us') },
    { id: 'cn', label: t('dashboard.market_cn') },
    { id: 'crypto', label: t('dashboard.market_crypto') },
    { id: 'th', label: t('dashboard.market_th') },
  ];
  return (
    <div className="seg" role="tablist">
      {opts.map(o => (
        <button key={o.id} role="tab" aria-selected={value === o.id}
                className={'seg-btn' + (value === o.id ? ' active' : '')}
                onClick={() => onChange(o.id)}>{o.label}</button>
      ))}
    </div>
  );
}

function TermTabs({ value, onChange }) {
  const opts = [
    { id: 'short', label: t('dashboard.short_term'), sub: t('dashboard.short_sub') },
    { id: 'medium', label: t('dashboard.medium_term'), sub: t('dashboard.medium_sub') },
    { id: 'long', label: t('dashboard.long_term'), sub: t('dashboard.long_sub') },
  ];
  return (
    <div className="term-row" role="tablist">
      {opts.map(o => (
        <button key={o.id} role="tab" aria-selected={value === o.id}
                className={'term-btn' + (value === o.id ? ' active' : '')}
                onClick={() => onChange(o.id)}>
          {o.label}<span className="num">{o.sub}</span>
        </button>
      ))}
    </div>
  );
}

// ─── Circuit breaker banner ──────────────────────────────────
function CircuitBreakerBanner({ show }) {
  if (!show) return null;
  return (
    <div className="banner" role="alert">
      <Icon.alert width="14" height="14" style={{ flexShrink: 0, marginTop: 1 }} />
      <div>
        <div style={{ fontWeight: 600, marginBottom: 2 }}>{t('strategy.cb_title')}</div>
        <div style={{ color: 'color-mix(in oklch, var(--up-strong) 75%, white)' }}>{t('strategy.circuit_breaker')}</div>
      </div>
    </div>
  );
}

// ─── Recommendation card ─────────────────────────────────────
function RecommendationCard({ rec, onClick }) {
  return (
    <article className="rec" onClick={onClick} role="button" tabIndex={0}>
      <div className="rec-row1">
        <MarketIcon market={rec.market} />
        <div className="rec-id">
          <div className="rec-sym">
            <span className="symbol">{rec.symbol}</span>
            <span className="name">{rec.name}</span>
          </div>
        </div>
        <div className="rec-price">
          <div className="px">{fmt.price(rec.price.current, rec.price.currency)}</div>
          <ChangePct value={rec.price.change_pct} />
        </div>
      </div>

      <div className="rec-fusion">
        <span className="fusion-label">{t('recommendation.fusion_score')}</span>
        <div className="fusion-bar"><i style={{ transform: `scaleX(${rec.scores.fusion/100})` }} /></div>
        <span className="fusion-score">{rec.scores.fusion}<span className="max"> /100</span></span>
      </div>

      <ThreeSourceMini scores={rec.scores} />

      <div className="rec-meta">
        <div className="row">
          <Icon.calendar width="11" height="11" style={{ color: 'var(--text-3)' }} />
          <span className="lab">{t('recommendation.hold_period')}</span>
          <span className="v">{t('recommendation.hold_days', { days: rec.recommendation.hold_period_days })}</span>
        </div>
        <div className="row">
          <Icon.shield width="11" height="11" style={{ color: 'var(--text-3)' }} />
          <span className="lab">{t('recommendation.stop_loss')}</span>
          <span className="v">{fmt.price(rec.recommendation.stop_loss, rec.price.currency)}</span>
        </div>
        <div className="row">
          <Icon.trend width="11" height="11" style={{ color: 'var(--text-3)' }} />
          <span className="lab">{t('backtest.win_rate')}</span>
          <WinRateBadge winRate={rec.backtest.win_rate} sampleSize={rec.backtest.sample_size} />
        </div>
        <div className="row" style={{ justifyContent: 'flex-start' }}>
          <RiskChip level={rec.risk.level} lossProb={rec.risk.loss_probability} />
        </div>
      </div>
    </article>
  );
}

Object.assign(window, {
  Icon, fmt, MarketIcon, ChangePct, RiskChip, WinRateBadge,
  ThreeSourceMini, ThreeSourceBig, FusionRing,
  EmptyState, LoadingSkeleton,
  MarketTabs, TermTabs, CircuitBreakerBanner, RecommendationCard,
});
