/**
 * @license
 * SPDX-License-Identifier: Apache-2.0
 */

import React, { useMemo, useState } from 'react';
import {
  IndianRupee,
  ShoppingBag,
  TrendingUp,
  Download,
  Calendar,
  MapPin,
  Loader2,
  ChevronLeft,
  ChevronRight,
  TrendingDown
} from 'lucide-react';
import {
  useFiestaAllOrders,
  useFiestaSalesSummary
} from '../services/fiestaQueries';
import { FIESTA_TENANT_ID, num as fnum, str as fstr, ymd, type Row } from '../services/fiestaApi';


// ... inside the component ...
import { shortTime } from '../services/fiestaMappers';
import {
  KpiStrip, Pill, FilterBar, TH_STYLE,
  BRAND, BRAND_LIGHT, TEXT, TEXT_2, TEXT_3, BORDER, DIVIDER, SURFACE_ALT,
  tint, soft, edge, ring
} from './consoleUi';
import { ResponsiveContainer, AreaChart, Area, BarChart, Bar, PieChart, Pie, Cell, XAxis, YAxis, Tooltip as RechartsTooltip, CartesianGrid } from 'recharts';

interface SalesRevenueReportProps {
  locationid?: number;
  tenantId?: number;
}

const PAGE_SIZE = 20;

