'use client';

import { useState } from 'react';
import {
  TrendingDown,
  TrendingUp,
  Minus,
  AlertTriangle,
  DollarSign,
  Receipt,
  ShoppingBag,
  Users,
  UserPlus,
  UserCheck,
  Repeat,
  Package,
  PiggyBank,
  Wallet,
  Percent,
  LineChart,
  ListChecks,
  CreditCard,
  Boxes,
  FolderTree,
  MapPin,
  Ticket,
  RotateCcw,
  Warehouse,
  Star,
  ShoppingCart,
  Heart,
  CheckCircle2,
  XCircle,
  Clock,
  Ban,
  Layers,
  PackageX,
  PackageMinus,
  Tag,
  MessageSquare,
  Hourglass,
  Truck,
  type LucideIcon,
} from 'lucide-react';
import type { StoreReport } from '@/lib/reports/storeReport';
import { ColumnChart, EmptyState, ShareBars } from './ReportCharts';
import { human } from './ReportFilters';

type S = StoreReport['sections'];
type Fmt = (n: number | null | undefined) => string;

// ─── Colour tones ────────────────────────────────────────────────────────────
// The same gradient pairs the Dashboard's KPI cards use, so the two pages look
// like one product. `solid` is the chart/bar colour for a section in that tone.
const TONES = {
  amber: { from: '#F59E0B', to: '#D97706', solid: '#D97706' },
  green: { from: '#10B981', to: '#059669', solid: '#059669' },
  violet: { from: '#8B5CF6', to: '#6D28D9', solid: '#7C3AED' },
  cyan: { from: '#06B6D4', to: '#0891B2', solid: '#0891B2' },
  blue: { from: '#3B82F6', to: '#1D4ED8', solid: '#2563EB' },
  red: { from: '#EF4444', to: '#B91C1C', solid: '#DC2626' },
  pink: { from: '#EC4899', to: '#BE185D', solid: '#DB2777' },
  slate: { from: '#64748B', to: '#334155', solid: '#475569' },
  teal: { from: '#14B8A6', to: '#0F766E', solid: '#0D9488' },
  indigo: { from: '#6366F1', to: '#4338CA', solid: '#4F46E5' },
  orange: { from: '#FB923C', to: '#EA580C', solid: '#EA580C' },
} as const;
type Tone = keyof typeof TONES;
const gradient = (t: Tone) => `linear-gradient(135deg, ${TONES[t].from}, ${TONES[t].to})`;

const STATUS_COLORS: Record<string, string> = {
  pending: '#F59E0B',
  confirmed: '#3B82F6',
  shipped: '#8B5CF6',
  delivered: '#059669',
  cancelled: '#EF4444',
  returned: '#DC2626',
  refunded: '#F97316',
};

const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
function bucketLabel(b: string, groupBy: string, long = false): string {
  const [y, m, d] = b.split('-');
  const mon = MONTHS[Number(m) - 1] ?? m;
  if (groupBy === 'month') return `${mon} ${y}`;
  if (groupBy === 'week') return long ? `Week of ${mon} ${Number(d)}, ${y}` : `${mon} ${Number(d)}`;
  return long ? `${mon} ${Number(d)}, ${y}` : `${mon} ${Number(d)}`;
}
const intStr = (n: number) => Math.round(n).toLocaleString();
const pctStr = (n: number | null | undefined) => (n === null || n === undefined ? '—' : `${n}%`);

// ─── Building blocks ─────────────────────────────────────────────────────────

function Section({
  id,
  title,
  subtitle,
  icon: Icon,
  tone,
  children,
}: {
  id: string;
  title: string;
  subtitle?: string;
  icon: LucideIcon;
  tone: Tone;
  children: React.ReactNode;
}) {
  return (
    <section
      id={`report-${id}`}
      className="relative p-4 sm:p-5 rounded-xl scroll-mt-24 overflow-hidden"
      style={{ background: 'var(--color-surface)', border: '1px solid var(--color-border)' }}
    >
      {/* Thin tone strip along the top edge */}
      <div className="absolute inset-x-0 top-0 h-1" style={{ background: gradient(tone) }} />
      <div className="flex items-start gap-3 mb-5">
        <div
          className="w-10 h-10 rounded-xl flex items-center justify-center shrink-0 shadow-sm"
          style={{ background: gradient(tone), color: 'white' }}
        >
          <Icon size={20} />
        </div>
        <div className="min-w-0">
          <h2 className="text-base font-semibold leading-tight" style={{ color: 'var(--color-text)' }}>{title}</h2>
          {subtitle && <p className="text-xs mt-1" style={{ color: 'var(--color-text-secondary)' }}>{subtitle}</p>}
        </div>
      </div>
      {children}
    </section>
  );
}

function Sub({ title, tone, children }: { title: string; tone?: Tone; children: React.ReactNode }) {
  return (
    <div className="min-w-0">
      <h3 className="flex items-center gap-2 text-sm font-semibold mb-3" style={{ color: 'var(--color-text)' }}>
        <span className="w-1.5 h-4 rounded-full" style={{ background: tone ? gradient(tone) : 'var(--color-cta)' }} />
        {title}
      </h3>
      {children}
    </div>
  );
}

// Growth on a coloured card: white pill with an arrow and a sign, so the
// direction never depends on colour alone.
function Growth({ value }: { value: number | null | undefined }) {
  if (value === null || value === undefined) {
    return <span className="text-[11px] opacity-80">vs previous: n/a</span>;
  }
  const Icon = value > 0 ? TrendingUp : value < 0 ? TrendingDown : Minus;
  return (
    <span className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded-md text-[11px] font-semibold" style={{ background: 'rgba(255,255,255,0.22)' }}>
      <Icon size={12} /> {value > 0 ? '+' : ''}{value}% vs previous
    </span>
  );
}

