/* ============================================================
   FIFA EDGE — reusable components
   ============================================================ */

const { useState, useEffect, useMemo, useRef } = React;

/* ----- Icons (inline SVG, 16px) ----- */
const Icon = ({ name, size = 16 }) => {
  const paths = {
    home:      <><path d="M3 9.5L8 3l5 6.5V13a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V9.5Z"/><path d="M6.5 14v-3.5h3V14"/></>,
    live:      <><circle cx="8" cy="8" r="2.5" fill="currentColor" stroke="none"/><path d="M4 8a4 4 0 0 1 8 0"/><path d="M2 8a6 6 0 0 1 12 0"/></>,
    signals:   <><path d="M2 12l3-3 2 2 3-4 4 5"/><circle cx="5" cy="9" r="1" fill="currentColor" stroke="none"/><circle cx="7" cy="11" r="1" fill="currentColor" stroke="none"/><circle cx="10" cy="7" r="1" fill="currentColor" stroke="none"/></>,
    trophy:    <><path d="M4 3h8v2a3 3 0 0 1-3 3H7a3 3 0 0 1-3-3V3Z"/><path d="M12 4h2v1a2 2 0 0 1-2 2M4 4H2v1a2 2 0 0 0 2 2"/><path d="M6 11h4l-.5 2h-3L6 11Z"/><path d="M5 13h6v1H5z"/></>,
    stats:     <><path d="M3 13V7M7 13V3M11 13V9"/></>,
    perf:      <><path d="M2 11l3-3 3 3 5-6"/><path d="M11 5h2v2"/></>,
    settings:  <><circle cx="8" cy="8" r="2"/><path d="M8 2v1.5M8 12.5V14M14 8h-1.5M3.5 8H2M12.2 3.8l-1 1M4.8 11.2l-1 1M12.2 12.2l-1-1M4.8 4.8l-1-1"/></>,
    search:    <><circle cx="7" cy="7" r="4.5"/><path d="M10.5 10.5L13 13"/></>,
    bell:      <><path d="M4 11V7a4 4 0 0 1 8 0v4l1 1H3l1-1Z"/><path d="M6.5 13a1.5 1.5 0 0 0 3 0"/></>,
    arrow_up:  <><path d="M8 12V4M4 8l4-4 4 4"/></>,
    arrow_dn:  <><path d="M8 4v8M4 8l4 4 4-4"/></>,
    filter:    <><path d="M2 3h12l-5 6v4l-2 1V9L2 3z"/></>,
    refresh:   <><path d="M13 4v3h-3"/><path d="M13 7A5 5 0 1 0 12 12"/></>,
    expand:    <><path d="M3 3h3M3 3v3M13 13h-3M13 13v-3M3 13h3M3 13v-3M13 3h-3M13 3v3"/></>,
    telegram:  <><path d="M13 3L2 7l4 1.5L8 13l2-3 3 2.5L13 3Z"/></>,
    play:      <><path d="M5 3l7 5-7 5V3Z" fill="currentColor"/></>,
    pause:     <><path d="M5 3h2v10H5zM9 3h2v10H9z" fill="currentColor" stroke="none"/></>,
    dot:       <circle cx="8" cy="8" r="3" fill="currentColor" stroke="none"/>,
    chev:      <><path d="M6 4l4 4-4 4"/></>,
  };
  return (
    <svg className="ico" width={size} height={size} viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round">
      {paths[name]}
    </svg>
  );
};

