/**
 * SET 19 / 33b.1 — in-app Admin: GLOBAL stats only. Publicly visible to any
 * visitor — no extension, no engine, no gate required. Fed by the
 * deploy-published `/api/site-stats.json`; provenance + generated-at line;
 * unsourced facets are OMITTED (never a fabricated zero). Per-install
 * aggregates live in `InstallStatsPanel` (opened from the sidebar), not here.
 */
import React, { useEffect, useState } from 'react';
import { exportSiteStatsFile } from './exportMetrics';

export type SiteStatsPayload = {
  generatedAt: string;
  unavailable?: true;
  hits?: number;
  botHits?: number;
  downloads?: number;
  runsExecuted?: number;
  runsSucceeded?: number;
  runsFailed?: number;
  provenance?: string[];
};

function fmtGenerated(iso: string | null | undefined): string {
  if (!iso) return '—';
  try {
    return new Date(iso).toLocaleString();
  } catch {
    return iso;
  }
}

/** Card-style number tile — engine admin's `.metric` look (555da66), re-idiomized onto web design tokens. */
function MetricTile({ value, label, tone }: { value: string; label: string; tone?: 'ok' }) {
  return (
    <div className="metrictile">
      <b className={tone ?? ''}>{value}</b>
      <span className="dim">{label}</span>
    </div>
  );
}

function SiteWideSection({ stats, loading }: { stats: SiteStatsPayload | null; loading: boolean }) {
  const unavailable = !stats || stats.unavailable;
  const topFacets: { key: keyof SiteStatsPayload; label: string }[] = [
    { key: 'hits', label: 'Hits (30d)' },
    { key: 'botHits', label: 'Bot hits (30d)' },
    { key: 'downloads', label: 'Plugin downloads' },
    { key: 'runsExecuted', label: 'Runs executed' },
  ];
  const presentTop = topFacets.filter(f => typeof stats?.[f.key] === 'number');
  const succeeded = typeof stats?.runsSucceeded === 'number' ? stats.runsSucceeded : null;
  const failed = typeof stats?.runsFailed === 'number' ? stats.runsFailed : null;
  const hasRatio = succeeded != null && failed != null;
  const totalFinished = (succeeded ?? 0) + (failed ?? 0);
  const pct = hasRatio && totalFinished > 0 ? Math.round(((succeeded ?? 0) / totalFinished) * 100) : null;
  const anyPresent = presentTop.length > 0 || hasRatio;

  return (
    <div className="card admin-section">
      <div className="cardhead">
        <b>Site-wide</b>
        <span className="dim small">open info · publish-time snapshot · no extension required</span>
      </div>
      {loading && <p className="dim">Loading…</p>}
      {!loading && (unavailable || !anyPresent) && (
        <p className="dim">site-wide stats unavailable</p>
      )}
      {!loading && !unavailable && anyPresent && (
        <>
          {presentTop.length > 0 && (
            <div className="metricgrid">
              {presentTop.map(f => (
                <MetricTile key={f.key} value={(stats![f.key] as number).toLocaleString()} label={f.label} />
              ))}
            </div>
          )}
          {hasRatio && (
            <>
              <div className="cardhead" style={{ marginTop: 14 }}><b>Success / failure</b></div>
              <div className="metricgrid">
                <MetricTile value={String(succeeded)} label="Succeeded" tone="ok" />
                <MetricTile value={String(failed)} label="Failed" />
                <MetricTile value={`${pct}%`} label={`Success rate (${totalFinished} finished)`} tone="ok" />
              </div>
            </>
          )}
          <p className="dim small admin-provenance">
            Generated {fmtGenerated(stats!.generatedAt)}
            {stats!.provenance?.length ? ` · ${stats!.provenance.join(' · ')}` : ''}
          </p>
          <button
            type="button"
            className="btn"
            style={{ marginTop: 10 }}
            onClick={() => exportSiteStatsFile(stats!)}
          >
            Export site stats
          </button>
        </>
      )}
    </div>
  );
}

function EngineSection({ engineAdminHref }: { engineAdminHref: string }) {
  return (
    <div className="card admin-section admin-section-secondary">
      <div className="cardhead">
        <b>Engine (Tier 2)</b>
        <span className="dim small">local only · Express telemetry</span>
      </div>
      <p className="dim small" style={{ marginBottom: 0 }}>
        A local engine is running on this machine — its own admin surface has fuller telemetry
        and runtime configuration, kept separate from the global page above.
      </p>
      <a href={engineAdminHref} target="_blank" rel="noreferrer" className="btn ghost" style={{ marginTop: 10, display: 'inline-block' }}>
        Open local engine admin
      </a>
    </div>
  );
}

export function AdminView({
  engineAdminHref,
  onClose,
}: {
  engineAdminHref?: string;
  onClose: () => void;
}) {
  const [site, setSite] = useState<SiteStatsPayload | null>(null);
  const [siteLoading, setSiteLoading] = useState(true);

  useEffect(() => {
    let stop = false;
    setSiteLoading(true);
    fetch('/api/site-stats.json')
      .then(async r => {
        if (!r.ok) throw new Error(`HTTP ${r.status}`);
        return r.json() as Promise<SiteStatsPayload>;
      })
      .then(j => { if (!stop) setSite(j); })
      .catch(() => { if (!stop) setSite({ unavailable: true, generatedAt: new Date().toISOString() }); })
      .finally(() => { if (!stop) setSiteLoading(false); });
    return () => { stop = true; };
  }, []);

  return (
    <div className="admin-view" data-rha-boot="admin">
      <div className="cardhead" style={{ marginBottom: 12, display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
        <b style={{ fontSize: 16 }}>Admin</b>
        <button type="button" className="btn ghost" onClick={onClose}>Close</button>
      </div>
      <SiteWideSection stats={site} loading={siteLoading} />
      {engineAdminHref && <EngineSection engineAdminHref={engineAdminHref} />}
    </div>
  );
}
