{% raw %}/**
 * AnalyticsDashboard - Admin dashboard page for analytics.
 *
 * Displays key metrics: events, sessions, page views, top events, and trends.
 *
 * ⚠️ AUTO-GENERATED BY PRISM — DO NOT EDIT
 */

import React, { useEffect, useState } from 'react';
import { analyticsApi, type AnalyticsSummary } from '../lib/analyticsApi';

type TimeRange = 7 | 30 | 90;

export default function AnalyticsDashboard() {
  const [summary, setSummary] = useState<AnalyticsSummary | null>(null);
  const [loading, setLoading] = useState(true);
  const [days, setDays] = useState<TimeRange>(30);

  useEffect(() => {
    setLoading(true);
    analyticsApi
      .getSummary(days)
      .then(setSummary)
      .finally(() => setLoading(false));
  }, [days]);

  if (loading) {
    return (
      <div style={{ padding: '2rem', textAlign: 'center' }}>
        <p>Loading analytics...</p>
      </div>
    );
  }

  if (!summary) {
    return (
      <div style={{ padding: '2rem', textAlign: 'center' }}>
        <p>Failed to load analytics data.</p>
      </div>
    );
  }

  return (
    <div style={{ padding: '2rem', maxWidth: '1200px', margin: '0 auto' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '2rem' }}>
        <h1 style={{ margin: 0, fontSize: '1.5rem' }}>Analytics Dashboard</h1>
        <div style={{ display: 'flex', gap: '0.5rem' }}>
          {([7, 30, 90] as TimeRange[]).map((d) => (
            <button
              key={d}
              onClick={() => setDays(d)}
              style={{
                padding: '0.5rem 1rem',
                border: '1px solid #ddd',
                borderRadius: '4px',
                background: days === d ? '#0066cc' : '#fff',
                color: days === d ? '#fff' : '#333',
                cursor: 'pointer',
              }}
            >
              {d}d
            </button>
          ))}
        </div>
      </div>

      {/* Summary Cards */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: '1rem', marginBottom: '2rem' }}>
        <SummaryCard label="Total Events" value={summary.total_events} />
        <SummaryCard label="Page Views" value={summary.total_page_views} />
        <SummaryCard label="Sessions" value={summary.total_sessions} />
        <SummaryCard label="Unique Users" value={summary.unique_users} />
        <SummaryCard
          label="Avg Session"
          value={summary.avg_session_duration ? `${Math.round(summary.avg_session_duration)}s` : 'N/A'}
        />
      </div>

      {/* Top Events & Pages */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '1.5rem', marginBottom: '2rem' }}>
        <div>
          <h3 style={{ marginBottom: '0.5rem' }}>Top Events</h3>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr>
                <th style={thStyle}>Event</th>
                <th style={{ ...thStyle, textAlign: 'right' }}>Count</th>
              </tr>
            </thead>
            <tbody>
              {summary.top_events.map((e, i) => (
                <tr key={i}>
                  <td style={tdStyle}>{e.event_name}</td>
                  <td style={{ ...tdStyle, textAlign: 'right' }}>{e.count}</td>
                </tr>
              ))}
              {summary.top_events.length === 0 && (
                <tr><td colSpan={2} style={tdStyle}>No events yet</td></tr>
              )}
            </tbody>
          </table>
        </div>
        <div>
          <h3 style={{ marginBottom: '0.5rem' }}>Top Pages</h3>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr>
                <th style={thStyle}>Page</th>
                <th style={{ ...thStyle, textAlign: 'right' }}>Views</th>
              </tr>
            </thead>
            <tbody>
              {summary.top_pages.map((p, i) => (
                <tr key={i}>
                  <td style={tdStyle}>{p.page_url}</td>
                  <td style={{ ...tdStyle, textAlign: 'right' }}>{p.count}</td>
                </tr>
              ))}
              {summary.top_pages.length === 0 && (
                <tr><td colSpan={2} style={tdStyle}>No page views yet</td></tr>
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* Events by Day */}
      <div>
        <h3 style={{ marginBottom: '0.5rem' }}>Events by Day</h3>
        <div style={{ display: 'flex', alignItems: 'flex-end', gap: '2px', height: '120px' }}>
          {summary.events_by_day.map((d, i) => {
            const max = Math.max(...summary.events_by_day.map((x) => x.count), 1);
            const height = (d.count / max) * 100;
            return (
              <div
                key={i}
                title={`${d.day}: ${d.count} events`}
                style={{
                  flex: 1,
                  height: `${height}%`,
                  background: '#0066cc',
                  borderRadius: '2px 2px 0 0',
                  minHeight: '2px',
                }}
              />
            );
          })}
        </div>
      </div>
    </div>
  );
}

function SummaryCard({ label, value }: { label: string; value: string | number }) {
  return (
    <div style={{ padding: '1rem', border: '1px solid #e0e0e0', borderRadius: '8px', background: '#fafafa' }}>
      <div style={{ fontSize: '0.85rem', color: '#666', marginBottom: '0.25rem' }}>{label}</div>
      <div style={{ fontSize: '1.5rem', fontWeight: 600 }}>{value}</div>
    </div>
  );
}

const thStyle: React.CSSProperties = {
  textAlign: 'left',
  padding: '0.5rem',
  borderBottom: '2px solid #e0e0e0',
  fontSize: '0.85rem',
  color: '#666',
};

const tdStyle: React.CSSProperties = {
  padding: '0.5rem',
  borderBottom: '1px solid #f0f0f0',
  fontSize: '0.9rem',
};
{% endraw %}