/* ----- Sparkline ----- */
const Sparkline = ({ data, w = 72, h = 28, color = 'currentColor' }) => {
  const max = Math.max(...data), min = Math.min(...data);
  const range = max - min || 1;
  const step = w / (data.length - 1);
  const points = data.map((v, i) => `${i*step},${h - ((v - min) / range) * (h - 4) - 2}`).join(' ');
  const areaPoints = `0,${h} ${points} ${w},${h}`;
  return (
    <svg className="spark" viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none">
      <polygon points={areaPoints} fill={color} opacity="0.12" />
      <polyline points={points} fill="none" stroke={color} strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
};

/* ----- KPI tile ----- */
const Kpi = ({ label, value, unit, delta, spark, sparkColor }) => (
  <div className="kpi">
    <div className="lbl"><span className="pip"></span>{label}</div>
    <div className="val mono">{value}{unit && <span className="unit">{unit}</span>}</div>
    {delta !== undefined && (
      <div className={`delta ${delta >= 0 ? 'pos' : 'neg'}`}>
        <Icon name={delta >= 0 ? 'arrow_up' : 'arrow_dn'} size={10} />
        {delta >= 0 ? '+' : ''}{delta}%
      </div>
    )}
    {spark && <Sparkline data={spark} color={sparkColor || 'var(--accent)'} />}
  </div>
);

/* ----- EV circular meter ----- */
const EvMeter = ({ value, conf }) => {
  const pct = Math.max(0, Math.min(100, (value / 20) * 100));
  const r = 18, C = 2 * Math.PI * r;
  const off = C - (C * pct) / 100;
  return (
    <div className="ev-meter" title={`EV +${value}% · conf ${conf}%`}>
      <svg viewBox="0 0 44 44">
        <circle className="bg" cx="22" cy="22" r={r} />
        <circle className="fg" cx="22" cy="22" r={r} strokeDasharray={C} strokeDashoffset={off} />
      </svg>
      <div className="label">+{value.toFixed(1)}</div>
    </div>
  );
};

/* ----- Form dots (W/D/L) ----- */
const FormDots = ({ form }) => (
  <span className="form-dots">
    {form.slice(-10).map((r, i) => <span key={i} className={r}>{r.toUpperCase()}</span>)}
  </span>
);

/* ----- Match row (for Today list) ----- */
const MatchRow = ({ m, showEv }) => {
  const oddKey = m.ev.pick === '1' ? 'h' : m.ev.pick === 'X' ? 'd' : m.ev.pick === '2' ? 'a' : null;
  const pill = m.ev.value >= 7 ? 'pos' : m.ev.value >= 3 ? 'mid' : 'flat';
  return (
    <div className="match" style={{cursor:'pointer'}} onClick={() => window.openH2H && window.openH2H(m.id)}>
      <div className="time">
        <div className="t">{window.fmtHM(m.kickoff)}</div>
        <div>T-{m.minuteToKO}m</div>
      </div>
      <div className="teams">
        <div className="row"><span className="nm">{m.home.handle}<span className="tm">{m.home.team}</span></span><span className="sc mono">{m.home.elo}</span></div>
        <div className="row"><span className="nm">{m.away.handle}<span className="tm">{m.away.team}</span></span><span className="sc mono">{m.away.elo}</span></div>
      </div>
      <div className="league">{m.league}</div>
      <div className="odds">
        <div className={`odd ${oddKey==='h' ? 'highlight' : ''}`}><span className="k">1</span><span className="v">{m.odds.h.toFixed(2)}</span></div>
        <div className={`odd ${oddKey==='d' ? 'highlight' : ''}`}><span className="k">X</span><span className="v">{m.odds.d.toFixed(2)}</span></div>
        <div className={`odd ${oddKey==='a' ? 'highlight' : ''}`}><span className="k">2</span><span className="v">{m.odds.a.toFixed(2)}</span></div>
      </div>
      {showEv && (
        m.ev.pick
          ? <span className={`ev-pill ${pill}`}>{m.ev.pick} · +{m.ev.value.toFixed(1)}%</span>
          : <span className="ev-pill flat">no edge</span>
      )}
    </div>
  );
};

/* ----- Signal queue item ----- */
const SignalQueueItem = ({ m }) => {
  const [countdown, setCountdown] = useState(m.minuteToKO * 60 - 15 * 60); // seconds until T-15min dispatch
  useEffect(() => {
    const t = setInterval(() => setCountdown(c => Math.max(0, c - 1)), 1000);
    return () => clearInterval(t);
  }, []);
  const mm = Math.floor(Math.abs(countdown) / 60).toString().padStart(2,'0');
  const ss = Math.floor(Math.abs(countdown) % 60).toString().padStart(2,'0');
  const oddPicked = m.ev.pick === '1' ? m.odds.h : m.ev.pick === 'X' ? m.odds.d : m.ev.pick === '2' ? m.odds.a : null;
  const status = countdown > 0 ? 'queued' : 'dispatched';

  return (
    <div className="sig">
      <div className="sig-head">
        <span>{m.league} · Kickoff {window.fmtHM(m.kickoff)}</span>
        <span>·</span>
        {status === 'queued' ? <span className="countdown">Dispara em <span className="n mono">{mm}:{ss}</span></span> : <span className="live">dispatched</span>}
      </div>
      <div>
        <div className="sig-match">{m.home.handle} <span className="vs">vs</span> {m.away.handle}</div>
        <div className="sig-meta mono">
          <span><span className="k">ELO</span>{m.home.elo}/{m.away.elo}</span>
          <span><span className="k">Conf</span>{m.ev.conf}%</span>
          <span><span className="k">Stake</span>2.0u</span>
        </div>
      </div>
      <div className="sig-right">
        <EvMeter value={m.ev.value} conf={m.ev.conf} />
        {m.ev.pick && (
          <span className="sig-tip mono"><span className="k">TIP</span>{m.ev.pick}@{oddPicked && oddPicked.toFixed(2)}</span>
        )}
      </div>
    </div>
  );
};

/* ----- Live match row ----- */
const LiveRow = ({ m }) => (
  <div className="live-event">
    <div className="live-time mono">
      {m.minute.toFixed(1)}'
      <div className="bar"><i style={{width: `${(m.minute/8)*100}%`}}/></div>
    </div>
    <div className="live-teams">
      <div className="row"><span className="nm">{m.home.handle} <span style={{color:'var(--text-3)', fontSize:11, fontWeight:400}}>{m.home.team}</span></span><span className="sc">{m.score.h}</span></div>
      <div className="row"><span className="nm">{m.away.handle} <span style={{color:'var(--text-3)', fontSize:11, fontWeight:400}}>{m.away.team}</span></span><span className="sc">{m.score.a}</span></div>
    </div>
    <div className="live-odds">
      <div className="o">{m.odds.h.toFixed(2)}</div>
      <div className="o">{m.odds.d.toFixed(2)}</div>
      <div className="o">{m.odds.a.toFixed(2)}</div>
    </div>
  </div>
);

/* ----- Heatmap ----- */
const Heat = ({ data }) => (
  <div className="heat">
    {data.map((v, i) => <div key={i} className={`cell h${v}`}></div>)}
  </div>
);

/* ----- Sidebar ----- */
const Sidebar = ({ current, onNav }) => {
  const nav = [
    { id: 'today',   label: 'Hoje',           icon: 'home',    count: MATCHES.length },
    { id: 'live',    label: 'Ao Vivo',        icon: 'live',    live: true },
    { id: 'signals', label: 'Sinais',         icon: 'signals', count: SIGNALS.length },
    { id: 'elo',     label: 'Leaderboard',    icon: 'trophy' },
    { id: 'stats',   label: 'Estatísticas',   icon: 'stats' },
    { id: 'perf',    label: 'Performance',    icon: 'perf' },
  ];
  const secondary = [];

  return (
    <aside className="sidebar">
      <div className="brand">
        <div className="brand-mark">FE</div>
        <div>
          <div className="brand-name">FIFA EDGE</div>
          <div className="brand-sub">Tipster · v0.4</div>
        </div>
      </div>

      <div className="nav-section">
        <div className="nav-label">Operação</div>
        {nav.map(n => (
          <div key={n.id} className={`nav-item ${current===n.id?'active':''}`} onClick={() => onNav(n.id)}>
            <Icon name={n.icon} />
            <span>{n.label}</span>
            {n.live ? <span className="live-dot" /> : n.count !== undefined && <span className="count mono">{n.count}</span>}
          </div>
        ))}
      </div>

      {secondary.length > 0 && (
        <div className="nav-section">
          <div className="nav-label">Sistema</div>
          {secondary.map(n => (
            <div key={n.id} className={`nav-item ${current===n.id?'active':''}`} onClick={() => onNav(n.id)}>
              <Icon name={n.icon} />
              <span>{n.label}</span>
            </div>
          ))}
        </div>
      )}

      <div className="sidebar-foot">
        <div className="bot-status">
          <span className="dot"></span>
          <div>
            <div className="k">Scheduler</div>
            <div className="v">online · last tick 12s</div>
          </div>
          <span className="dot" style={{background:'var(--info)', boxShadow:'0 0 8px var(--info)'}}></span>
          <div>
            <div className="k">Telegram</div>
            <div className="v">canal VIP · 847</div>
          </div>
        </div>
      </div>
    </aside>
  );
};

/* ----- Topbar ----- */
const Topbar = ({ section }) => {
  const labels = { today:'Hoje', live:'Ao Vivo', signals:'Sinais', elo:'Leaderboard', stats:'Estatísticas', perf:'Performance' };
  const ov = (typeof OVERVIEW !== 'undefined' ? OVERVIEW : {}) || {};
  const roi = ov.roi_14d;
  const wr = ov.winrate;
  const n14 = ov.signals_14d ?? 0;
  const fmt = (v, d=1) => v == null ? '—' : v.toFixed(d);
  const roiCls = roi == null ? '' : roi >= 0 ? 'pos' : 'neg';
  const roiStr = roi == null ? '—' : (roi >= 0 ? '+' : '') + roi.toFixed(1) + '%';
  return (
    <div className="topbar">
      <div className="crumbs mono">
        <span>FIFA_EDGE</span>
        <span className="sep">/</span>
        <span>e-Soccer</span>
        <span className="sep">/</span>
        <span className="cur">{labels[section]}</span>
      </div>
      <div className="search">
        <Icon name="search" />
        <input placeholder="Buscar player, partida, liga…" />
        <span className="kbd">⌘K</span>
      </div>
      <div className="topbar-right">
        <div className="ticker">
          <span className="lbl">ROI 14d</span>
          <span className={`v ${roiCls} mono`}>{roiStr}</span>
          <span className="sep"></span>
          <span className="lbl">WR</span>
          <span className="v mono">{fmt(wr)}%</span>
          <span className="sep"></span>
          <span className="lbl">Sinais 14d</span>
          <span className="v mono">{n14}</span>
        </div>
        <button className="iconbtn" title="Atualizar"><Icon name="refresh" /></button>
        <button className="iconbtn" title="Notificações"><Icon name="bell" /></button>
        <div className="user-chip">
          <div className="av">AD</div>
          <div>
            <div className="nm">Admin</div>
            <div className="rl mono">OPERATOR</div>
          </div>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { Icon, Sparkline, Kpi, EvMeter, FormDots, MatchRow, SignalQueueItem, LiveRow, Heat, Sidebar, Topbar });
