// admin-speed-audit.jsx — "Funnel Speed Audit" page (Trello #167).
// Shows the latest weekly speed benchmark (WiseFunnel vs competitors) inside the admin.
// Data: dist/speed-audit/audit_results_latest.json + the full dashboard at
// dist/speed-audit/index.html, both copied from the repo root at build time
// (see admin-app/package.json "build"). The weekly-speed-audit.yml workflow produces them.
// "Sync" re-reads the published files without cache, so a fresh deploy shows up at once.
(function () {
  const { useState: useS, useEffect: useE } = React;

  const BASE = '/speed-audit';
  const RUN_URL = 'https://github.com/lecfmpp/wisefunnel_2026_may/actions/workflows/weekly-speed-audit.yml';

  const COLORS = {
    good: { fg: '#16a34a', bg: '#dcfce7' },
    'needs-improvement': { fg: '#d97706', bg: '#fef3c7' },
    poor: { fg: '#dc2626', bg: '#fee2e2' },
    unknown: { fg: '#6b7280', bg: '#f3f4f6' },
  };

  function scoreColor(score) {
    if (score == null) return COLORS.unknown;
    if (score >= 90) return COLORS.good;
    if (score >= 50) return COLORS['needs-improvement'];
    return COLORS.poor;
  }

  function fmtMs(ms) {
    if (ms == null) return '—';
    return ms >= 1000 ? `${(ms / 1000).toFixed(1)} s` : `${Math.round(ms)} ms`;
  }

  function Score({ value }) {
    const c = scoreColor(value);
    return (
      <span style={{ display: 'inline-block', minWidth: 36, textAlign: 'center', padding: '2px 8px', borderRadius: 999, fontWeight: 700, fontSize: 12, color: c.fg, background: c.bg }}>
        {value == null ? '—' : value}
      </span>
    );
  }

  function SpeedAuditPage() {
    const [data, setData] = useS(null);
    const [err, setErr] = useS(null);
    const [loading, setLoading] = useS(true);
    const [stamp, setStamp] = useS(Date.now());
    const [lastSync, setLastSync] = useS(null);

    const load = async () => {
      setLoading(true);
      setErr(null);
      try {
        const t = Date.now();
        const r = await fetch(`${BASE}/audit_results_latest.json?t=${t}`, { cache: 'no-store' });
        if (!r.ok) throw new Error(`HTTP ${r.status} ao ler os resultados`);
        setData(await r.json());
        setStamp(t);
        setLastSync(new Date());
      } catch (e) {
        setErr(e.message);
      } finally {
        setLoading(false);
      }
    };

    useE(() => { load(); }, []);

    const funnels = (data && data.funnels) || [];
    const sorted = [...funnels].sort((a, b) =>
      ((b.composite_mobile || {}).performance_score || 0) - ((a.composite_mobile || {}).performance_score || 0));

    const btn = {
      display: 'inline-flex', alignItems: 'center', gap: 6, padding: '8px 14px', borderRadius: 8,
      border: '1px solid #E5E7EB', background: '#fff', color: '#1A2B3B', fontFamily: 'inherit',
      fontSize: 13, fontWeight: 600, cursor: 'pointer', textDecoration: 'none',
    };

    return (
      <div className="page-content" style={{ padding: 24, display: 'flex', flexDirection: 'column', gap: 16 }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap' }}>
          <div>
            <h1 style={{ fontSize: 20, fontWeight: 800 }}>Funnel Speed Audit</h1>
            <div style={{ fontSize: 12, color: '#6B7280', marginTop: 4 }}>
              {data ? `Audit of ${data.audit_date || data.audit_timestamp}` : 'Weekly benchmark: WiseFunnel vs competitors'}
              {lastSync ? ` · synced ${lastSync.toLocaleTimeString()}` : ''}
            </div>
          </div>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            <button style={{ ...btn, background: '#F97316', borderColor: '#F97316', color: '#fff' }} onClick={load} disabled={loading}>
              <Icon name="RefreshCw" size={14} color="#fff" /> {loading ? 'Syncing…' : 'Sync'}
            </button>
            <a style={btn} href={RUN_URL} target="_blank" rel="noopener noreferrer">
              <Icon name="Play" size={14} /> Run new audit
            </a>
            <a style={btn} href={`${BASE}/index.html?t=${stamp}`} target="_blank" rel="noopener noreferrer">
              <Icon name="ExternalLink" size={14} /> Open full dashboard
            </a>
          </div>
        </div>

        {err && (
          <div style={{ padding: 12, borderRadius: 8, background: '#fee2e2', color: '#991b1b', fontSize: 13 }}>
            Could not load the audit results: {err}
          </div>
        )}

        {sorted.length > 0 && (
          <div style={{ background: '#fff', border: '1px solid #E5E7EB', borderRadius: 12, overflowX: 'auto' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
              <thead>
                <tr style={{ textAlign: 'left', color: '#6B7280', fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.05em' }}>
                  <th style={{ padding: '10px 14px' }}>Platform</th>
                  <th style={{ padding: '10px 14px' }}>Mobile</th>
                  <th style={{ padding: '10px 14px' }}>Mobile LCP</th>
                  <th style={{ padding: '10px 14px' }}>Desktop</th>
                  <th style={{ padding: '10px 14px' }}>Desktop LCP</th>
                  <th style={{ padding: '10px 14px' }}>Pages</th>
                </tr>
              </thead>
              <tbody>
                {sorted.map((f) => {
                  const m = f.composite_mobile || {};
                  const d = f.composite_desktop || {};
                  const isWF = f.platform === 'WiseFunnel';
                  return (
                    <tr key={f.platform} style={{ borderTop: '1px solid #F3F4F6', background: isWF ? '#FFF7ED' : 'transparent' }}>
                      <td style={{ padding: '10px 14px', fontWeight: isWF ? 800 : 600 }}>{f.logo_emoji ? `${f.logo_emoji} ` : ''}{f.platform}</td>
                      <td style={{ padding: '10px 14px' }}><Score value={m.performance_score} /></td>
                      <td style={{ padding: '10px 14px' }}>{fmtMs(m.lcp_ms)}</td>
                      <td style={{ padding: '10px 14px' }}><Score value={d.performance_score} /></td>
                      <td style={{ padding: '10px 14px' }}>{fmtMs(d.lcp_ms)}</td>
                      <td style={{ padding: '10px 14px', color: '#6B7280' }}>{f.page_count != null ? f.page_count : (f.pages || []).length}</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}

        {/* The full dashboard opens in a new tab: the admin sends X-Frame-Options: DENY, so it can't be embedded. */}
        <div style={{ fontSize: 12, color: '#6B7280' }}>
          Per-page details, Web Vitals and fixes are in the full dashboard ("Open full dashboard").
        </div>
      </div>
    );
  }

  window.SpeedAuditPage = SpeedAuditPage;
})();
