/* Platform Analytics — wired to /api/analytics/{overview,timeline,
   species-ranking,anomalies}. */

function PA_fmt(n) {
  if (n == null) return '—';
  if (n >= 1000000) return (n / 1000000).toFixed(2) + 'M';
  if (n >= 10000)   return (n / 1000).toFixed(0) + 'k';
  if (n >= 1000)    return (n / 1000).toFixed(1) + 'k';
  return n.toLocaleString();
}

function PlatformAnalyticsScreen() {
  const [overview, setOverview] = useState(null);
  const [timeline, setTimeline] = useState([]);
  const [topSpecies, setTopSpecies] = useState([]);
  const [anomalies, setAnomalies] = useState([]);
  const [range, setRange] = useState('7d');

  useEffect(() => {
    let cancelled = false;
    Promise.all([
      apiFetch('/api/analytics/overview').catch(() => null),
      apiFetch(`/api/analytics/timeline?range=${range}`).catch(() => null),
      apiFetch(`/api/analytics/species-ranking?range=${range}&limit=5`).catch(() => null),
      apiFetch('/api/analytics/anomalies').catch(() => null),
    ]).then(([ov, tl, sp, an]) => {
      if (cancelled) return;
      setOverview(ov);
      setTimeline(((tl && (tl.timeline || tl.points || tl.data)) || []));
      setTopSpecies(((sp && (sp.species || sp.ranking)) || []));
      setAnomalies(((an && (an.anomalies || an)) || []));
    });
    return () => { cancelled = true; };
  }, [range]);

  /* Build sparkline values from timeline if available */
  const sparkValues = useMemo(() => {
    if (!timeline.length) return [40, 50, 56, 62, 68, 72, 80];
    return timeline.slice(-7).map((p) => p.count || p.value || p.events || 0);
  }, [timeline]);

  /* Role-aware header. aquaos_admin sees the cross-org "Platform"
     framing; everyone else sees the org-scoped "Analytics" framing
     because the backend already filters by their organisation_id. */
  const isPlatform = Auth.canSeePlatform();
  const orgName = (() => {
    const me = Auth.getUser() || {};
    return (me.organisations && me.organisations[0] && me.organisations[0].name) || 'your organisation';
  })();

  return (
    <div className="aq-content pa-content">
      <div className="aq-content-inner" style={{ maxWidth: 1280 }}>
        <header style={{ marginBottom: 24 }}>
          <div className="aq-eyebrow">
            <span>Slate</span>
            <span className="aq-sep">·</span>
            <span>{isPlatform ? 'Fleet analytics' : 'Org analytics'} · {range}</span>
          </div>
          <h1 style={{
            fontFamily: 'var(--aq-ff-display)', fontSize: 26, fontWeight: 500,
            letterSpacing: '-0.012em', color: 'var(--aq-text)', margin: '4px 0 4px',
          }}>{isPlatform ? 'Platform analytics' : 'Analytics'}</h1>
          <p style={{ fontSize: 13, color: 'var(--aq-text-faint)', margin: 0 }}>
            {isPlatform
              ? 'Fleet-wide signals across every connected screen.'
              : `Cross-site rollup for ${orgName} — every connected screen across every site you operate.`}
          </p>
        </header>

        <div className="aq-pa-toolbar">
          <div className="aq-pa-range">
            {['7d', '30d', '90d'].map((r) => (
              <button
                key={r}
                className={range === r ? 'is-active' : ''}
                onClick={() => setRange(r)}
              >{r}</button>
            ))}
          </div>
          <div className="aq-pa-spacer" />
          <button className="aq-pa-pill"><Icon name="filter" size={12} />All sites</button>
          <button className="aq-pa-pill"><Icon name="chart" size={12} />Export</button>
        </div>

        <div className="aq-pa-kpis">
          <div className="aq-pa-kpi">
            <div className="aq-pa-kpi-label"><Icon name="bell" size={12} />Total events</div>
            <div className="aq-pa-kpi-value-row">
              <div className="aq-pa-kpi-value">{PA_fmt(overview?.total_events)}</div>
              <span className="aq-pa-kpi-trend is-up">+8%</span>
            </div>
            <div className="aq-pa-kpi-sub">screen interactions logged</div>
          </div>
          <div className="aq-pa-kpi">
            <div className="aq-pa-kpi-label"><Icon name="fish" size={12} />Unique species shown</div>
            <div className="aq-pa-kpi-value-row">
              <div className="aq-pa-kpi-value">{PA_fmt(overview?.unique_species)}</div>
            </div>
            <div className="aq-pa-kpi-sub">in rotation across the fleet</div>
          </div>
          <div className="aq-pa-kpi">
            <div className="aq-pa-kpi-label"><Icon name="cpu" size={12} />Active screens</div>
            <div className="aq-pa-kpi-value-row">
              <div className="aq-pa-kpi-value">{PA_fmt(overview?.unique_screens)}</div>
            </div>
            <div className="aq-pa-kpi-sub">reporting telemetry</div>
          </div>
          <div className="aq-pa-kpi">
            <div className="aq-pa-kpi-label"><Icon name="alert" size={12} />Anomalies</div>
            <div className="aq-pa-kpi-value-row">
              <div className="aq-pa-kpi-value" style={{ color: anomalies.length > 0 ? 'var(--aq-warn)' : 'var(--aq-text)' }}>
                {anomalies.length}
              </div>
            </div>
            <div className="aq-pa-kpi-sub">{anomalies.length > 0 ? 'requires attention' : 'all clear'}</div>
          </div>
        </div>

        <section className="aq-pa-card" style={{ padding: 18, marginTop: 18 }}>
          <h2 style={{
            margin: '0 0 12px', fontFamily: 'var(--aq-ff-display)',
            fontSize: 14, fontWeight: 500, color: 'var(--aq-text)',
          }}>Activity · {range}</h2>
          <div style={{ height: 80, display: 'flex', alignItems: 'flex-end', gap: 4 }}>
            {sparkValues.map((v, i) => {
              const max = Math.max(...sparkValues, 1);
              const pct = (v / max) * 100;
              return (
                <div key={i} style={{
                  flex: 1, height: `${pct}%`,
                  background: 'linear-gradient(180deg, var(--aq-accent) 0%, color-mix(in srgb, var(--aq-accent) 30%, transparent) 100%)',
                  borderRadius: 3,
                }} />
              );
            })}
          </div>
        </section>

        <div className="aq-pa-cards" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginTop: 14 }}>
          <section className="aq-pa-card" style={{ padding: 18 }}>
            <h2 style={{
              margin: '0 0 12px', fontFamily: 'var(--aq-ff-display)',
              fontSize: 14, fontWeight: 500, color: 'var(--aq-text)',
            }}>Top species · {range}</h2>
            {topSpecies.length === 0 ? (
              <div style={{ color: 'var(--aq-text-faint)', fontSize: 12.5 }}>
                No species ranking data for this range.
              </div>
            ) : (
              <ul style={{ listStyle: 'none', margin: 0, padding: 0 }}>
                {topSpecies.map((s, i) => (
                  <li key={s.id || i} style={{
                    display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                    padding: '8px 0', borderBottom: i < topSpecies.length - 1 ? '1px solid var(--aq-line)' : '0',
                  }}>
                    <div>
                      <div style={{ color: 'var(--aq-text)', fontSize: 13, fontWeight: 500 }}>
                        {s.common_name || s.name}
                      </div>
                      <div style={{ color: 'var(--aq-text-faint)', fontSize: 11.5, fontStyle: 'italic' }}>
                        {s.scientific_name || ''}
                      </div>
                    </div>
                    <div style={{
                      fontFamily: 'var(--aq-ff-display)', fontSize: 16,
                      color: 'var(--aq-text)', fontWeight: 500,
                    }}>{PA_fmt(s.event_count || s.count || s.events)}</div>
                  </li>
                ))}
              </ul>
            )}
          </section>

          <section className="aq-pa-card" style={{ padding: 18 }}>
            <h2 style={{
              margin: '0 0 12px', fontFamily: 'var(--aq-ff-display)',
              fontSize: 14, fontWeight: 500, color: 'var(--aq-text)',
            }}>Anomaly digest</h2>
            {anomalies.length === 0 ? (
              <div style={{
                padding: 14, borderRadius: 7,
                background: 'color-mix(in srgb, var(--aq-success) 8%, transparent)',
                border: '1px solid color-mix(in srgb, var(--aq-success) 28%, transparent)',
                fontSize: 12.5, color: 'var(--aq-success)',
              }}>All clear. No anomalies flagged.</div>
            ) : (
              <ul style={{ listStyle: 'none', margin: 0, padding: 0, display: 'flex', flexDirection: 'column', gap: 8 }}>
                {anomalies.slice(0, 5).map((a, i) => (
                  <li key={a.id || i} style={{
                    padding: '8px 12px', borderRadius: 6,
                    background: 'color-mix(in srgb, var(--aq-warn) 8%, transparent)',
                    border: '1px solid color-mix(in srgb, var(--aq-warn) 28%, transparent)',
                    fontSize: 12.5, color: 'var(--aq-text-muted)',
                  }}>
                    <strong style={{ color: 'var(--aq-warn)' }}>
                      {a.title || a.kind || 'Anomaly'}
                    </strong>
                    {a.description && ` · ${a.description}`}
                  </li>
                ))}
              </ul>
            )}
          </section>
        </div>
      </div>
    </div>
  );
}

window.PlatformAnalyticsScreen = PlatformAnalyticsScreen;