function Kpi({
  label,
  value,
  note,
  growth,
  tone,
  icon: Icon,
}: {
  label: string;
  value: string;
  note?: React.ReactNode;
  growth?: number | null;
  tone: Tone;
  icon: LucideIcon;
}) {
  return (
    <div
      className="relative p-4 rounded-xl min-w-0 overflow-hidden group transition-all hover:shadow-lg hover:-translate-y-0.5"
      style={{ background: gradient(tone), color: 'white' }}
    >
      <div className="absolute top-3 right-3 opacity-20 group-hover:opacity-30 transition-opacity">
        <Icon size={44} />
      </div>
      <p className="relative text-[11px] font-medium uppercase tracking-wide truncate opacity-90">{label}</p>
      <p className="relative text-lg sm:text-2xl font-bold mt-1 truncate" title={value}>{value}</p>
      <div className="relative mt-1.5 min-h-[20px] text-[11px] truncate opacity-95">
        {growth !== undefined ? <Growth value={growth} /> : note}
      </div>
    </div>
  );
}

function KpiGrid({ children }: { children: React.ReactNode }) {
  return <div className="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-3">{children}</div>;
}

interface Col<R> { label: string; align?: 'left' | 'right'; cell: (r: R) => React.ReactNode }

function Table<R>({
  cols,
  rows,
  rowKey,
  empty,
  tone = 'slate',
}: {
  cols: Col<R>[];
  rows: R[];
  rowKey: (r: R, i: number) => string;
  empty?: string;
  tone?: Tone;
}) {
  if (rows.length === 0) return <EmptyState text={empty} />;
  return (
    <div className="overflow-x-auto rounded-lg" style={{ border: '1px solid var(--color-border)' }}>
      <table className="w-full text-sm">
        <thead>
          {/* 1A = ~10% alpha of the tone colour — tinted, still readable in dark mode */}
          <tr style={{ background: `${TONES[tone].solid}1A` }}>
            {cols.map((c) => (
              <th
                key={c.label}
                className={`py-2.5 px-3 text-[11px] font-semibold uppercase tracking-wide whitespace-nowrap ${c.align === 'right' ? 'text-right' : 'text-left'}`}
                style={{ color: TONES[tone].solid }}
              >
                {c.label}
              </th>
            ))}
          </tr>
        </thead>
        <tbody>
          {rows.map((r, i) => (
            <tr
              key={rowKey(r, i)}
              className="transition-colors hover:bg-[var(--color-surface-alt)]"
              style={{ borderTop: '1px solid var(--color-border)' }}
            >
              {cols.map((c) => (
                <td
                  key={c.label}
                  className={`py-2 px-3 whitespace-nowrap ${c.align === 'right' ? 'text-right tabular-nums' : 'text-left'}`}
                  style={{ color: 'var(--color-text)' }}
                >
                  {c.cell(r)}
                </td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

// Long names shouldn't blow the table width.
const Clip = ({ text, w = 'max-w-[16rem]' }: { text: string; w?: string }) => (
  <span className={`block truncate ${w}`} title={text}>{text}</span>
);

// Small coloured pill for statuses / types inside tables.
function Pill({ text, color }: { text: string; color: string }) {
  return (
    <span className="inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-xs font-medium" style={{ background: `${color}1F`, color }}>
      <span className="w-1.5 h-1.5 rounded-full" style={{ background: color }} />
      {text}
    </span>
  );
}

// Margin coloured by health — always shown with its number.
function Margin({ value }: { value: number | null }) {
  if (value === null) return <span style={{ color: 'var(--color-text-secondary)' }}>—</span>;
  const color = value >= 30 ? '#059669' : value >= 15 ? '#D97706' : '#DC2626';
  return <span className="font-semibold" style={{ color }}>{value}%</span>;
}

type BreakdownRow = [string, string, boolean?];
const breakdownCols: Col<BreakdownRow>[] = [
  { label: 'Line', cell: (r) => <span className={r[2] ? 'font-semibold' : ''}>{r[0]}</span> },
  { label: 'Amount', align: 'right', cell: (r) => <span className={r[2] ? 'font-bold' : ''}>{r[1]}</span> },
];

// ─── Sections ────────────────────────────────────────────────────────────────

const OPEN_STATUS_ICON: Record<string, LucideIcon> = { pending: Clock, confirmed: CheckCircle2, shipped: Truck };

// Money still to come — kept apart from revenue on purpose (revenue = delivered only).
function UpcomingPanel({ u, money }: { u: NonNullable<S['summary']>['upcoming']; money: Fmt }) {
  return (
    <div
      className="mt-4 p-4 sm:p-5 rounded-xl relative overflow-hidden"
      style={{ background: 'linear-gradient(135deg, #1E293B, #334155)', color: 'white' }}
    >
      <div className="absolute top-4 right-4 opacity-10"><Hourglass size={72} /></div>
      <div className="relative flex flex-col lg:flex-row lg:items-center gap-4 lg:gap-8">
        <div className="min-w-0">
          <p className="text-[11px] font-medium uppercase tracking-wide opacity-80">Upcoming revenue · not counted above</p>
          <p className="text-2xl sm:text-3xl font-bold mt-1">{money(u.total)}</p>
          <p className="text-xs mt-1 opacity-80">
            {u.orders} open order{u.orders === 1 ? '' : 's'} (pending, confirmed, shipped) — becomes revenue when delivered. All dates.
          </p>
        </div>
        <div className="grid grid-cols-2 gap-3 lg:ml-auto">
          <div className="px-3 py-2 rounded-lg" style={{ background: 'rgba(16,185,129,0.22)' }}>
            <p className="text-[11px] opacity-85">Advance already received</p>
            <p className="text-base font-bold">{money(u.advancePaid)}</p>
          </div>
          <div className="px-3 py-2 rounded-lg" style={{ background: 'rgba(245,158,11,0.25)' }}>
            <p className="text-[11px] opacity-85">Still to collect</p>
            <p className="text-base font-bold">{money(u.stillToCollect)}</p>
          </div>
        </div>
      </div>
      <div className="relative flex flex-wrap gap-2 mt-4">
        {u.byStatus.map((s) => {
          const Icon = OPEN_STATUS_ICON[s.status] ?? Clock;
          return (
            <span
              key={s.status}
              className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium"
              style={{ background: 'rgba(255,255,255,0.12)' }}
            >
              <Icon size={13} style={{ color: STATUS_COLORS[s.status] }} />
              {human(s.status)}: {s.orders} · {money(s.total)}
            </span>
          );
        })}
      </div>
    </div>
  );
}

function SummarySection({ x, money }: { x: NonNullable<S['summary']>; money: Fmt }) {
  const g = x.growth;
  const prev = x.previousRange;
  return (
    <Section
      id="summary"
      title="Sales Summary"
      icon={DollarSign}
      tone="amber"
      subtitle={`Revenue = delivered orders only, counted on their delivery date. ${prev ? `Growth compares with ${prev.startDate} – ${prev.endDate}.` : 'All time — no previous period to compare with.'}`}
    >
      <KpiGrid>
        <Kpi tone="amber" icon={DollarSign} label="Total revenue" value={money(x.totalRevenue)} growth={g ? g.totalRevenue : null} />
        <Kpi tone="green" icon={Receipt} label="Net sales" value={money(x.netSales)} growth={g ? g.netSales : null} />
        <Kpi tone="blue" icon={ShoppingBag} label="Orders" value={intStr(x.orders)} growth={g ? g.orders : null} />
        <Kpi tone="violet" icon={Wallet} label="Avg order value" value={money(x.avgOrderValue)} growth={g ? g.avgOrderValue : null} />
        <Kpi tone="cyan" icon={Users} label="Customers" value={intStr(x.customers)} growth={g ? g.customers : null} />
        <Kpi tone="pink" icon={Package} label="Items sold" value={intStr(x.itemsSold)} growth={g ? g.itemsSold : null} />
        <Kpi tone="teal" icon={PiggyBank} label="Gross profit" value={money(x.grossProfit)} note={`${x.grossMarginPct}% margin`} />
        <Kpi tone="indigo" icon={Percent} label="Net profit (est.)" value={money(x.netProfitEstimate)} note="after item & coupon discounts" />
      </KpiGrid>

      <UpcomingPanel u={x.upcoming} money={money} />

      {x.itemRevenue > 0 && x.costCoveragePct < 100 && (
        <p className="mt-3 flex items-start gap-1.5 text-xs px-3 py-2 rounded-lg" style={{ background: '#FEF3C7', color: '#92400E' }}>
          <AlertTriangle size={14} className="shrink-0 mt-px" />
          Cost price is set for only {x.costCoveragePct}% of item revenue — profit covers those items only. Add cost prices in Products for a full picture.
        </p>
      )}

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-5 mt-6">
        <Sub title="Revenue breakdown" tone="amber">
          <Table
            tone="amber"
            cols={breakdownCols}
            rowKey={(r) => r[0]}
            rows={[
              ['Gross sales (items)', money(x.grossSales)],
              ['Item discounts', `− ${money(x.itemDiscounts)}`],
              ['Coupon discounts', `− ${money(x.couponDiscounts)}`],
              ['Net sales', money(x.netSales), true],
              ['Delivery fees', `+ ${money(x.deliveryFees)}`],
              ['Tax collected', `+ ${money(x.tax)}`],
              ['Total revenue', money(x.totalRevenue), true],
              ['Refunds issued (recorded in period)', `− ${money(x.refundsIssued)}`],
              ['Revenue after refunds', money(x.netRevenueAfterRefunds), true],
            ]}
          />
        </Sub>
        <Sub title="Profit & cash" tone="teal">
          <Table
            tone="teal"
            cols={breakdownCols}
            rowKey={(r) => r[0]}
            rows={[
              ['Item revenue with a cost price', money(x.revenueWithCost)],
              ['Cost of goods sold', `− ${money(x.costOfGoods)}`],
              ['Gross profit', `${money(x.grossProfit)} (${x.grossMarginPct}%)`, true],
              ['Net profit estimate', money(x.netProfitEstimate), true],
              ['Payments received (recorded in period)', money(x.paymentsReceived)],
              [`Delivered, payment not marked received (${x.unpaidOrders})`, money(x.unpaidAmount)],
              ['Avg items per order', String(x.avgItemsPerOrder)],
            ]}
          />
        </Sub>
      </div>
    </Section>
  );
}

type TrendMetric = 'total' | 'net' | 'orders' | 'items';
const TREND_TONE: Record<TrendMetric, Tone> = { total: 'amber', net: 'green', orders: 'blue', items: 'pink' };

function TrendSection({ x, money }: { x: NonNullable<S['trend']>; money: Fmt }) {
  const [metric, setMetric] = useState<TrendMetric>('total');
  const [showTable, setShowTable] = useState(false);
  const isMoney = metric === 'total' || metric === 'net';
  const fmt = (n: number) => (isMoney ? money(n) : intStr(n));
  const metricLabel: Record<TrendMetric, string> = { total: 'Revenue', net: 'Net sales', orders: 'Orders', items: 'Items sold' };
  const withOrders = x.points.filter((p) => p.orders > 0);
  const tone = TREND_TONE[metric];

  return (
    <Section id="trend" title="Sales Trend" icon={LineChart} tone="blue" subtitle={`Delivered revenue per ${x.groupBy}, by delivery date. Periods with nothing delivered show as zero.`}>
      <div className="flex flex-wrap items-center gap-1.5 mb-3">
        {(Object.keys(metricLabel) as TrendMetric[]).map((m) => (
          <button
            key={m}
            type="button"
            onClick={() => setMetric(m)}
            className="px-3 py-1.5 rounded-lg text-xs font-semibold transition-all"
            style={
              metric === m
                ? { background: gradient(TREND_TONE[m]), color: 'white', boxShadow: '0 2px 6px rgba(0,0,0,0.15)' }
                : { background: 'var(--color-surface-alt)', color: 'var(--color-text-secondary)', border: '1px solid var(--color-border)' }
            }
          >
            {metricLabel[m]}
          </button>
        ))}
        <button
          type="button"
          onClick={() => setShowTable((v) => !v)}
          className="ml-auto px-3 py-1.5 rounded-lg text-xs font-medium"
          style={{ border: '1px solid var(--color-border)', color: 'var(--color-text)' }}
        >
          {showTable ? 'Hide table' : 'Show table'}
        </button>
      </div>

      <div className="p-3 rounded-xl" style={{ background: `${TONES[tone].solid}0D` }}>
        <ColumnChart
          ariaLabel={`${metricLabel[metric]} per ${x.groupBy}`}
          formatValue={fmt}
          color={TONES[tone].solid}
          points={x.points.map((p) => ({
            key: p.bucket,
            label: bucketLabel(p.bucket, x.groupBy),
            title: bucketLabel(p.bucket, x.groupBy, true),
            value: p[metric],
            detail: `${p.orders} order${p.orders === 1 ? '' : 's'}`,
          }))}
        />
      </div>

      {showTable && (
        <div className="mt-4">
          <Table
            tone="blue"
            rows={withOrders}
            rowKey={(p) => p.bucket}
            empty="No orders in this period"
            cols={[
              { label: human(x.groupBy), cell: (p) => bucketLabel(p.bucket, x.groupBy, true) },
              { label: 'Orders', align: 'right', cell: (p) => intStr(p.orders) },
              { label: 'Items', align: 'right', cell: (p) => intStr(p.items) },
              { label: 'Gross', align: 'right', cell: (p) => money(p.gross) },
              { label: 'Discounts', align: 'right', cell: (p) => money(p.discounts) },
              { label: 'Net', align: 'right', cell: (p) => money(p.net) },
              { label: 'Tax', align: 'right', cell: (p) => money(p.tax) },
              { label: 'Delivery', align: 'right', cell: (p) => money(p.delivery) },
              { label: 'Total', align: 'right', cell: (p) => <strong>{money(p.total)}</strong> },
            ]}
          />
        </div>
      )}

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-5 mt-6">
        <Sub title="Orders by day of week (when placed)" tone="violet">
          <div className="p-3 rounded-xl" style={{ background: `${TONES.violet.solid}0D` }}>
            <ColumnChart
              height={140}
              color={TONES.violet.solid}
              ariaLabel="Orders by day of week"
              formatValue={(n) => `${intStr(n)} order${n === 1 ? '' : 's'}`}
              points={x.byWeekday.map((d) => ({ key: d.day, label: d.day.slice(0, 3), title: d.day, value: d.orders, detail: money(d.total) }))}
            />
          </div>
        </Sub>
        <Sub title="Orders by hour of day (when placed)" tone="cyan">
          <div className="p-3 rounded-xl" style={{ background: `${TONES.cyan.solid}0D` }}>
            <ColumnChart
              height={140}
              color={TONES.cyan.solid}
              ariaLabel="Orders by hour of day"
              formatValue={(n) => `${intStr(n)} order${n === 1 ? '' : 's'}`}
              points={x.byHour.map((h) => ({
                key: String(h.hour),
                label: h.hour % 6 === 0 ? `${String(h.hour).padStart(2, '0')}h` : '',
                title: `${String(h.hour).padStart(2, '0')}:00 – ${String(h.hour).padStart(2, '0')}:59`,
                value: h.orders,
                detail: money(h.total),
              }))}
            />
          </div>
        </Sub>
      </div>
    </Section>
  );
}

function StatusSection({ x, money }: { x: NonNullable<S['status']>; money: Fmt }) {
  return (
    <Section id="status" title="Order Status" icon={ListChecks} tone="violet" subtitle="Every status is shown here, whatever the status filter.">
      <KpiGrid>
        <Kpi tone="slate" icon={ShoppingBag} label="All orders" value={intStr(x.totalOrders)} note={`${x.openOrders} still open`} />
        <Kpi tone="green" icon={CheckCircle2} label="Delivered rate" value={pctStr(x.deliveredRatePct)} />
        <Kpi tone="red" icon={Ban} label="Cancellation rate" value={pctStr(x.cancellationRatePct)} />
        <Kpi tone="orange" icon={RotateCcw} label="Return / refund rate" value={pctStr(x.returnRatePct)} />
      </KpiGrid>
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-5 mt-6">
        <ShareBars
          rows={x.rows.filter((r) => r.orders > 0).map((r) => ({
            key: r.status, label: human(r.status), value: `${r.orders} orders`, pct: r.sharePct, accent: STATUS_COLORS[r.status],
          }))}
        />
        <Table
          tone="violet"
          rows={x.rows}
          rowKey={(r) => r.status}
          cols={[
            { label: 'Status', cell: (r) => <Pill text={human(r.status)} color={STATUS_COLORS[r.status] ?? '#64748B'} /> },
            { label: 'Orders', align: 'right', cell: (r) => intStr(r.orders) },
            { label: 'Share', align: 'right', cell: (r) => pctStr(r.sharePct) },
            { label: 'Order value', align: 'right', cell: (r) => money(r.total) },
          ]}
        />
      </div>
    </Section>
  );
}

function PaymentsSection({ x, money }: { x: NonNullable<S['payments']>; money: Fmt }) {
  const cols: Col<(typeof x.byMethod)[number]>[] = [
    { label: 'Name', cell: (r) => human(r.key) },
    { label: 'Orders', align: 'right', cell: (r) => intStr(r.orders) },
    { label: 'Share', align: 'right', cell: (r) => pctStr(r.sharePct) },
    { label: 'Order value', align: 'right', cell: (r) => money(r.total) },
  ];
  const rec = x.recorded;
  return (
    <Section id="payments" title="Payments" icon={CreditCard} tone="cyan">
      <KpiGrid>
        <Kpi tone="green" icon={CheckCircle2} label="Received" value={money(rec.received.amount)} note={`${rec.received.count} entries in period`} />
        <Kpi tone="amber" icon={Clock} label="Pending" value={money(rec.pending.amount)} note={`${rec.pending.count} entries in period`} />
        <Kpi tone="red" icon={XCircle} label="Failed" value={money(rec.failed.amount)} note={`${rec.failed.count} entries in period`} />
        <Kpi tone="orange" icon={RotateCcw} label="Refunded" value={money(rec.refunded.amount)} note={`${rec.refunded.count} entries in period`} />
      </KpiGrid>
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-5 mt-6">
        <Sub title="By payment method" tone="cyan">
          <ShareBars color={TONES.cyan.solid} rows={x.byMethod.map((r) => ({ key: r.key, label: human(r.key), value: money(r.total), pct: r.sharePct }))} />
          <div className="mt-4"><Table tone="cyan" rows={x.byMethod} rowKey={(r) => r.key} cols={cols} /></div>
        </Sub>
        <Sub title="By payment status" tone="blue">
          <ShareBars color={TONES.blue.solid} rows={x.byStatus.map((r) => ({ key: r.key, label: human(r.key), value: money(r.total), pct: r.sharePct }))} />
          <div className="mt-4"><Table tone="blue" rows={x.byStatus} rowKey={(r) => r.key} cols={cols} /></div>
        </Sub>
      </div>
    </Section>
  );
}

function ProductsSection({ x, money, topN }: { x: NonNullable<S['products']>; money: Fmt; topN: number }) {
  return (
    <Section
      id="products"
      title="Product Performance"
      icon={Boxes}
      tone="pink"
      subtitle={`Top ${Math.min(topN, x.totalProducts)} of ${x.totalProducts} products sold, by revenue. Profit uses the current cost price.`}
    >
      <Table
        tone="pink"
        rows={x.rows}
        rowKey={(r) => r.productId ?? r.name}
        empty="No products sold in this period"
        cols={[
          { label: 'Product', cell: (r) => <Clip text={r.name} /> },
          { label: 'SKU', cell: (r) => <span className="font-mono text-xs" style={{ color: 'var(--color-text-secondary)' }}>{r.sku || '—'}</span> },
          { label: 'Qty', align: 'right', cell: (r) => intStr(r.qty) },
          { label: 'Orders', align: 'right', cell: (r) => intStr(r.orders) },
          { label: 'Revenue', align: 'right', cell: (r) => <strong>{money(r.revenue)}</strong> },
          {
            label: 'Share',
            align: 'right',
            cell: (r) => (
              <span className="inline-flex items-center gap-2 justify-end">
                <span className="hidden sm:inline-block w-14 h-1.5 rounded-full overflow-hidden" style={{ background: 'var(--color-surface-alt)' }}>
                  <span className="block h-full rounded-full" style={{ width: `${Math.min(r.sharePct, 100)}%`, background: TONES.pink.solid }} />
                </span>
                {pctStr(r.sharePct)}
              </span>
            ),
          },
          { label: 'Profit', align: 'right', cell: (r) => money(r.profit) },
          { label: 'Margin', align: 'right', cell: (r) => <Margin value={r.marginPct} /> },
          { label: 'Returns', align: 'right', cell: (r) => (r.returnedQty ? <span style={{ color: '#DC2626' }}>{r.returnedQty} ({r.returnRatePct}%)</span> : '0') },
          { label: 'Stock', align: 'right', cell: (r) => (r.stock === null ? '—' : intStr(r.stock)) },
        ]}
      />
    </Section>
  );
}

function CategoriesSection({ x, money }: { x: NonNullable<S['categories']>; money: Fmt }) {
  return (
    <Section id="categories" title="Category Performance" icon={FolderTree} tone="indigo">
      <div className="grid grid-cols-1 lg:grid-cols-5 gap-5">
        <div className="lg:col-span-2">
          <ShareBars color={TONES.indigo.solid} rows={x.rows.map((r) => ({ key: r.name, label: r.name, value: money(r.revenue), pct: r.sharePct }))} />
        </div>
        <div className="lg:col-span-3">
          <Table
            tone="indigo"
            rows={x.rows}
            rowKey={(r) => r.name}
            cols={[
              { label: 'Category', cell: (r) => <Clip text={r.name} w="max-w-[12rem]" /> },
              { label: 'Products', align: 'right', cell: (r) => intStr(r.products) },
              { label: 'Qty', align: 'right', cell: (r) => intStr(r.qty) },
              { label: 'Orders', align: 'right', cell: (r) => intStr(r.orders) },
              { label: 'Revenue', align: 'right', cell: (r) => <strong>{money(r.revenue)}</strong> },
              { label: 'Profit', align: 'right', cell: (r) => money(r.profit) },
              { label: 'Margin', align: 'right', cell: (r) => <Margin value={r.marginPct} /> },
            ]}
          />
        </div>
      </div>
    </Section>
  );
}

function CustomersSection({ x, money, topN }: { x: NonNullable<S['customers']>; money: Fmt; topN: number }) {
  return (
    <Section id="customers" title="Customers" icon={Users} tone="green">
      <KpiGrid>
        <Kpi tone="green" icon={Users} label="Buyers" value={intStr(x.buyers)} note={`avg ${money(x.avgSpentPerBuyer)} each`} />
        <Kpi tone="cyan" icon={UserPlus} label="New buyers" value={intStr(x.newBuyers)} note="first purchase in period" />
        <Kpi tone="blue" icon={UserCheck} label="Returning buyers" value={intStr(x.returningBuyers)} note="had bought before" />
        <Kpi tone="violet" icon={Repeat} label="Repeat rate" value={pctStr(x.repeatRatePct)} note={`${x.repeatBuyers} with 2+ orders`} />
        <Kpi tone="pink" icon={UserPlus} label="New sign-ups" value={intStr(x.newRegistrations)} note={`${x.newRegistrationsVerified} email-verified`} />
        <Kpi tone="teal" icon={UserCheck} label="Registered orders" value={intStr(x.registeredOrders)} note={money(x.registeredTotal)} />
        <Kpi tone="slate" icon={ShoppingBag} label="Guest orders" value={intStr(x.guestOrders)} note={money(x.guestTotal)} />
      </KpiGrid>
      <div className="mt-6">
        <Sub title={`Top ${topN} customers by spend`} tone="green">
          <Table
            tone="green"
            rows={x.top}
            rowKey={(r, i) => `${r.email}-${i}`}
            empty="No customers in this period"
            cols={[
              {
                label: 'Customer',
                cell: (r) => (
                  <span className="flex items-center gap-2">
                    <span
                      className="w-7 h-7 rounded-full flex items-center justify-center text-xs font-bold text-white shrink-0"
                      style={{ background: gradient('green') }}
                    >
                      {(r.name.trim()[0] ?? '?').toUpperCase()}
                    </span>
                    <Clip text={r.name} w="max-w-[9rem]" />
                  </span>
                ),
              },
              { label: 'Email', cell: (r) => <Clip text={r.email || '—'} w="max-w-[14rem]" /> },
              { label: 'Phone', cell: (r) => r.phone || '—' },
              { label: 'Type', cell: (r) => <Pill text={human(r.type)} color={r.type === 'guest' ? '#64748B' : '#059669'} /> },
              { label: 'Orders', align: 'right', cell: (r) => intStr(r.orders) },
              { label: 'Spent', align: 'right', cell: (r) => <strong>{money(r.spent)}</strong> },
              { label: 'Avg order', align: 'right', cell: (r) => money(r.avgOrderValue) },
              { label: 'Last order', cell: (r) => r.lastOrder },
            ]}
          />
        </Sub>
      </div>
    </Section>
  );
}

function GeographySection({ x, money }: { x: NonNullable<S['geography']>; money: Fmt }) {
  return (
    <Section id="geography" title="Sales by City" icon={MapPin} tone="teal" subtitle={'Shipping city on the order. "Unknown" = no city entered.'}>
      <div className="grid grid-cols-1 lg:grid-cols-5 gap-5">
        <div className="lg:col-span-2">
          <ShareBars color={TONES.teal.solid} rows={x.rows.map((r) => ({ key: r.city, label: r.city, value: money(r.total), pct: r.sharePct }))} />
        </div>
        <div className="lg:col-span-3">
          <Table
            tone="teal"
            rows={x.rows}
            rowKey={(r) => r.city}
            cols={[
              { label: 'City', cell: (r) => r.city },
              { label: 'Orders', align: 'right', cell: (r) => intStr(r.orders) },
              { label: 'Customers', align: 'right', cell: (r) => intStr(r.customers) },
              { label: 'Revenue', align: 'right', cell: (r) => <strong>{money(r.total)}</strong> },
              { label: 'Avg order', align: 'right', cell: (r) => money(r.avgOrderValue) },
            ]}
          />
        </div>
      </div>
    </Section>
  );
}

function CouponsSection({ x, money }: { x: NonNullable<S['coupons']>; money: Fmt }) {
  return (
    <Section id="coupons" title="Coupons" icon={Ticket} tone="orange">
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
        <Kpi tone="orange" icon={Ticket} label="Orders with coupon" value={intStr(x.ordersWithCoupon)} />
        <Kpi tone="violet" icon={Percent} label="Coupon usage" value={pctStr(x.couponUsagePct)} note="of orders" />
        <Kpi tone="red" icon={Tag} label="Total discount" value={money(x.totalDiscount)} />
      </div>
      <div className="mt-6">
        <Table
          tone="orange"
          rows={x.rows}
          rowKey={(r) => r.code}
          empty="No coupons used in this period"
          cols={[
            {
              label: 'Code',
              cell: (r) => (
                <span className="font-mono text-xs font-semibold px-2 py-0.5 rounded border border-dashed" style={{ color: TONES.orange.solid, borderColor: TONES.orange.solid }}>
                  {r.code}
                </span>
              ),
            },
            { label: 'Name', cell: (r) => <Clip text={r.name || '(deleted coupon)'} w="max-w-[12rem]" /> },
            { label: 'Offer', cell: (r) => (r.type === 'percentage' ? `${r.value}%` : r.type === 'fixed' ? money(r.value) : '—') },
            { label: 'Orders', align: 'right', cell: (r) => intStr(r.orders) },
            { label: 'Customers', align: 'right', cell: (r) => intStr(r.customers) },
            { label: 'Discount given', align: 'right', cell: (r) => <strong>{money(r.discount)}</strong> },
            { label: 'Avg discount', align: 'right', cell: (r) => money(r.avgDiscount) },
            { label: 'Order value', align: 'right', cell: (r) => money(r.total) },
          ]}
        />
      </div>
    </Section>
  );
}

function ReturnsSection({ x, money }: { x: NonNullable<S['returns']>; money: Fmt }) {
  return (
    <Section id="returns" title="Returns & Refunds" icon={RotateCcw} tone="red" subtitle="Returned items on orders placed in the period (any status). Refunds are dated when recorded.">
      <KpiGrid>
        <Kpi tone="red" icon={PackageX} label="Units returned" value={intStr(x.returnedQty)} note={`${x.itemReturnRatePct}% of units ordered`} />
        <Kpi tone="orange" icon={DollarSign} label="Returned value" value={money(x.returnedValue)} />
        <Kpi tone="pink" icon={ShoppingBag} label="Orders with returns" value={intStr(x.ordersWithReturns)} />
        <Kpi tone="slate" icon={Wallet} label="Refunds issued" value={money(x.refundsIssued)} note={`${x.refundsCount} refund(s) recorded`} />
      </KpiGrid>
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-5 mt-6">
        <Sub title="Return reasons" tone="red">
          <Table
            tone="red"
            rows={x.reasons}
            rowKey={(r) => r.reason}
            empty="No returns in this period"
            cols={[
              { label: 'Reason', cell: (r) => <Clip text={r.reason} w="max-w-[18rem]" /> },
              { label: 'Units', align: 'right', cell: (r) => intStr(r.qty) },
              { label: 'Value', align: 'right', cell: (r) => money(r.value) },
            ]}
          />
        </Sub>
        <Sub title="Most returned products" tone="orange">
          <Table
            tone="orange"
            rows={x.products}
            rowKey={(r, i) => `${r.name}-${i}`}
            empty="No returns in this period"
            cols={[
              { label: 'Product', cell: (r) => <Clip text={r.name} w="max-w-[14rem]" /> },
              { label: 'Units', align: 'right', cell: (r) => intStr(r.returnedQty) },
              { label: 'Rate', align: 'right', cell: (r) => <span style={{ color: '#DC2626' }}>{pctStr(r.returnRatePct)}</span> },
              { label: 'Value', align: 'right', cell: (r) => money(r.returnedValue) },
            ]}
          />
        </Sub>
      </div>
    </Section>
  );
}

function InventorySection({ x, money }: { x: NonNullable<S['inventory']>; money: Fmt }) {
  return (
    <Section id="inventory" title="Inventory (live snapshot)" icon={Warehouse} tone="slate" subtitle="Stock as it is right now — the date filter doesn't apply. Variable products are counted by their variations.">
      <KpiGrid>
        <Kpi tone="slate" icon={Package} label="Products" value={intStr(x.products)} note={`${x.activeProducts} active · ${x.inactiveProducts} inactive`} />
        <Kpi tone="blue" icon={Layers} label="Stock units" value={intStr(x.units)} note={`${x.skus} SKUs`} />
        <Kpi tone="amber" icon={DollarSign} label="Stock value (retail)" value={money(x.retailValue)} />
        <Kpi tone="violet" icon={Receipt} label="Stock value (cost)" value={money(x.costValue)} />
        <Kpi tone="green" icon={PiggyBank} label="Potential profit" value={money(x.potentialProfit)} note="if all stock sells at list price" />
        <Kpi tone="red" icon={PackageX} label="Out of stock" value={intStr(x.outOfStock)} />
        <Kpi tone="orange" icon={PackageMinus} label="Low stock" value={intStr(x.lowStock)} note="at or below threshold" />
        <Kpi tone="pink" icon={Hourglass} label="Unsold in period" value={intStr(x.deadStockTotal)} note="in stock, no sales" />
      </KpiGrid>
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-5 mt-6">
        <Sub title="Low / out of stock" tone="red">
          <Table
            tone="red"
            rows={x.lowStockRows}
            rowKey={(r, i) => `${r.sku}-${i}`}
            empty="Nothing is low on stock"
            cols={[
              { label: 'Product', cell: (r) => <Clip text={`${r.name}${r.variation ? ' (variation)' : ''}`} w="max-w-[14rem]" /> },
              { label: 'SKU', cell: (r) => <span className="font-mono text-xs">{r.sku || '—'}</span> },
              {
                label: 'Stock',
                align: 'right',
                cell: (r) => <Pill text={intStr(r.stock)} color={r.stock <= 0 ? '#DC2626' : '#D97706'} />,
              },
              { label: 'Min', align: 'right', cell: (r) => intStr(r.threshold) },
            ]}
          />
        </Sub>
        <Sub title="In stock but unsold in this period" tone="pink">
          <Table
            tone="pink"
            rows={x.deadStockRows}
            rowKey={(r, i) => `${r.sku}-${i}`}
            empty="Every in-stock product sold at least once"
            cols={[
              { label: 'Product', cell: (r) => <Clip text={r.name} w="max-w-[14rem]" /> },
              { label: 'Stock', align: 'right', cell: (r) => intStr(r.stock) },
              { label: 'Stock value', align: 'right', cell: (r) => money(r.stockValue) },
              { label: 'Added', cell: (r) => r.created },
            ]}
          />
        </Sub>
      </div>
    </Section>
  );
}

function Stars({ value }: { value: number }) {
  return (
    <span className="inline-flex items-center gap-0.5" aria-label={`${value} out of 5`}>
      {[1, 2, 3, 4, 5].map((i) => (
        <Star key={i} size={12} fill={i <= Math.round(value) ? '#F59E0B' : 'none'} color="#F59E0B" />
      ))}
      <span className="ml-1 text-xs">{value}</span>
    </span>
  );
}

function ReviewsSection({ x }: { x: NonNullable<S['reviews']> }) {
  return (
    <Section id="reviews" title="Reviews" icon={Star} tone="amber" subtitle="Reviews written in the period.">
      <KpiGrid>
        <Kpi tone="blue" icon={MessageSquare} label="Reviews" value={intStr(x.total)} note={`${x.verified} verified purchase`} />
        <Kpi tone="amber" icon={Star} label="Average rating" value={x.avgRating === null ? '—' : `${x.avgRating} / 5`} note="approved reviews" />
        <Kpi tone="orange" icon={Hourglass} label="Awaiting moderation" value={intStr(x.pending)} />
        <Kpi tone="green" icon={CheckCircle2} label="Approved / rejected" value={`${x.approved} / ${x.rejected}`} />
      </KpiGrid>
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-5 mt-6">
        <Sub title="Rating distribution" tone="amber">
          <ShareBars color={TONES.amber.from} rows={x.distribution.map((d) => ({ key: String(d.star), label: `${'★'.repeat(d.star)}  ${d.star} star`, value: `${d.count}`, pct: d.sharePct }))} />
        </Sub>
        <Sub title="Most reviewed products" tone="blue">
          <Table
            tone="blue"
            rows={x.mostReviewed}
            rowKey={(r, i) => `${r.name}-${i}`}
            empty="No reviews in this period"
            cols={[
              { label: 'Product', cell: (r) => <Clip text={r.name} w="max-w-[14rem]" /> },
              { label: 'Reviews', align: 'right', cell: (r) => intStr(r.reviews) },
              { label: 'Avg rating', align: 'right', cell: (r) => <Stars value={r.avgRating} /> },
            ]}
          />
        </Sub>
      </div>
    </Section>
  );
}

function CartsSection({ x, money }: { x: NonNullable<S['carts']>; money: Fmt }) {
  return (
    <Section id="carts" title="Carts & Wishlists" icon={ShoppingCart} tone="cyan" subtitle="Carts with items whose last activity is in the period. Abandoned = no activity for 24 hours or more.">
      <KpiGrid>
        <Kpi tone="cyan" icon={ShoppingCart} label="Open carts" value={intStr(x.openCarts)} note={`${x.customerCarts} customer · ${x.guestCarts} guest`} />
        <Kpi tone="blue" icon={DollarSign} label="Cart value" value={money(x.cartValue)} note={`${x.cartItems} items`} />
        <Kpi tone="orange" icon={Hourglass} label="Abandoned carts" value={intStr(x.abandonedCarts)} note={`${x.remindersSent} sent a reminder`} />
        <Kpi tone="red" icon={Wallet} label="Abandoned value" value={money(x.abandonedValue)} />
        <Kpi tone="pink" icon={Heart} label="Wishlist items" value={intStr(x.wishlistItems)} note={`${x.wishlistShoppers} shoppers`} />
        <Kpi tone="violet" icon={Package} label="Wished products" value={intStr(x.wishlistProducts)} />
      </KpiGrid>
      <div className="mt-6">
        <Sub title="Most wished products" tone="pink">
          <Table
            tone="pink"
            rows={x.topWished}
            rowKey={(r, i) => `${r.name}-${i}`}
            empty="No wishlist activity in this period"
            cols={[
              { label: 'Product', cell: (r) => <Clip text={r.name} /> },
              {
                label: 'Wishlists',
                align: 'right',
                cell: (r) => (
                  <span className="inline-flex items-center gap-1">
                    <Heart size={12} fill="#DB2777" color="#DB2777" /> {intStr(r.count)}
                  </span>
                ),
              },
            ]}
          />
        </Sub>
      </div>
    </Section>
  );
}

// ─── All sections, in report order ───────────────────────────────────────────

export default function ReportSections({ report }: { report: StoreReport }) {
  const { sections: s, meta } = report;
  // Same symbol/code placement as formatCurrency(), but always 2 decimals —
  // a financial report reads "PKR 275.50", not "PKR 275.5".
  const cur = meta.currency;
  const money: Fmt = (n) => {
    if (n === null || n === undefined) return '—';
    const v = Number(n).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
    if (cur.format === 'code') return `${cur.code} ${v}`;
    if (cur.format === 'both') return `${cur.symbol} ${v} ${cur.code}`;
    return `${cur.symbol} ${v}`;
  };
  const topN = meta.filters.topN;

  return (
    <div className="space-y-5">
      {s.summary && <SummarySection x={s.summary} money={money} />}
      {s.trend && <TrendSection x={s.trend} money={money} />}
      {s.status && <StatusSection x={s.status} money={money} />}
      {s.payments && <PaymentsSection x={s.payments} money={money} />}
      {s.products && <ProductsSection x={s.products} money={money} topN={topN} />}
      {s.categories && <CategoriesSection x={s.categories} money={money} />}
      {s.customers && <CustomersSection x={s.customers} money={money} topN={topN} />}
      {s.geography && <GeographySection x={s.geography} money={money} />}
      {s.coupons && <CouponsSection x={s.coupons} money={money} />}
      {s.returns && <ReturnsSection x={s.returns} money={money} />}
      {s.inventory && <InventorySection x={s.inventory} money={money} />}
      {s.reviews && <ReviewsSection x={s.reviews} />}
      {s.carts && <CartsSection x={s.carts} money={money} />}
    </div>
  );
}
