// History.jsx — stats + per-platform status table + detail drawer with retry.
/* global React, I, PlatGlyph, PLATFORMS, PLAT_LABEL, PRODUCTS */

const STAT_ICON = { success: 'check', processing: 'clock', failed: 'x', idle: 'dash' };
const STAT_TX = { success: 'Tuntas', processing: 'Proses', failed: 'Gagal', idle: '—' };
const ERR = {
  facebook: 'Token halaman ditolak (kode 190)',
  instagram: 'Rasio video tidak didukung',
  youtube: 'Kuota unggah harian tercapai',
  tiktok: 'Sesi OAuth kedaluwarsa',
  shopee: 'Produk tujuan tidak ditemukan',
};

function rowState(targets) {
  const vals = PLATFORMS.map(p => targets[p.id]).filter(v => v && v !== 'idle');
  if (vals.includes('processing')) return { cls: 'run', tx: 'Sedang diproses' };
  if (vals.includes('failed')) {
    const ok = vals.filter(v => v === 'success').length;
    return { cls: 'fail', tx: `${ok}/${vals.length} terkirim` };
  }
  return { cls: 'done', tx: 'Semua terkirim' };
}

function StatusCell({ state, onRetry, label }) {
  const Ico = I[STAT_ICON[state]];
  return (
    <div className="scell">
      <span className={'st ' + state} title={label + ': ' + STAT_TX[state]}
            onClick={state === 'failed' ? (e) => { e.stopPropagation(); onRetry(); } : undefined}>
        {state === 'failed' ? <I.retry /> : <Ico />}
      </span>
    </div>
  );
}

function Thumb({ h, big }) {
  return (
    <div className={'hthumb' + (big ? ' big' : '')} style={h.cover
      ? { backgroundImage: `url(${h.cover})`, backgroundSize: 'cover', backgroundPosition: 'center' }
      : { background: `linear-gradient(150deg, hsl(${h.hue} 45% 55%), hsl(${(h.hue + 40) % 360} 50% 38%))`, color: '#fff' }}>
      {!h.cover && <I.play />}
    </div>
  );
}

