// Dashboard view

const { fmtRel } = window.CIE_DATA;
const { useLang } = window.CIE_I18N;

// Нормалізуємо поля сервера — backend повертає вкладений об'єкт a2s: { online, players, max_players, ping_ms, map_name }
function normalizeServer(s) {
  const a2s = s.a2s || {};
  return {
    id:            s.id,
    name:          s.name || s.id,
    host:          s.host,
    region:        s.region,
    status:        a2s.online ? 'online' : 'offline',
    players:       a2s.players ?? 0,
    cap:           a2s.max_players ?? 0,
    ping:          a2s.ping_ms != null ? Math.round(a2s.ping_ms) : null,
    cfgVersion:    s.cfg_version || s.cfgVersion || '—',
    lastUpdate:    s.last_update || s.lastUpdate || null,
    scenario:      a2s.map_name || s.scenario || '',
    note:          s.note || null,
  };
}

function Dashboard({ servers: rawServers, openEditor, onRefresh }) {
  const { t } = useLang();
  const [region, setRegion] = useState('all');
  const [statusFilter, setStatusFilter] = useState('all');
  const [search, setSearch] = useState('');
  const [refreshing, setRefreshing] = useState(false);

  const servers = useMemo(() => (rawServers || []).map(normalizeServer), [rawServers]);

  const filtered = useMemo(() => servers.filter(s => {
    if (region !== 'all' && s.region !== region) return false;
    if (statusFilter !== 'all' && s.status !== statusFilter) return false;
    if (search && !`${s.id} ${s.name} ${s.host}`.toLowerCase().includes(search.toLowerCase())) return false;
    return true;
  }), [servers, region, statusFilter, search]);

  const counts = useMemo(() => ({
    all:     servers.length,
    EU:      servers.filter(s => s.region === 'EU').length,
    CN:      servers.filter(s => s.region === 'CN').length,
    online:  servers.filter(s => s.status === 'online').length,
    offline: servers.filter(s => s.status === 'offline').length,
    warning: servers.filter(s => s.status === 'warning').length,
    players: servers.reduce((a, b) => a + b.players, 0),
    cap:     servers.reduce((a, b) => a + b.cap, 0),
  }), [servers]);

  const handleRefresh = () => {
    setRefreshing(true);
    Promise.resolve(onRefresh()).finally(() => setRefreshing(false));
  };

  if (!rawServers) {
    return (
      <div className="view">
        <div className="empty" style={{paddingTop:120}}>{t('dash.loading')}</div>
      </div>
    );
  }

  return (
    <div className="view">
      <div className="view-head">
        <div>
          <h1>{t('dash.title')}</h1>
          <div className="sub">{t('dash.subtitle', { n: servers.length })}</div>
        </div>
        <div className="actions">
          <button className="btn ghost sm" onClick={handleRefresh} disabled={refreshing}>
            {refreshing ? t('dash.refreshing') : t('dash.refresh')}
          </button>
        </div>
      </div>

      <div className="stats">
        <div className="cell" style={counts.online === counts.all && counts.all > 0 ? {boxShadow:'inset 0 -2px 0 var(--ok)'} : {}}>
          <div className="label">{t('online')}</div>
          <div className="v ok">{counts.online}<span style={{color:'var(--text-faint)', fontSize:14}}>/{counts.all}</span></div>
        </div>
        <div className="cell" style={counts.offline > 0 ? {boxShadow:'inset 0 -2px 0 var(--err)', background:'rgba(221,68,68,0.04)'} : {}}>
          <div className="label">{t('offline')}</div>
          <div className="v err">{counts.offline}</div>
          {counts.offline > 0 && <div className="delta">{servers.filter(s=>s.status==='offline').map(s=>s.id).join(', ')}</div>}
        </div>
        <div className="cell" style={counts.warning > 0 ? {boxShadow:'inset 0 -2px 0 var(--warn)', background:'rgba(221,170,68,0.04)'} : {}}>
          <div className="label">{t('warning')}</div>
          <div className="v warn">{counts.warning}</div>
          {counts.warning > 0 && <div className="delta">{servers.filter(s=>s.status==='warning').map(s=>s.id).join(', ')}</div>}
        </div>
        <div className="cell" style={counts.cap > 0 && counts.players/counts.cap > 0.7 ? {boxShadow:'inset 0 -2px 0 var(--warn)'} : {}}>
          <div className="label">{t('players')}</div>
          <div className="v">{counts.players}<span style={{color:'var(--text-faint)', fontSize:14}}>/{counts.cap}</span></div>
          {counts.cap > 0 && <div className="delta">{t('dash.capacity', { pct: Math.round(counts.players / counts.cap * 100) })}</div>}
        </div>
      </div>

      <div className="filterbar">
        <div className="group">
          <div className={`seg ${region==='all'?'on':''}`} onClick={() => setRegion('all')}>{t('all')}<span className="count">{counts.all}</span></div>
          <div className={`seg ${region==='EU' ?'on':''}`} onClick={() => setRegion('EU')}>EU<span className="count">{counts.EU}</span></div>
          <div className={`seg ${region==='CN' ?'on':''}`} onClick={() => setRegion('CN')}>CN<span className="count">{counts.CN}</span></div>
        </div>
        <div className="group">
          <div className={`seg ${statusFilter==='all'    ?'on':''}`} onClick={() => setStatusFilter('all')}>{t('any')}</div>
          <div className={`seg ${statusFilter==='online' ?'on':''}`} onClick={() => setStatusFilter('online')}>{t('online')}<span className="count">{counts.online}</span></div>
          <div className={`seg ${statusFilter==='offline'?'on':''}`} onClick={() => setStatusFilter('offline')}>{t('offline')}<span className="count">{counts.offline}</span></div>
          <div className={`seg ${statusFilter==='warning'?'on':''}`} onClick={() => setStatusFilter('warning')}>{t('warning')}<span className="count">{counts.warning}</span></div>
        </div>
        <div className="search">
          <span className="ico">⌕</span>
          <input value={search} onChange={(e) => setSearch(e.target.value)} placeholder={t('search_placeholder')} />
        </div>
      </div>

      <table className="tbl" style={{marginTop:0, width:'auto', minWidth:'100%'}}>
        <thead>
          <tr>
            <th style={{width:220}}>{t('dash.col_server')}</th>
            <th style={{width:64}}>{t('region')}</th>
            <th style={{width:120}}>{t('status')}</th>
            <th style={{width:110}}>{t('players')}</th>
            <th style={{width:70}}>{t('ping')}</th>
            <th style={{width:140}}>{t('host')}</th>
            <th style={{width:60}}></th>
          </tr>
        </thead>
        <tbody>
          {filtered.map(s => {
            const fillPct = s.cap > 0 ? Math.round((s.players / s.cap) * 100) : 0;
            return (
              <tr key={s.id}>
                <td>
                  <div style={{fontWeight:500, fontSize:13}}>{s.name || s.id}</div>
                  {s.scenario && <div className="mono" style={{fontSize:10, color:'var(--text-faint)', marginTop:2}}>{s.scenario}</div>}
                </td>
                <td><RegionTag region={s.region} /></td>
                <td>
                  <StatusBadge status={s.status} label={t(s.status)} />
                  {s.note && <div style={{fontSize:10, color:'var(--text-mute)', marginTop:2, fontFamily:'var(--mono)'}}>{s.note}</div>}
                </td>
                <td className="num">
                  <span style={{color: s.players > 0 ? 'var(--text)' : 'var(--text-faint)'}}>
                    {s.players}<span style={{color:'var(--text-faint)'}}>/{s.cap}</span>
                  </span>
                  <div style={{height:2, background:'var(--surface-3)', marginTop:4, borderRadius:1, overflow:'hidden'}}>
                    <div style={{height:'100%', width: fillPct+'%', background: fillPct > 80 ? 'var(--warn)' : 'var(--accent)', transition:'width 0.3s ease'}} />
                  </div>
                </td>
                <td className="num dim">{s.ping == null ? '—' : s.ping + 'ms'}</td>
                <td className="mono dim" style={{fontSize:10.5}}>{s.host}</td>
                <td>
                  <button className="btn ghost sm" style={{padding:'2px 10px'}} onClick={() => openEditor(s.id)}>
                    {t('edit')}
                  </button>
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>

      {filtered.length === 0 && (
        <div className="empty">{t('dash.no_match')}</div>
      )}
    </div>
  );
}

window.Dashboard = Dashboard;