export default function SalesRevenueReport({
  locationid,
  tenantId = FIESTA_TENANT_ID,
}: SalesRevenueReportProps) {
  const today = new Date();
  const monthStart = new Date(today.getFullYear(), today.getMonth(), 1);
  const todayStr = ymd(today);

  const dayOffset = (n: number) => { const d = new Date(); d.setDate(d.getDate() - n); return ymd(d); };
  
  const presets = [
    { key: 'today', label: 'Today', from: todayStr, to: todayStr },
    { key: '7d', label: 'Last 7 Days', from: dayOffset(6), to: todayStr },
    { key: '30d', label: 'Last 30 Days', from: dayOffset(29), to: todayStr },
    { key: 'month', label: 'This Month', from: ymd(monthStart), to: todayStr },
  ];

  const [fromdate, setFromdate] = useState(presets[1].from);
  const [todate, setTodate] = useState(todayStr);
  const [pageno, setPageno] = useState(1);
  const [storeFilter, setStoreFilter] = useState<string>('All');

  const activePreset = presets.find((p) => p.from === fromdate && p.to === todate)?.key ?? 'custom';

  // ── Queries ──────────────────────────────────────────────────────────────────
  const salesSummaryQ = useFiestaSalesSummary({ tenantid: tenantId, fromdate, todate, locationid });
  const allOrdersQ = useFiestaAllOrders({ tenantid: tenantId, fromdate, todate, locationid });
  const allRows = allOrdersQ.data || [];

  // ── Calculations ─────────────────────────────────────────────────────────────
  const salesData = salesSummaryQ.data;
  const totalRevenue = salesData?.totalRevenue ?? 0;
  const totalOrders = salesData?.totalOrders ?? 0;
  const aov = salesData?.averageOrderValue ?? 0;
  const chartData = salesData?.chartData ?? [];
  const backendTopLocations = salesData?.topLocations ?? [];

  // Filter only delivered orders for client-side stats (retention, hourly, etc.)
  const completedOrders = useMemo(() => {
    return allRows.filter((r) => {
      const s = fstr(r.orderstatus).toLowerCase();
      return s === 'delivered' || s === 'completed';
    });
  }, [allRows]);

  const formatLabel = (key: string) => {
    const d = new Date(key);
    const months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
    return `${d.getDate()} ${months[d.getMonth()]}`;
  };

  // 1. Customer Retention
  const { uniqueCustomers, repeatCustomers } = useMemo(() => {
    const custCount = new Map<string, number>();
    for (const r of completedOrders) {
      if (locationid) {
        const rLoc = fnum(r.locationid);
        const rApp = fnum(r.applocationid);
        if (rLoc !== locationid && rApp !== locationid) continue;
      }
      const custStr = fstr(r.deliverycustomer) || fstr(r.pickupcustomer) || fstr(r.customerphone) || fstr(r.tenantname);
      if (custStr) {
        custCount.set(custStr, (custCount.get(custStr) || 0) + 1);
      }
    }
    let repeat = 0;
    for (const cnt of custCount.values()) {
      if (cnt > 1) repeat++;
    }
    return { uniqueCustomers: custCount.size, repeatCustomers: repeat };
  }, [completedOrders, locationid]);

  // 2. Hourly peak
  const hourlyData = useMemo(() => {
    const hours = new Array(24).fill(0).map((_, i) => ({ hour: `${String(i).padStart(2, '0')}:00`, orders: 0 }));
    for (const r of completedOrders) {
      if (locationid) {
        const rLoc = fnum(r.locationid);
        const rApp = fnum(r.applocationid);
        if (rLoc !== locationid && rApp !== locationid) continue;
      }
      const d = fstr(r.orderdate) || fstr(r.deliverydate);
      if (d) {
        const h = new Date(d).getHours();
        if (!isNaN(h)) {
          hours[h].orders += 1;
        }
      }
    }
    return hours.filter(h => h.orders > 0 || (parseInt(h.hour) >= 8 && parseInt(h.hour) <= 20));
  }, [completedOrders, locationid]);

  // 3. Payment Split
  const paymentData = useMemo(() => {
    const pmap = new Map<string, number>();
    for (const r of completedOrders) {
      if (locationid) {
        const rLoc = fnum(r.locationid);
        const rApp = fnum(r.applocationid);
        if (rLoc !== locationid && rApp !== locationid) continue;
      }
      const p = (fstr(r.paymentmode) || fstr(r.paymenttype) || 'CASH').toUpperCase();
      const cleanP = p.includes('UPI') ? 'UPI' : p.includes('CARD') ? 'CARD' : p;
      pmap.set(cleanP, (pmap.get(cleanP) || 0) + 1);
    }
    const colors = ['#6366f1', '#10b981', '#f59e0b', '#ec4899', '#8b5cf6'];
    return Array.from(pmap.entries()).map(([name, value], i) => ({
      name, value, color: colors[i % colors.length]
    }));
  }, [completedOrders, locationid]);

  // 4. Top Locations Leaderboard (Admin Only)
  const topLocations = backendTopLocations.length > 0 
    ? backendTopLocations.map(l => ({ name: l.locationname, revenue: l.revenue }))
    : [];

  const kpis = [
    { label: 'Total Sales', value: totalOrders.toLocaleString('en-IN'), color: '#6366f1', icon: <ShoppingBag size={20} />, badge: 'Completed orders' },
    { label: 'Total Revenue', value: `₹${totalRevenue.toLocaleString('en-IN')}`, color: '#10b981', icon: <IndianRupee size={20} />, badge: 'Total collected' },
    { label: 'Avg Order Value', value: `₹${Math.round(aov).toLocaleString('en-IN')}`, color: '#8b5cf6', icon: <TrendingUp size={20} />, badge: 'Per order' },
    { label: 'Unique Customers', value: uniqueCustomers.toLocaleString('en-IN'), color: '#f59e0b', icon: <TrendingDown size={20} />, badge: `${repeatCustomers} repeat` },
  ];

  // Table Data
  const tableRows = useMemo(() => {
    return completedOrders.filter(r => {
      if (locationid) {
        const rLoc = fnum(r.locationid);
        const rApp = fnum(r.applocationid);
        if (rLoc !== locationid && rApp !== locationid) return false;
      }
      if (storeFilter !== 'All') {
        const locStr = fstr(r.applocation) || fstr(r.locationname) || `Location ${fstr(r.locationid) || fstr(r.applocationid)}`;
        if (locStr !== storeFilter) return false;
      }
      return true;
    }).sort((a, b) => {
      const d1 = new Date(fstr(b.orderdate) || fstr(b.deliverydate)).getTime();
      const d2 = new Date(fstr(a.orderdate) || fstr(a.deliverydate)).getTime();
      return d1 - d2;
    });
  }, [completedOrders, locationid, storeFilter]);

  const uniqueStoreNames = useMemo(() => {
    const stores = new Set<string>();
    for (const r of completedOrders) {
      if (locationid) continue;
      const locStr = fstr(r.applocation) || fstr(r.locationname) || `Location ${fstr(r.locationid) || fstr(r.applocationid)}`;
      if (locStr) stores.add(locStr);
    }
    return Array.from(stores).sort();
  }, [completedOrders, locationid]);

  const pageRows = useMemo(
    () => tableRows.slice((pageno - 1) * PAGE_SIZE, pageno * PAGE_SIZE),
    [tableRows, pageno]
  );
  
  const hasNext = tableRows.length > pageno * PAGE_SIZE;

  // CSV export
  const exportCsv = () => {
    const headers = ['#', 'Order ID', 'Branch', 'Date', 'Customer', 'Qty', 'Payment', 'Amount (₹)'];
    const esc = (v: unknown) => `"${fstr(v).replace(/"/g, '""')}"`;
    const lines = tableRows.map((r, i) => [
      i + 1,
      fstr(r.orderid) || fstr(r.orderheaderid),
      fstr(r.applocation) || fstr(r.locationname),
      shortTime(r.orderdate || r.deliverydate),
      fstr(r.deliverycustomer) || fstr(r.pickupcustomer) || fstr(r.tenantname),
      fnum(r.quantity),
      (fstr(r.paymentmode) || fstr(r.paymenttype) || 'CASH').toUpperCase(),
      fnum(r.ordervalue) || fnum(r.orderamount) || fnum(r.deliveryamt),
    ].map(esc).join(','));
    const blob = new Blob([[headers.join(','), ...lines].join('\n')], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a'); a.href = url;
    a.download = `Sales_Revenue_${fromdate}_to_${todate}.csv`; a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div className="animate-in fade-in duration-300">


      <div className="mb-6"><KpiStrip items={kpis} loading={allOrdersQ.isLoading} /></div>

      <FilterBar className="mb-4">
        <div className="flex flex-col lg:flex-row lg:items-center justify-between gap-4">
          <div className="flex items-center gap-2 flex-wrap">
            <span className="hidden sm:inline-flex items-center gap-1.5 text-[10px] font-extrabold uppercase tracking-widest pr-1" style={{ color: TEXT_2 }}>
              <Calendar size={13} style={{ color: BRAND }} /> Period
            </span>
            {presets.map((p) => (
              <React.Fragment key={p.key}>
                <Pill active={activePreset === p.key} color={BRAND} onClick={() => { setFromdate(p.from); setTodate(p.to); setPageno(1); }}>
                  {p.label}
                </Pill>
              </React.Fragment>
            ))}
          </div>
          
          <div className="flex items-center gap-3 flex-wrap lg:justify-end min-w-0">
            <div className="flex items-center gap-1.5">
              <input type="date" value={fromdate} max={todate} onChange={(e) => { setFromdate(e.target.value); setPageno(1); }} className="rounded-full outline-none font-semibold text-xs transition-colors" style={{ padding: '6px 12px', border: `1.5px solid ${edge(BRAND)}`, background: tint(BRAND), color: BRAND }} />
              <span className="text-zinc-400 font-bold px-1 text-xs">—</span>
              <input type="date" value={todate} min={fromdate} max={todayStr} onChange={(e) => { setTodate(e.target.value); setPageno(1); }} className="rounded-full outline-none font-semibold text-xs transition-colors" style={{ padding: '6px 12px', border: `1.5px solid ${edge(BRAND)}`, background: tint(BRAND), color: BRAND }} />
            </div>
            <button
              onClick={exportCsv}
              disabled={tableRows.length === 0}
              title="Export to CSV"
              className="inline-flex items-center gap-1.5 rounded-full font-extrabold text-white cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed whitespace-nowrap shrink-0"
              style={{ padding: '8px 14px', fontSize: 12, background: `linear-gradient(135deg, ${BRAND}, ${BRAND_LIGHT})`, boxShadow: `0 6px 18px ${ring(BRAND)}` }}
            >
              <Download size={13} /> Export CSV
            </button>
          </div>
        </div>
      </FilterBar>

      <div className="grid grid-cols-1 xl:grid-cols-3 gap-6 mb-6">
        <div className="xl:col-span-3 bg-white rounded-2xl border border-slate-200 shadow-sm p-6 flex flex-col">
          <div className="flex items-center gap-2 mb-6">
            <TrendingUp size={18} className="text-emerald-500" />
            <h3 className="text-sm font-bold text-slate-900 tracking-tight uppercase">Revenue Trend</h3>
          </div>
          <div className="w-full h-72">
            {allOrdersQ.isLoading ? (
              <div className="w-full h-full flex items-center justify-center">
                <Loader2 size={24} className="animate-spin text-emerald-500" />
              </div>
            ) : chartData.length === 0 ? (
               <div className="w-full h-full flex items-center justify-center text-sm font-medium text-slate-500">No revenue data for this period.</div>
            ) : (
              <ResponsiveContainer width="100%" height="100%">
                <AreaChart data={chartData} margin={{ top: 10, right: 10, left: 0, bottom: 0 }}>
                  <defs>
                    <linearGradient id="colorRev" x1="0" y1="0" x2="0" y2="1">
                      <stop offset="5%" stopColor="#10b981" stopOpacity={0.2} />
                      <stop offset="95%" stopColor="#10b981" stopOpacity={0} />
                    </linearGradient>
                  </defs>
                  <CartesianGrid strokeDasharray="4 4" vertical={false} stroke="#e2e8f0" />
                  <XAxis dataKey="date" axisLine={false} tickLine={false} tick={{ fontSize: 11, fill: '#64748b', fontWeight: 500 }} dy={10} 
                    tickFormatter={formatLabel} />
                  <YAxis axisLine={false} tickLine={false} tick={{ fontSize: 11, fill: '#64748b', fontWeight: 500 }} dx={-10} tickFormatter={(v) => `₹${v.toLocaleString('en-IN')}`} />
                  <RechartsTooltip 
                    cursor={{ stroke: '#10b981', strokeWidth: 1, strokeDasharray: '4 4' }}
                    content={({ active, payload, label }: any) => {
                      if (active && payload && payload.length) {
                        return (
                          <div className="bg-white p-3 rounded-xl border border-slate-200 shadow-lg">
                            <p className="text-[10px] font-bold text-slate-400 uppercase tracking-wider mb-2">{formatLabel(label)}</p>
                            <div className="flex flex-col gap-1">
                              <span className="flex items-center gap-1.5 text-xs font-bold text-slate-600 capitalize">
                                <span className="w-2 h-2 rounded-full bg-emerald-500"></span>
                                Revenue
                              </span>
                              <span className="text-base font-black text-slate-900">
                                ₹{payload[0].value.toLocaleString('en-IN')}
                              </span>
                              <span className="text-[10px] text-slate-500 mt-1">
                                {payload[0].payload.orders} orders
                              </span>
                            </div>
                          </div>
                        );
                      }
                      return null;
                    }}
                  />
                  <Area type="monotone" dataKey="revenue" stroke="#10b981" strokeWidth={2.5} fillOpacity={1} fill="url(#colorRev)" activeDot={{ r: 5, strokeWidth: 2, stroke: '#fff', fill: '#10b981' }} />
                </AreaChart>
              </ResponsiveContainer>
            )}
          </div>
        </div>
      </div>

      <div className="grid grid-cols-1 xl:grid-cols-2 gap-6 mb-6">
        <div className="bg-white rounded-2xl border border-slate-200 shadow-sm p-6 flex flex-col">
          <div className="flex items-center gap-2 mb-6">
            <TrendingUp size={18} className="text-blue-500" />
            <h3 className="text-sm font-bold text-slate-900 tracking-tight uppercase">Hourly Sales Distribution</h3>
          </div>
          <div className="w-full h-64">
            {allOrdersQ.isLoading ? (
               <div className="w-full h-full flex items-center justify-center"><Loader2 size={24} className="animate-spin text-blue-500" /></div>
            ) : hourlyData.length === 0 ? (
               <div className="w-full h-full flex items-center justify-center text-sm font-medium text-slate-500">No data for this period.</div>
            ) : (
              <ResponsiveContainer width="100%" height="100%">
                <BarChart data={hourlyData} margin={{ top: 10, right: 10, left: -20, bottom: 0 }}>
                  <CartesianGrid strokeDasharray="4 4" vertical={false} stroke="#e2e8f0" />
                  <XAxis dataKey="hour" axisLine={false} tickLine={false} tick={{ fontSize: 11, fill: '#64748b', fontWeight: 500 }} dy={10} />
                  <YAxis axisLine={false} tickLine={false} tick={{ fontSize: 11, fill: '#64748b', fontWeight: 500 }} />
                  <RechartsTooltip cursor={{ fill: '#f1f5f9' }} content={({ active, payload, label }: any) => {
                    if (active && payload && payload.length) {
                      return (
                        <div className="bg-white p-3 rounded-xl border border-slate-200 shadow-lg">
                          <p className="text-[10px] font-bold text-slate-400 uppercase tracking-wider mb-2">{label}</p>
                          <span className="text-sm font-black text-slate-900">{payload[0].value} orders</span>
                        </div>
                      );
                    }
                    return null;
                  }} />
                  <Bar dataKey="orders" fill="#3b82f6" radius={[4, 4, 0, 0]} />
                </BarChart>
              </ResponsiveContainer>
            )}
          </div>
        </div>

        <div className="bg-white rounded-2xl border border-slate-200 shadow-sm p-6 flex flex-col">
          <div className="flex items-center gap-2 mb-6">
            <IndianRupee size={18} className="text-amber-500" />
            <h3 className="text-sm font-bold text-slate-900 tracking-tight uppercase">Payment Methods</h3>
          </div>
          <div className="w-full h-64">
            {allOrdersQ.isLoading ? (
               <div className="w-full h-full flex items-center justify-center"><Loader2 size={24} className="animate-spin text-amber-500" /></div>
            ) : paymentData.length === 0 ? (
               <div className="w-full h-full flex items-center justify-center text-sm font-medium text-slate-500">No payment data available.</div>
            ) : (
              <ResponsiveContainer width="100%" height="100%">
                <PieChart>
                  <Pie data={paymentData} cx="50%" cy="50%" innerRadius={60} outerRadius={80} paddingAngle={5} dataKey="value">
                    {paymentData.map((entry, index) => (
                      <Cell key={`cell-${index}`} fill={entry.color} />
                    ))}
                  </Pie>
                  <RechartsTooltip content={({ active, payload }: any) => {
                    if (active && payload && payload.length) {
                      return (
                        <div className="bg-white p-3 rounded-xl border border-slate-200 shadow-lg flex items-center gap-2">
                          <div className="w-3 h-3 rounded-full" style={{ backgroundColor: payload[0].payload.color }}></div>
                          <span className="text-sm font-bold text-slate-700">{payload[0].name}:</span>
                          <span className="text-sm font-black text-slate-900">{payload[0].value}</span>
                        </div>
                      );
                    }
                    return null;
                  }} />
                </PieChart>
              </ResponsiveContainer>
            )}
          </div>
        </div>
      </div>

      {!locationid && topLocations.length > 0 && (
        <div className="bg-white rounded-2xl border border-slate-200 shadow-sm p-6 mb-6">
           <div className="flex items-center gap-2 mb-6">
            <MapPin size={18} className="text-purple-600" />
            <h3 className="text-sm font-bold text-slate-900 tracking-tight uppercase">Top Locations by Revenue</h3>
          </div>
          <div className="grid grid-cols-1 md:grid-cols-5 gap-4">
            {topLocations.map((loc, i) => (
              <div key={i} className="p-4 rounded-xl border border-slate-100 bg-slate-50 flex flex-col gap-2">
                <span className="text-[10px] font-bold text-slate-400 uppercase tracking-wider line-clamp-1">{loc.name}</span>
                <span className="text-lg font-black text-slate-800">₹{loc.revenue.toLocaleString('en-IN')}</span>
              </div>
            ))}
          </div>
        </div>
      )}

      <div className="bg-white border rounded-2xl overflow-hidden" style={{ borderColor: BORDER }}>
        <div className="p-4 border-b bg-slate-50/50 flex flex-col sm:flex-row sm:items-center justify-between gap-4" style={{ borderColor: BORDER }}>
          <div className="flex items-center gap-2">
            <ShoppingBag size={16} className="text-slate-500" />
            <h3 className="text-sm font-bold text-slate-800">Completed Order Ledger</h3>
          </div>
          {!locationid && uniqueStoreNames.length > 0 && (
            <select
              value={storeFilter}
              onChange={(e) => { setStoreFilter(e.target.value); setPageno(1); }}
              className="text-xs font-bold outline-none rounded-lg px-3 py-1.5 border border-slate-200 bg-white text-slate-700 focus:ring-2 focus:ring-emerald-500 focus:border-transparent transition-all cursor-pointer"
            >
              <option value="All">All Stores</option>
              {uniqueStoreNames.map(store => (
                <option key={store} value={store}>{store}</option>
              ))}
            </select>
          )}
        </div>
        <div className="overflow-x-auto">
          <table className="w-full" style={{ minWidth: 800 }}>
            <thead>
              <tr>
                {['#', 'Order', 'Branch', 'Customer', 'Qty', 'Payment', 'Amount (₹)'].map((h, i) => (
                  <th key={i} className={`px-3 py-2.5 ${i === 6 ? 'text-right' : 'text-left'}`} style={TH_STYLE}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {allOrdersQ.isLoading ? (
                <tr><td colSpan={7} className="px-3 py-12 text-center" style={{ color: TEXT_3 }}>
                  <span className="inline-flex items-center gap-2 text-xs font-semibold">
                    <Loader2 size={15} className="animate-spin" style={{ color: BRAND }} /> Loading data…
                  </span>
                </td></tr>
              ) : pageRows.length === 0 ? (
                <tr><td colSpan={7} className="px-3 py-12 text-center text-xs" style={{ color: TEXT_3 }}>
                  No completed orders found for this date range.
                </td></tr>
              ) : (
                pageRows.map((r, i) => {
                  const amount = fnum(r.ordervalue) || fnum(r.orderamount) || fnum(r.deliveryamt);
                  return (
                    <tr
                      key={fstr(r.orderid) || fstr(r.orderheaderid) || i}
                      className="transition-colors align-top"
                      style={{ borderBottom: `1px solid ${DIVIDER}` }}
                      onMouseEnter={(e) => (e.currentTarget.style.background = SURFACE_ALT)}
                      onMouseLeave={(e) => (e.currentTarget.style.background = 'transparent')}
                    >
                      <td className="px-3 py-2.5 font-mono" style={{ color: TEXT_3 }}>{(pageno - 1) * PAGE_SIZE + i + 1}</td>
                      <td className="px-3 py-2.5">
                        <p className="font-extrabold font-mono text-[13px]" style={{ color: TEXT }}>{fstr(r.orderid) || `#${fstr(r.orderheaderid)}`}</p>
                        <p className="text-[10px]" style={{ color: TEXT_2 }}>{shortTime(r.orderdate || r.deliverydate)}</p>
                      </td>
                      <td className="px-3 py-2.5">
                        <span className="inline-flex items-center gap-1 font-bold text-[12px]" style={{ color: BRAND }}>
                          <MapPin size={11} /> {fstr(r.applocation) || fstr(r.locationname) || '—'}
                        </span>
                      </td>
                      <td className="px-3 py-2.5">
                        <p className="font-bold text-[12px] truncate max-w-[140px]" style={{ color: TEXT }}>{fstr(r.deliverycustomer) || fstr(r.pickupcustomer) || fstr(r.tenantname) || '—'}</p>
                      </td>
                      <td className="px-3 py-2.5 font-mono text-[12px]" style={{ color: TEXT }}>{fnum(r.quantity) || '—'}</td>
                      <td className="px-3 py-2.5">
                        <span className="inline-flex items-center px-1.5 py-0.5 rounded-full text-[10px] font-black tracking-wide bg-slate-100 text-slate-600">
                          {(fstr(r.paymentmode) || fstr(r.paymenttype) || 'CASH').toUpperCase()}
                        </span>
                      </td>
                      <td className="px-3 py-2.5 text-right font-mono text-[13px] font-bold text-emerald-600">
                        {amount > 0 ? `₹${amount.toLocaleString('en-IN')}` : '—'}
                      </td>
                    </tr>
                  );
                })
              )}
            </tbody>
          </table>
        </div>

        {/* Pagination */}
        <div className="flex items-center justify-between px-4 py-3 border-t" style={{ borderColor: BORDER, background: SURFACE_ALT }}>
          <span className="text-[10px] font-bold uppercase tracking-wider" style={{ color: TEXT_2 }}>
            Page {pageno} · {pageRows.length} of {tableRows.length} shown
          </span>
          <div className="flex items-center gap-2">
            <button disabled={pageno === 1} onClick={() => setPageno((p) => Math.max(1, p - 1))}
              className="inline-flex items-center gap-1 rounded-full font-bold transition-colors cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed"
              style={{ padding: '6px 12px', fontSize: 11, border: `1px solid ${BORDER}`, background: '#fff', color: TEXT_2 }}>
              <ChevronLeft size={13} /> Prev
            </button>
            <button disabled={!hasNext} onClick={() => setPageno((p) => p + 1)}
              className="inline-flex items-center gap-1 rounded-full font-bold transition-colors cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed"
              style={{ padding: '6px 12px', fontSize: 11, border: `1px solid ${BORDER}`, background: '#fff', color: TEXT_2 }}>
              Next <ChevronRight size={13} />
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
