import { useEffect, useState, useCallback } from 'react';
import { supabase } from './supabaseClient';
import {
  Users, Send, MousePointer2, Mail, RefreshCw,
  ChevronDown, Search, Download, CheckCircle2, XCircle, ExternalLink
} from 'lucide-react';

const APP_VERSION = "2026.06.15.03-DASHBOARD-GRANULAR";

// ── Types ──────────────────────────────────────────────────────────────
type Instance = { sentAt: string; sent: number; opens: number; clicks: number };
type Campaign = {
  subject: string; totalSent: number; totalOpens: number; totalClicks: number;
  instances: Instance[];
};
type GranularRow = {
  recipient_email: string; subject: string; sent_at: string | null;
  opened: boolean; opened_at: string | null;
  clicked: boolean; clicked_at: string | null; url_clicked: string | null;
};

// ── Helpers ────────────────────────────────────────────────────────────
const pct = (num: number, den: number) =>
  den > 0 ? `${Math.round((num / den) * 100)}%` : '—';

const fmtDate = (iso: string | null | undefined) => {
  if (!iso) return '—';
  const d = new Date(iso);
  return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }) +
    ' · ' + d.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' });
};

const fmtShort = (iso: string | null | undefined) => {
  if (!iso) return '—';
  const d = new Date(iso);
  return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' }) +
    ' · ' + d.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' });
};

const PAGE_SIZE = 50;

// ── CSV export ─────────────────────────────────────────────────────────
function downloadCSV(rows: GranularRow[], source: string) {
  const headers = ['Email', 'Subject', 'Sent At', 'Opened', 'Opened At', 'Clicked', 'Clicked At', 'URL Clicked'];
  const escape  = (v: string) => `"${(v || '').replace(/"/g, '""')}"`;
  const lines   = [
    headers.join(','),
    ...rows.map(r => [
      escape(r.recipient_email),
      escape(r.subject),
      r.sent_at    ? new Date(r.sent_at).toLocaleString()    : '',
      r.opened     ? 'Yes' : 'No',
      r.opened_at  ? new Date(r.opened_at).toLocaleString()  : '',
      r.clicked    ? 'Yes' : 'No',
      r.clicked_at ? new Date(r.clicked_at).toLocaleString() : '',
      escape(r.url_clicked || ''),
    ].join(','))
  ];
  const blob = new Blob([lines.join('\n')], { type: 'text/csv' });
  const url  = URL.createObjectURL(blob);
  const a    = document.createElement('a');
  a.href     = url;
  a.download = `SMM_${source}_analytics_${new Date().toISOString().slice(0, 10)}.csv`;
  a.click();
  URL.revokeObjectURL(url);
}