function Drawer({ entry, onClose, onRetry }) {
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose]);
  if (!entry) return null;
  const rs = rowState(entry.targets);
  const prod = entry.product && PRODUCTS.find(p => p.id === entry.product);

  return (
    <div className="drawer-scrim" onClick={onClose}>
      <aside className="drawer" onClick={e => e.stopPropagation()}>
        <div className="dw-head">
          <b>Detail Sebaran</b>
          <button className="iconbtn" onClick={onClose} aria-label="Tutup"><I.x /></button>
        </div>
        <div className="dw-body">
          <div className="dw-top">
            <Thumb h={entry} big />
            <div className="dw-meta">
              <span className={'pill ' + rs.cls} style={{ alignSelf: 'flex-start' }}>{rs.tx}</span>
              <p className="dw-cap">{entry.title}</p>
              <small>{entry.when} · {entry.dur}</small>
              {entry.tags && entry.tags.length > 0 && (
                <div className="tags" style={{ marginTop: 4 }}>
                  {entry.tags.map(t => <span className="tag" key={t} style={{ background: 'var(--surface-2)', color: 'var(--ink-2)' }}>#{t}</span>)}
                </div>
              )}
              {prod && <div className="dw-prod"><PlatGlyph id="shopee" size={20} radius={6} /> Tertaut ke <b>{prod.name}</b></div>}
            </div>
          </div>

          <div className="dw-sect">Status per platform</div>
          <div className="dw-list">
            {PLATFORMS.map(p => {
              const s = entry.targets[p.id] || 'idle';
              return (
                <div className={'dw-row ' + s} key={p.id}>
                  <PlatGlyph id={p.id} size={34} />
                  <div className="dw-pi">
                    <b>{p.name}</b>
                    <small>
                      {s === 'success' ? `Terkirim · ${entry.when}`
                        : s === 'processing' ? 'Sedang diunggah…'
                        : s === 'failed' ? ERR[p.id]
                        : 'Tidak dipilih'}
                    </small>
                  </div>
                  {s === 'success' && <a className="dw-link" href="#" onClick={e => e.preventDefault()}>Lihat <I.ext /></a>}
                  {s === 'processing' && <span className="st processing" style={{ width: 28, height: 28 }}><I.clock /></span>}
                  {s === 'failed' && <button className="btn-soft danger" onClick={() => onRetry(entry.id, p.id)}><I.retry /> Ulang</button>}
                  {s === 'idle' && <span className="dw-idle">—</span>}
                </div>
              );
            })}
          </div>
        </div>
      </aside>
    </div>
  );
}

function History({ history, onRetry, goCompose }) {
  const [q, setQ] = React.useState('');
  const [filter, setFilter] = React.useState('all'); // all | done | run | fail
  const [openId, setOpenId] = React.useState(null);
  const [page, setPage] = React.useState(1);
  const PER = 8;

  const rows = history.filter(h => {
    const s = rowState(h.targets).cls;
    if (filter !== 'all' && filter !== s) return false;
    if (q && !h.title.toLowerCase().includes(q.toLowerCase())) return false;
    return true;
  });

  React.useEffect(() => { setPage(1); }, [q, filter]);
  const totalPages = Math.max(1, Math.ceil(rows.length / PER));
  const curPage = Math.min(page, totalPages);
  const pageRows = rows.slice((curPage - 1) * PER, curPage * PER);
  const from = rows.length ? (curPage - 1) * PER + 1 : 0;
  const to = Math.min(curPage * PER, rows.length);

  const counts = history.reduce((a, h) => { a[rowState(h.targets).cls]++; return a; }, { done: 0, run: 0, fail: 0 });

  // KPIs
  let attempts = 0, successes = 0;
  history.forEach(h => PLATFORMS.forEach(p => {
    const s = h.targets[p.id];
    if (s && s !== 'idle') { attempts++; if (s === 'success') successes++; }
  }));
  const rate = attempts ? Math.round((successes / attempts) * 100) : 0;
  const kpis = [
    { ic: 'film', lbl: 'Total video', val: history.length, tone: '' },
    { ic: 'check', lbl: 'Tingkat sukses', val: rate + '%', tone: 'done' },
    { ic: 'clock', lbl: 'Sedang proses', val: counts.run, tone: 'run' },
    { ic: 'x', lbl: 'Perlu perhatian', val: counts.fail, tone: 'fail' },
  ];

  const openEntry = history.find(h => h.id === openId) || null;

  return (
    <div className="wrap">
      <div className="page-head">
        <h1>Riwayat &amp; Status</h1>
        <p>Pantau setiap video dan keberhasilannya di tiap platform. Klik baris untuk detail, atau ikon merah untuk mengulang.</p>
      </div>

      <div className="kpi-row">
        {kpis.map(k => (
          <div className="kpi card" key={k.lbl}>
            <span className={'kpi-ic ' + k.tone}>{React.createElement(I[k.ic])}</span>
            <div><b>{k.val}</b><small>{k.lbl}</small></div>
          </div>
        ))}
      </div>

      <div className="hist-tools">
        <div className="search">
          <I.search />
          <input className="input" placeholder="Cari judul video…" value={q} onChange={e => setQ(e.target.value)} />
        </div>
        <div className="filterchips">
          {[['all', 'Semua', history.length], ['done', 'Tuntas', counts.done], ['run', 'Proses', counts.run], ['fail', 'Ada gagal', counts.fail]].map(([k, lbl, n]) => (
            <button key={k} className={'fchip' + (filter === k ? ' on' : '')} onClick={() => setFilter(k)}>{lbl} · {n}</button>
          ))}
        </div>
      </div>

      <div className="card" style={{ overflow: 'hidden' }}>
        <div className="thead">
          <div>Video</div>
          {PLATFORMS.map(p => <div key={p.id} className="pcol" title={p.name}><PlatGlyph id={p.id} size={28} radius={8} /></div>)}
          <div style={{ textAlign: 'right' }}>Status</div>
        </div>

        {rows.length === 0 ? (
          <div className="empty">
            <div className="ic"><I.film /></div>
            <b>Belum ada yang cocok</b>
            <span>Coba ubah pencarian atau filter, atau </span>
            <a href="#" onClick={e => { e.preventDefault(); goCompose(); }} style={{ color: 'var(--primary-ink)', fontWeight: 600, textDecoration: 'none' }}>buat multi upload baru</a>.
          </div>
        ) : pageRows.map(h => {
          const rs = rowState(h.targets);
          const prod = h.product && PRODUCTS.find(p => p.id === h.product);
          return (
            <div className="hrow click" key={h.id} onClick={() => setOpenId(h.id)}>
              <div className="hvid">
                <Thumb h={h} />
                <div className="hi">
                  <b>{h.title}</b>
                  <small>{h.when} · {h.dur}{prod ? ` · Shopee → ${prod.name}` : ''}</small>
                  <div className="hmobile-stat">
                    {PLATFORMS.filter(p => h.targets[p.id] && h.targets[p.id] !== 'idle').map(p => (
                      <span className="ms" key={p.id}>
                        <PlatGlyph id={p.id} size={16} radius={5} />
                        <span className={'st ' + h.targets[p.id]} style={{ width: 18, height: 18, borderRadius: 6 }}
                              onClick={h.targets[p.id] === 'failed' ? (e) => { e.stopPropagation(); onRetry(h.id, p.id); } : undefined}>
                          {h.targets[p.id] === 'failed' ? <I.retry /> : React.createElement(I[STAT_ICON[h.targets[p.id]]])}
                        </span>
                      </span>
                    ))}
                  </div>
                </div>
              </div>
              {PLATFORMS.map(p => (
                <StatusCell key={p.id} state={h.targets[p.id] || 'idle'} label={p.name}
                            onRetry={() => onRetry(h.id, p.id)} />
              ))}
              <div className="hstatus">
                <span className={'pill ' + rs.cls}>{rs.tx}</span>
                <span className="hchev"><I.chev /></span>
              </div>
            </div>
          );
        })}
      </div>

      {rows.length > 0 && (
        <div className="pager">
          <span className="pager-info">Menampilkan <b>{from}–{to}</b> dari <b>{rows.length}</b> video</span>
          <div className="pager-ctrl">
            <button className="pgbtn" disabled={curPage === 1} onClick={() => setPage(curPage - 1)} aria-label="Sebelumnya">
              <I.chev style={{ transform: 'rotate(90deg)' }} />
            </button>
            {Array.from({ length: totalPages }, (_, i) => i + 1).map(n => (
              <button key={n} className={'pgbtn num' + (n === curPage ? ' on' : '')} onClick={() => setPage(n)}>{n}</button>
            ))}
            <button className="pgbtn" disabled={curPage === totalPages} onClick={() => setPage(curPage + 1)} aria-label="Berikutnya">
              <I.chev style={{ transform: 'rotate(-90deg)' }} />
            </button>
          </div>
        </div>
      )}

      <Drawer entry={openEntry} onClose={() => setOpenId(null)} onRetry={onRetry} />
    </div>
  );
}

Object.assign(window, { History });