// ── Component ──────────────────────────────────────────────────────────
const Dashboard = ({ userId }: { userId: string }) => {
  const [activeTab, setActiveTab]       = useState<'overview' | 'granular'>('overview');
  const [selectedSource, setSelectedSource] = useState<'BNP' | 'B2B' | 'B2C'>('BNP');

  // Overview state
  const [stats, setStats]           = useState({ totalMembers: 0, totalSent: 0, totalOpens: 0, totalClicks: 0 });
  const [campaigns, setCampaigns]   = useState<Campaign[]>([]);
  const [expanded, setExpanded]     = useState<Set<string>>(new Set());
  const [overviewLoading, setOverviewLoading] = useState(true);

  // Granular state
  const [granularRows, setGranularRows]     = useState<GranularRow[]>([]);
  const [granularTotal, setGranularTotal]   = useState(0);
  const [granularLoading, setGranularLoading] = useState(false);
  const [search, setSearch]                 = useState('');
  const [page, setPage]                     = useState(0);
  const [csvLoading, setCsvLoading]         = useState(false);

  // ── Effects ───────────────────────────────────────────────────────────
  useEffect(() => { fetchOverview(); }, [selectedSource]);

  useEffect(() => {
    if (activeTab === 'granular') {
      setPage(0);
      fetchGranular(0, search);
    }
  }, [selectedSource, activeTab]);

  // ── Overview data ─────────────────────────────────────────────────────
  const fetchOverview = async () => {
    setOverviewLoading(true);
    setCampaigns([]);
    setExpanded(new Set());
    try {
      const token = (await supabase.auth.getSession()).data.session?.access_token;
      const targetTable =
        selectedSource === 'B2B' ? 'business_partners' :
        selectedSource === 'B2C' ? 'customer_list' :
        'members_list';

      const [memberRes, analyticsRes, campaignRes] = await Promise.all([
        supabase.from(targetTable).select('*', { count: 'exact', head: true }),
        fetch(`/api/analytics/${selectedSource}?userId=${userId}`, {
          headers: {
            'Authorization': `Bearer ${token}`
          }
        }).then(r => r.json()),
        fetch(`/api/analytics/${selectedSource}/campaigns?userId=${userId}`, {
          headers: {
            'Authorization': `Bearer ${token}`
          }
        }).then(r => r.json()),
      ]);

      setStats({
        totalMembers: memberRes.count      || 0,
        totalSent:    analyticsRes.totalSent || analyticsRes.sent    || 0,
        totalOpens:   analyticsRes.totalOpens || analyticsRes.opens   || 0,
        totalClicks:  analyticsRes.totalClicks || analyticsRes.clicks  || 0,
      });
      setCampaigns(campaignRes.campaigns || []);
    } catch (err) {
      console.error('Dashboard fetch error:', (err as Error).message);
    } finally {
      setOverviewLoading(false);
    }
  };

  // ── Granular data ─────────────────────────────────────────────────────
  const fetchGranular = useCallback(async (pageNum: number, searchTerm: string) => {
    setGranularLoading(true);
    try {
      const token = (await supabase.auth.getSession()).data.session?.access_token;
      const params = new URLSearchParams({
        limit:  String(PAGE_SIZE),
        offset: String(pageNum * PAGE_SIZE),
        ...(searchTerm ? { search: searchTerm } : {}),
      });
      const res  = await fetch(`/api/analytics/${selectedSource}/granular?userId=${userId}&${params}`, {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });
      const data = await res.json();
      setGranularRows(data.rows  || []);
      setGranularTotal(data.total || 0);
    } catch (err) {
      console.error('[granular] fetch error:', err);
    } finally {
      setGranularLoading(false);
    }
  }, [selectedSource]);

  // Debounced search
  useEffect(() => {
    if (activeTab !== 'granular') return;
    const t = setTimeout(() => { setPage(0); fetchGranular(0, search); }, 400);
    return () => clearTimeout(t);
  }, [search]);

  const handlePageChange = (newPage: number) => {
    setPage(newPage);
    fetchGranular(newPage, search);
  };

  // CSV — fetch up to 500 matching rows then download
  const handleDownloadCsv = async () => {
    setCsvLoading(true);
    try {
      const token = (await supabase.auth.getSession()).data.session?.access_token;
      const params = new URLSearchParams({
        limit: '500', offset: '0',
        ...(search ? { search } : {}),
      });
      const res  = await fetch(`/api/analytics/${selectedSource}/granular?userId=${userId}&${params}`, {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });
      const data = await res.json();
      downloadCSV(data.rows || [], selectedSource);
    } catch (err) {
      console.error('[csv export] error:', err);
    } finally {
      setCsvLoading(false);
    }
  };

  // ── UI helpers ────────────────────────────────────────────────────────
  const toggleExpand = (subject: string) => {
    setExpanded(prev => {
      const next = new Set(prev);
      next.has(subject) ? next.delete(subject) : next.add(subject);
      return next;
    });
  };

  const accentColor   = selectedSource === 'BNP' ? 'blue' : selectedSource === 'B2B' ? 'indigo' : 'green';
  const accentClasses: Record<string, string> = {
    blue: 'bg-blue-600', indigo: 'bg-indigo-600', green: 'bg-green-600',
  };

  const totalPages = Math.ceil(granularTotal / PAGE_SIZE);

  const sourceBtn = (src: 'BNP' | 'B2B' | 'B2C') => {
    const active = selectedSource === src;
    const color  = src === 'BNP' ? 'bg-blue-600' : src === 'B2B' ? 'bg-indigo-600' : 'bg-green-600';
    return (
      <button key={src}
        onClick={() => { setSelectedSource(src); setPage(0); setSearch(''); }}
        className={`px-4 py-2 rounded-lg text-sm font-bold transition ${active ? `${color} text-white shadow-sm` : 'text-slate-500 hover:bg-slate-200'}`}
      >{src}</button>
    );
  };

  // ── Render ────────────────────────────────────────────────────────────
  return (
    <div className="space-y-8 animate-in fade-in duration-500">

      {/* ── Page header ── */}
      <div className="flex flex-col md:flex-row md:items-end justify-between gap-4">
        <div>
          <h2 className="text-4xl font-serif italic text-slate-800">Campaign Analytics</h2>
          <p className="text-slate-500 mt-1">Real-time engagement metrics for your campaigns.</p>
        </div>

        <div className="flex gap-4 items-center">
          {/* Source switcher */}
          <div className="flex bg-slate-100 p-1 rounded-xl">
            {(['BNP', 'B2B', 'B2C'] as const).map(sourceBtn)}
          </div>

          {activeTab === 'overview' && (
            <button onClick={fetchOverview} disabled={overviewLoading}
              className="bg-slate-800 text-white px-4 py-2 rounded-lg font-medium hover:bg-slate-900 flex items-center gap-2 transition-colors disabled:opacity-60"
            >
              <RefreshCw size={15} className={overviewLoading ? 'animate-spin' : ''} />
              {overviewLoading ? 'Refreshing…' : 'Refresh Data'}
            </button>
          )}
        </div>
      </div>

{/* ── Tab switcher ── */}
<div className="sticky top-[64px] z-40 bg-white border-b border-slate-100 py-3 -mx-4 md:-mx-8 px-4 md:px-8">
  <div className="flex bg-slate-100 p-1 rounded-xl w-fit shadow-sm">
    <button
      onClick={() => setActiveTab('overview')}
      className={`px-5 py-2 rounded-lg text-sm transition ${activeTab === 'overview' ? 'bg-white text-slate-800 shadow-sm font-bold' : 'text-slate-600 hover:text-slate-900'}`}
    >
      Overview
    </button>
    <button
      onClick={() => setActiveTab('granular')}
      className={`px-5 py-2 rounded-lg text-sm transition ${activeTab === 'granular' ? 'bg-white text-slate-800 shadow-sm font-bold' : 'text-slate-600 hover:text-slate-900'}`}
    >
      Recipient Detail
    </button>
  </div>
</div>
      {/* ════════════════════════════════════════
          OVERVIEW TAB
      ════════════════════════════════════════ */}
      {activeTab === 'overview' && (
        <>
          {/* Stats cards */}
          <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
            <div className="bg-white p-8 rounded-[2rem] shadow-sm border border-gray-100 relative overflow-hidden">
              <div className="absolute top-4 right-4 text-[10px] font-bold bg-gray-100 text-gray-500 px-2 py-1 rounded-full uppercase tracking-tighter">~ Network Size</div>
              <div className="bg-slate-50 w-12 h-12 rounded-2xl flex items-center justify-center mb-4"><Users className="text-slate-600" size={24} /></div>
              <p className="text-gray-400 font-bold text-xs uppercase tracking-widest">Total Members</p>
              <p className="text-5xl font-bold mt-2 text-slate-900">{overviewLoading ? '…' : stats.totalMembers}</p>
            </div>
            <div className="bg-white p-8 rounded-[2rem] shadow-sm border border-gray-100 relative">
              <div className="absolute top-4 right-4 text-[10px] font-bold bg-green-50 text-green-600 px-2 py-1 rounded-full uppercase tracking-tighter">~ Active</div>
              <div className="bg-blue-50 w-12 h-12 rounded-2xl flex items-center justify-center mb-4"><Send className="text-blue-600" size={24} /></div>
              <p className="text-gray-400 font-bold text-xs uppercase tracking-widest">Total Sent</p>
              <p className="text-5xl font-bold mt-2 text-slate-900">{overviewLoading ? '…' : stats.totalSent}</p>
            </div>
            <div className="bg-white p-8 rounded-[2rem] shadow-sm border border-gray-100 relative">
              <div className="absolute top-4 right-4 text-[10px] font-bold bg-green-50 text-green-600 px-2 py-1 rounded-full uppercase tracking-tighter">~ Active</div>
              <div className="bg-indigo-50 w-12 h-12 rounded-2xl flex items-center justify-center mb-4"><Mail className="text-indigo-600" size={24} /></div>
              <p className="text-gray-400 font-bold text-xs uppercase tracking-widest">Total Opens</p>
              <p className="text-5xl font-bold mt-2 text-slate-900">{overviewLoading ? '…' : stats.totalOpens}</p>
            </div>
            <div className="bg-white p-8 rounded-[2rem] shadow-sm border border-gray-100 relative">
              <div className="absolute top-4 right-4 text-[10px] font-bold bg-green-50 text-green-600 px-2 py-1 rounded-full uppercase tracking-tighter">~ Active</div>
              <div className="bg-purple-50 w-12 h-12 rounded-2xl flex items-center justify-center mb-4"><MousePointer2 className="text-purple-600" size={24} /></div>
              <p className="text-gray-400 font-bold text-xs uppercase tracking-widest">Total Clicks</p>
              <p className="text-5xl font-bold mt-2 text-slate-900">{overviewLoading ? '…' : stats.totalClicks}</p>
            </div>
          </div>

          {/* Campaign history accordion */}
          <div className="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
            <div className="px-6 py-4 border-b border-gray-100 flex items-center justify-between">
              <div>
                <h3 className="font-bold text-slate-800 text-lg">Campaign History</h3>
                <p className="text-slate-400 text-xs mt-0.5">Grouped by subject · expand a row to see individual send runs</p>
              </div>
              {!overviewLoading && campaigns.length > 0 && (
                <span className="text-xs font-bold bg-slate-100 text-slate-500 px-3 py-1 rounded-full">
                  {campaigns.length} subject{campaigns.length !== 1 ? 's' : ''}
                </span>
              )}
            </div>

            {overviewLoading && <div className="p-12 text-center text-slate-400 text-sm">Loading campaign history…</div>}

            {!overviewLoading && campaigns.length === 0 && (
              <div className="p-12 text-center text-slate-400 text-sm italic">
                No campaigns sent yet for {selectedSource}. Send your first blast to see history here.
              </div>
            )}

            {!overviewLoading && campaigns.map((campaign, idx) => {
              const isOpen    = expanded.has(campaign.subject);
              const openRate  = pct(campaign.totalOpens,  campaign.totalSent);
              const clickRate = pct(campaign.totalClicks, campaign.totalSent);
              return (
                <div key={campaign.subject} className={idx < campaigns.length - 1 ? 'border-b border-gray-100' : ''}>
                  <button onClick={() => toggleExpand(campaign.subject)}
                    className="w-full px-6 py-4 flex items-center gap-4 hover:bg-slate-50 transition text-left group"
                  >
                    <ChevronDown size={16} className={`text-slate-400 transition-transform duration-200 flex-shrink-0 ${isOpen ? 'rotate-180' : ''}`} />
                    <div className="flex-1 min-w-0">
                      <p className="font-semibold text-slate-800 truncate">{campaign.subject}</p>
                      <p className="text-xs text-slate-400 mt-0.5">
                        {campaign.instances.length} run{campaign.instances.length !== 1 ? 's' : ''} · most recent {fmtDate(campaign.instances[0]?.sentAt)}
                      </p>
                    </div>
                    <div className="flex items-center gap-3 flex-shrink-0 text-xs font-semibold">
                      <span className="flex items-center gap-1.5 bg-blue-50 text-blue-700 px-3 py-1.5 rounded-full">
                        <Send size={11} /> {campaign.totalSent}
                      </span>
                      <span className="flex items-center gap-1.5 bg-indigo-50 text-indigo-700 px-3 py-1.5 rounded-full">
                        <Mail size={11} /> {campaign.totalOpens} <span className="text-indigo-400 font-normal">({openRate})</span>
                      </span>
                      <span className="flex items-center gap-1.5 bg-purple-50 text-purple-700 px-3 py-1.5 rounded-full">
                        <MousePointer2 size={11} /> {campaign.totalClicks} <span className="text-purple-400 font-normal">({clickRate})</span>
                      </span>
                    </div>
                  </button>

                  {isOpen && (
                    <div className="bg-slate-50 border-t border-slate-100">
                      <div className="grid grid-cols-5 px-14 py-2 text-[10px] font-bold uppercase tracking-widest text-slate-400">
                        <span className="col-span-2">Send Date &amp; Time</span>
                        <span className="text-center">Sent</span>
                        <span className="text-center">Opens</span>
                        <span className="text-center">Clicks</span>
                      </div>
                      {campaign.instances.map((inst, i) => (
                        <div key={i} className="grid grid-cols-5 px-14 py-3 text-sm border-t border-slate-100 hover:bg-white transition items-center">
                          <span className="col-span-2 text-slate-600 font-medium">{fmtDate(inst.sentAt)}</span>
                          <span className="text-center">
                            <span className="bg-blue-100 text-blue-700 font-bold px-2.5 py-0.5 rounded-full text-xs">{inst.sent}</span>
                          </span>
                          <span className="text-center">
                            <span className="bg-indigo-100 text-indigo-700 font-bold px-2.5 py-0.5 rounded-full text-xs">
                              {inst.opens} <span className="font-normal text-indigo-400">· {pct(inst.opens, inst.sent)}</span>
                            </span>
                          </span>
                          <span className="text-center">
                            <span className="bg-purple-100 text-purple-700 font-bold px-2.5 py-0.5 rounded-full text-xs">
                              {inst.clicks} <span className="font-normal text-purple-400">· {pct(inst.clicks, inst.sent)}</span>
                            </span>
                          </span>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              );
            })}
          </div>

          {/* Engagement insight */}
          <div className="bg-blue-50/50 border border-blue-100 rounded-2xl p-6 flex items-start gap-4">
            <div className={`${accentClasses[accentColor]} p-2 rounded-lg text-white`}>
              <MousePointer2 size={20} />
            </div>
            <div>
              <h4 className="font-bold text-blue-900">Engagement Insight</h4>
              <p className="text-blue-800 text-sm">
                {stats.totalMembers > 0
                  ? `Your ${selectedSource} network has ${stats.totalMembers} contacts. ${
                      stats.totalSent > 0
                        ? `Across all campaigns, ${pct(stats.totalOpens, stats.totalSent)} open rate and ${pct(stats.totalClicks, stats.totalSent)} click rate.`
                        : 'No emails sent yet — head to the Campaign tab to start a blast.'
                    }`
                  : 'No contacts found. Add members in the list tabs to begin outreach.'}
              </p>
            </div>
          </div>
        </>
      )}

      {/* ════════════════════════════════════════
          RECIPIENT DETAIL TAB
      ════════════════════════════════════════ */}
      {activeTab === 'granular' && (
        <div className="space-y-4">

          {/* Toolbar */}
          <div className="flex flex-col md:flex-row gap-3 items-start md:items-center justify-between">

            {/* Search */}
            <div className="relative w-full md:w-80">
              <Search size={15} className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
              <input
                type="text"
                placeholder="Search by email address…"
                value={search}
                onChange={e => setSearch(e.target.value)}
                className="w-full pl-9 pr-4 py-2.5 rounded-xl border border-slate-200 bg-white text-sm text-slate-800 placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-200"
              />
            </div>

            <div className="flex items-center gap-3">
              <span className="text-sm text-slate-500">
                {granularLoading ? 'Loading…' : `${granularTotal.toLocaleString()} record${granularTotal !== 1 ? 's' : ''}`}
              </span>

              {/* Download CSV */}
              <button
                onClick={handleDownloadCsv}
                disabled={csvLoading || granularTotal === 0}
                className="flex items-center gap-2 bg-emerald-600 hover:bg-emerald-700 text-white text-sm font-bold px-4 py-2.5 rounded-xl transition disabled:opacity-50"
              >
                <Download size={14} />
                {csvLoading ? 'Exporting…' : 'Download CSV'}
              </button>

              {/* Refresh */}
              <button
                onClick={() => fetchGranular(page, search)}
                disabled={granularLoading}
                className="bg-slate-800 text-white px-4 py-2.5 rounded-xl font-medium hover:bg-slate-900 flex items-center gap-2 transition-colors disabled:opacity-60 text-sm"
              >
                <RefreshCw size={14} className={granularLoading ? 'animate-spin' : ''} />
                Refresh
              </button>
            </div>
          </div>

          {/* Data table */}
          <div className="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">

            {/* Column headers */}
            <div className="grid grid-cols-12 px-5 py-3 bg-slate-50 border-b border-slate-100 text-[10px] font-bold uppercase tracking-widest text-slate-400">
              <span className="col-span-3">Recipient</span>
              <span className="col-span-3">Subject</span>
              <span className="col-span-2">Sent</span>
              <span className="col-span-2 text-center">Opened</span>
              <span className="col-span-2 text-center">Clicked</span>
            </div>

            {granularLoading && (
              <div className="p-12 text-center text-slate-400 text-sm">Loading records…</div>
            )}

            {!granularLoading && granularRows.length === 0 && (
              <div className="p-12 text-center text-slate-400 text-sm italic">
                {search
                  ? `No results for "${search}". Try a different search term.`
                  : `No send records found for ${selectedSource}.`}
              </div>
            )}

            {!granularLoading && granularRows.map((row, i) => (
              <div key={i}
                className="grid grid-cols-12 px-5 py-3.5 border-b border-slate-50 last:border-0 hover:bg-slate-50/60 transition text-sm items-center"
              >
                {/* Recipient email */}
                <span className="col-span-3 font-medium text-slate-700 truncate pr-3" title={row.recipient_email}>
                  {row.recipient_email}
                </span>

                {/* Subject */}
                <span className="col-span-3 text-slate-500 truncate pr-3" title={row.subject}>
                  {row.subject || '—'}
                </span>

                {/* Sent at */}
                <span className="col-span-2 text-slate-400 text-xs leading-snug">
                  {row.sent_at ? fmtShort(row.sent_at) : '—'}
                </span>

                {/* Opened */}
                <span className="col-span-2 flex flex-col items-center gap-0.5">
                  {(row.opened || row.clicked) ? (
                    <>
                      <CheckCircle2 size={17} className="text-emerald-500" />
                      <span className="text-[10px] text-slate-400 text-center leading-tight">
                        {row.opened_at ? fmtShort(row.opened_at) : (row.clicked_at ? fmtShort(row.clicked_at) : '')}
                      </span>
                    </>
                  ) : (
                    <XCircle size={17} className="text-slate-200" />
                  )}
                </span>

                {/* Clicked */}
                <span className="col-span-2 flex flex-col items-center gap-0.5">
                  {row.clicked ? (
                    <>
                      <CheckCircle2 size={17} className="text-blue-500" />
                      <span className="text-[10px] text-slate-400 text-center leading-tight">
                        {row.clicked_at ? fmtShort(row.clicked_at) : ''}
                      </span>
                      {row.url_clicked && (
                        <a href={row.url_clicked} target="_blank" rel="noopener noreferrer"
                          title={row.url_clicked}
                          className="text-[10px] text-blue-500 underline flex items-center gap-0.5 hover:text-blue-700"
                        >
                          <ExternalLink size={9} /> link
                        </a>
                      )}
                    </>
                  ) : (
                    <XCircle size={17} className="text-slate-200" />
                  )}
                </span>
              </div>
            ))}
          </div>

          {/* Pagination */}
          {totalPages > 1 && (
            <div className="flex items-center justify-between">
              <span className="text-sm text-slate-500">
                Page {page + 1} of {totalPages} &nbsp;·&nbsp;
                showing {(page * PAGE_SIZE + 1).toLocaleString()}–{Math.min((page + 1) * PAGE_SIZE, granularTotal).toLocaleString()} of {granularTotal.toLocaleString()}
              </span>
              <div className="flex gap-2">
                <button onClick={() => handlePageChange(page - 1)} disabled={page === 0}
                  className="px-4 py-2 bg-slate-100 hover:bg-slate-200 text-slate-700 rounded-lg text-sm font-medium disabled:opacity-40 transition"
                >← Prev</button>
                <button onClick={() => handlePageChange(page + 1)} disabled={page >= totalPages - 1}
                  className="px-4 py-2 bg-slate-100 hover:bg-slate-200 text-slate-700 rounded-lg text-sm font-medium disabled:opacity-40 transition"
                >Next →</button>
              </div>
            </div>
          )}

          {/* Tip */}
          <p className="text-xs text-slate-400">
            Open and click tracking begins after the first send with tracking enabled (APP_BASE_URL set in your .env).
            Older sends before tracking was activated will show no open/click data.
          </p>
        </div>
      )}

      <footer className="text-[10px] text-gray-300 mt-10">File Version: {APP_VERSION}</footer>
    </div>
  );
};

export default Dashboard;
