import { ColumnDef } from "@tanstack/react-table";
import { ArrowUpDown, ChevronDown, ChevronRight } from "lucide-react";
import { Button } from "@/components/ui/button";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";

// ─── Raw product from API ───────────────────────────────────────────────────

export interface ProductDetail {
  pid: string;
  title: string;
  sku: string;
  line: string;
  artist: string;
  category: string;
  categoryPath: string;
  lifetimeSales: number;
  first30dSales: number;
  first60dSales: number;
  first90dSales: number;
  currentStock: number;
  dateFirstReceived: string | null;
  price: number;
}

// ─── Grouped row types ──────────────────────────────────────────────────────

export interface GroupStats {
  productCount: number;
  avgLifetimeSales: number;
  medianLifetimeSales: number;
  avgFirst30dSales: number;
  minSales: number;
  maxSales: number;
  totalSales: number;
}

export interface CategoryBreakdown extends GroupStats {
  category: string;
  categoryPath: string;
  products: ProductDetail[];
}

/** Line view: one row per collection */
export interface LineGroup extends GroupStats {
  line: string;
  artist: string;
  dateFirstReceived: string | null;
  categories: CategoryBreakdown[];
  products: ProductDetail[];
}

/** Category view: one row per product type (enhanced) */
export interface CategoryGroup extends GroupStats {
  category: string;
  categoryPath: string;
  products: ProductDetail[];
}

/** Designer view: one row per artist, with line + category breakdowns */
export interface LineSummary extends GroupStats {
  line: string;
  dateFirstReceived: string | null;
}

export interface DesignerGroup extends GroupStats {
  artist: string;
  lineCount: number;
  lines: LineSummary[];
  categories: CategoryBreakdown[];
  products: ProductDetail[];
}

/** Cross-line average (one per category across all lines) */
export interface CrossLineAverage {
  category: string;
  lineCount: number;
  avgProductCount: number;
  avgLifetimeSales: number;
  medianLifetimeSales: number;
  avgFirst30dSales: number;
  minAvgSales: number;
  maxAvgSales: number;
}

// ─── Helpers ────────────────────────────────────────────────────────────────

export function median(values: number[]): number {
  if (values.length === 0) return 0;
  const sorted = [...values].sort((a, b) => a - b);
  const mid = Math.floor(sorted.length / 2);
  return sorted.length % 2 !== 0 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
}

export function computeGroupStats(products: ProductDetail[]): GroupStats {
  const sales = products.map(p => p.lifetimeSales);
  const total = sales.reduce((s, v) => s + v, 0);
  return {
    productCount: products.length,
    avgLifetimeSales: products.length > 0 ? total / products.length : 0,
    medianLifetimeSales: median(sales),
    avgFirst30dSales: products.length > 0
      ? products.reduce((s, p) => s + p.first30dSales, 0) / products.length
      : 0,
    minSales: sales.length > 0 ? Math.min(...sales) : 0,
    maxSales: sales.length > 0 ? Math.max(...sales) : 0,
    totalSales: total,
  };
}

// ─── Grouping logic ─────────────────────────────────────────────────────────

export function groupByLine(products: ProductDetail[]): LineGroup[] {
  const lineMap = new Map<string, ProductDetail[]>();
  for (const p of products) {
    const key = p.line || '(No Line)';
    if (!lineMap.has(key)) lineMap.set(key, []);
    lineMap.get(key)!.push(p);
  }

  return [...lineMap.entries()].map(([line, prods]) => {
    // Build category breakdown within this line
    const catMap = new Map<string, ProductDetail[]>();
    for (const p of prods) {
      const key = p.category || 'Uncategorized';
      if (!catMap.has(key)) catMap.set(key, []);
      catMap.get(key)!.push(p);
    }
    const categories: CategoryBreakdown[] = [...catMap.entries()]
      .map(([cat, catProds]) => ({
        category: cat,
        categoryPath: catProds[0]?.categoryPath || '',
        ...computeGroupStats(catProds),
        products: catProds,
      }))
      .sort((a, b) => b.avgLifetimeSales - a.avgLifetimeSales);

    const stats = computeGroupStats(prods);
    const firstArtist = prods.find(p => p.artist)?.artist || '';
    const dates = prods
      .map(p => p.dateFirstReceived)
      .filter(Boolean)
      .sort();

    return {
      line,
      artist: firstArtist,
      dateFirstReceived: dates[0] || null,
      ...stats,
      categories,
      products: prods,
    };
  }).sort((a, b) => {
    // Sort by received date descending (newest first)
    if (a.dateFirstReceived && b.dateFirstReceived) {
      return b.dateFirstReceived.localeCompare(a.dateFirstReceived);
    }
    if (a.dateFirstReceived) return -1;
    if (b.dateFirstReceived) return 1;
    return b.avgLifetimeSales - a.avgLifetimeSales;
  });
}

export function groupByCategory(products: ProductDetail[]): CategoryGroup[] {
  const catMap = new Map<string, ProductDetail[]>();
  for (const p of products) {
    const key = p.category || 'Uncategorized';
    if (!catMap.has(key)) catMap.set(key, []);
    catMap.get(key)!.push(p);
  }

  return [...catMap.entries()]
    .map(([cat, prods]) => ({
      category: cat,
      categoryPath: prods[0]?.categoryPath || '',
      ...computeGroupStats(prods),
      products: prods,
    }))
    .sort((a, b) => b.avgLifetimeSales - a.avgLifetimeSales);
}

export function groupByDesigner(products: ProductDetail[]): DesignerGroup[] {
  const artistMap = new Map<string, ProductDetail[]>();
  for (const p of products) {
    const key = p.artist || '(Unknown Designer)';
    if (!artistMap.has(key)) artistMap.set(key, []);
    artistMap.get(key)!.push(p);
  }

  return [...artistMap.entries()]
    .map(([artist, prods]) => {
      // Line breakdown within this designer
      const lineMap = new Map<string, ProductDetail[]>();
      for (const p of prods) {
        const key = p.line || '(No Line)';
        if (!lineMap.has(key)) lineMap.set(key, []);
        lineMap.get(key)!.push(p);
      }
      const lines: LineSummary[] = [...lineMap.entries()]
        .map(([line, lineProds]) => {
          const dates = lineProds.map(p => p.dateFirstReceived).filter(Boolean).sort();
          return {
            line,
            dateFirstReceived: dates[0] || null,
            ...computeGroupStats(lineProds),
          };
        })
        .sort((a, b) => {
          if (a.dateFirstReceived && b.dateFirstReceived)
            return b.dateFirstReceived.localeCompare(a.dateFirstReceived);
          if (a.dateFirstReceived) return -1;
          if (b.dateFirstReceived) return 1;
          return b.avgLifetimeSales - a.avgLifetimeSales;
        });

      // Category breakdown across all this designer's lines
      const catMap = new Map<string, ProductDetail[]>();
      for (const p of prods) {
        const key = p.category || 'Uncategorized';
        if (!catMap.has(key)) catMap.set(key, []);
        catMap.get(key)!.push(p);
      }
      const categories: CategoryBreakdown[] = [...catMap.entries()]
        .map(([cat, catProds]) => ({
          category: cat,
          categoryPath: catProds[0]?.categoryPath || '',
          ...computeGroupStats(catProds),
          products: catProds,
        }))
        .sort((a, b) => b.avgLifetimeSales - a.avgLifetimeSales);

      return {
        artist,
        lineCount: lines.filter(l => l.line !== '(No Line)').length,
        ...computeGroupStats(prods),
        lines,
        categories,
        products: prods,
      };
    })
    .sort((a, b) => b.avgLifetimeSales - a.avgLifetimeSales);
}

export function computeCrossLineAverages(lines: LineGroup[]): CrossLineAverage[] {
  // For each category that appears across lines, compute the average of each line's average
  const catLineData = new Map<string, { avgSales: number[]; avgFirst30d: number[]; productCounts: number[] }>();

  for (const line of lines) {
    if (line.line === '(No Line)') continue;
    for (const cat of line.categories) {
      if (!catLineData.has(cat.category)) {
        catLineData.set(cat.category, { avgSales: [], avgFirst30d: [], productCounts: [] });
      }
      const d = catLineData.get(cat.category)!;
      d.avgSales.push(cat.avgLifetimeSales);
      d.avgFirst30d.push(cat.avgFirst30dSales);
      d.productCounts.push(cat.productCount);
    }
  }

  return [...catLineData.entries()]
    .filter(([, d]) => d.avgSales.length >= 2) // Need at least 2 lines to be meaningful
    .map(([category, d]) => ({
      category,
      lineCount: d.avgSales.length,
      avgProductCount: d.productCounts.reduce((s, v) => s + v, 0) / d.productCounts.length,
      avgLifetimeSales: d.avgSales.reduce((s, v) => s + v, 0) / d.avgSales.length,
      medianLifetimeSales: median(d.avgSales),
      avgFirst30dSales: d.avgFirst30d.reduce((s, v) => s + v, 0) / d.avgFirst30d.length,
      minAvgSales: Math.min(...d.avgSales),
      maxAvgSales: Math.max(...d.avgSales),
    }))
    .sort((a, b) => b.avgLifetimeSales - a.avgLifetimeSales);
}

// ─── Line view columns ─────────────────────────────────────────────────────

const fmt = (v: number, decimals = 0) =>
  v.toLocaleString(undefined, { minimumFractionDigits: decimals, maximumFractionDigits: decimals });

export const lineColumns: ColumnDef<LineGroup>[] = [
  {
    id: "expander",
    header: () => null,
    cell: ({ row }) =>
      row.getCanExpand() ? (
        <Button variant="ghost" onClick={() => row.toggleExpanded()} className="p-0 h-auto">
          {row.getIsExpanded() ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
        </Button>
      ) : null,
  },
  {
    accessorKey: "line",
    header: "Line / Collection",
    cell: ({ row }) => (
      <div>
        <div className="font-medium">{row.original.line}</div>
        {row.original.artist && (
          <div className="text-xs text-muted-foreground">{row.original.artist}</div>
        )}
      </div>
    ),
  },
  {
    id: "received",
    header: "Received",
    cell: ({ row }) => {
      const d = row.original.dateFirstReceived;
      if (!d) return <span className="text-muted-foreground">—</span>;
      return <span className="text-sm whitespace-nowrap">{new Date(d).toLocaleDateString('en-US', { month: 'short', year: 'numeric' })}</span>;
    },
  },
  {
    accessorKey: "productCount",
    header: ({ column }) => (
      <Button variant="ghost" onClick={() => column.toggleSorting(column.getIsSorted() === "asc")} className="whitespace-nowrap">
        # Products <ArrowUpDown className="ml-1 h-4 w-4" />
      </Button>
    ),
    cell: ({ row }) => fmt(row.original.productCount),
  },
  {
    accessorKey: "avgLifetimeSales",
    header: ({ column }) => (
      <Button variant="ghost" onClick={() => column.toggleSorting(column.getIsSorted() === "asc")} className="whitespace-nowrap">
        Avg Lifetime <ArrowUpDown className="ml-1 h-4 w-4" />
      </Button>
    ),
    cell: ({ row }) => fmt(row.original.avgLifetimeSales, 1),
  },
  {
    accessorKey: "medianLifetimeSales",
    header: ({ column }) => (
      <Button variant="ghost" onClick={() => column.toggleSorting(column.getIsSorted() === "asc")} className="whitespace-nowrap">
        Median <ArrowUpDown className="ml-1 h-4 w-4" />
      </Button>
    ),
    cell: ({ row }) => fmt(row.original.medianLifetimeSales, 0),
  },
  {
    accessorKey: "avgFirst30dSales",
    header: ({ column }) => (
      <TooltipProvider delayDuration={0}>
        <Tooltip>
          <TooltipTrigger asChild>
            <Button variant="ghost" onClick={() => column.toggleSorting(column.getIsSorted() === "asc")} className="whitespace-nowrap">
              First 30d <ArrowUpDown className="ml-1 h-4 w-4" />
            </Button>
          </TooltipTrigger>
          <TooltipContent>Average sales in the first 30 days after product was received</TooltipContent>
        </Tooltip>
      </TooltipProvider>
    ),
    cell: ({ row }) => fmt(row.original.avgFirst30dSales, 1),
  },
  {
    accessorKey: "minSales",
    header: ({ column }) => (
      <Button variant="ghost" onClick={() => column.toggleSorting(column.getIsSorted() === "asc")} className="whitespace-nowrap">
        Min <ArrowUpDown className="ml-1 h-4 w-4" />
      </Button>
    ),
    cell: ({ row }) => fmt(row.original.minSales),
  },
  {
    accessorKey: "maxSales",
    header: ({ column }) => (
      <Button variant="ghost" onClick={() => column.toggleSorting(column.getIsSorted() === "asc")} className="whitespace-nowrap">
        Max <ArrowUpDown className="ml-1 h-4 w-4" />
      </Button>
    ),
    cell: ({ row }) => fmt(row.original.maxSales),
  },
  {
    accessorKey: "totalSales",
    header: ({ column }) => (
      <Button variant="ghost" onClick={() => column.toggleSorting(column.getIsSorted() === "asc")} className="whitespace-nowrap">
        Total <ArrowUpDown className="ml-1 h-4 w-4" />
      </Button>
    ),
    cell: ({ row }) => fmt(row.original.totalSales),
  },
];

// ─── Category view columns (enhanced) ───────────────────────────────────────

export const categoryColumns: ColumnDef<CategoryGroup>[] = [
  {
    id: "expander",
    header: () => null,
    cell: ({ row }) =>
      row.getCanExpand() ? (
        <Button variant="ghost" onClick={() => row.toggleExpanded()} className="p-0 h-auto">
          {row.getIsExpanded() ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
        </Button>
      ) : null,
  },
  {
    accessorKey: "category",
    header: "Category",
    cell: ({ row }) => (
      <div>
        <div className="font-medium">{row.original.category}</div>
        {row.original.categoryPath && row.original.categoryPath !== row.original.category && (
          <div className="text-xs text-muted-foreground">{row.original.categoryPath}</div>
        )}
      </div>
    ),
  },
  {
    accessorKey: "productCount",
    header: ({ column }) => (
      <Button variant="ghost" onClick={() => column.toggleSorting(column.getIsSorted() === "asc")} className="whitespace-nowrap">
        # Products <ArrowUpDown className="ml-1 h-4 w-4" />
      </Button>
    ),
    cell: ({ row }) => fmt(row.original.productCount),
  },
  {
    accessorKey: "avgLifetimeSales",
    header: ({ column }) => (
      <Button variant="ghost" onClick={() => column.toggleSorting(column.getIsSorted() === "asc")} className="whitespace-nowrap">
        Avg Lifetime <ArrowUpDown className="ml-1 h-4 w-4" />
      </Button>
    ),
    cell: ({ row }) => fmt(row.original.avgLifetimeSales, 1),
  },
  {
    accessorKey: "medianLifetimeSales",
    header: ({ column }) => (
      <Button variant="ghost" onClick={() => column.toggleSorting(column.getIsSorted() === "asc")} className="whitespace-nowrap">
        Median <ArrowUpDown className="ml-1 h-4 w-4" />
      </Button>
    ),
    cell: ({ row }) => fmt(row.original.medianLifetimeSales, 0),
  },
  {
    accessorKey: "avgFirst30dSales",
    header: ({ column }) => (
      <TooltipProvider delayDuration={0}>
        <Tooltip>
          <TooltipTrigger asChild>
            <Button variant="ghost" onClick={() => column.toggleSorting(column.getIsSorted() === "asc")} className="whitespace-nowrap">
              First 30d <ArrowUpDown className="ml-1 h-4 w-4" />
            </Button>
          </TooltipTrigger>
          <TooltipContent>Average sales in the first 30 days after product was received</TooltipContent>
        </Tooltip>
      </TooltipProvider>
    ),
    cell: ({ row }) => fmt(row.original.avgFirst30dSales, 1),
  },
  {
    accessorKey: "minSales",
    header: ({ column }) => (
      <Button variant="ghost" onClick={() => column.toggleSorting(column.getIsSorted() === "asc")} className="whitespace-nowrap">
        Min <ArrowUpDown className="ml-1 h-4 w-4" />
      </Button>
    ),
    cell: ({ row }) => fmt(row.original.minSales),
  },
  {
    accessorKey: "maxSales",
    header: ({ column }) => (
      <Button variant="ghost" onClick={() => column.toggleSorting(column.getIsSorted() === "asc")} className="whitespace-nowrap">
        Max <ArrowUpDown className="ml-1 h-4 w-4" />
      </Button>
    ),
    cell: ({ row }) => fmt(row.original.maxSales),
  },
  {
    accessorKey: "totalSales",
    header: ({ column }) => (
      <Button variant="ghost" onClick={() => column.toggleSorting(column.getIsSorted() === "asc")} className="whitespace-nowrap">
        Total <ArrowUpDown className="ml-1 h-4 w-4" />
      </Button>
    ),
    cell: ({ row }) => fmt(row.original.totalSales),
  },
];

// ─── Sub-component for Line view: category breakdown + product list ─────────

export function LineSubComponent({ row }: { row: { original: LineGroup } }) {
  const { categories, products } = row.original;

  return (
    <div className="p-4 space-y-4 bg-muted/30">
      {/* Category breakdown summary */}
      <div>
        <p className="text-xs font-medium text-muted-foreground mb-2">
          Category breakdown — {categories.length} categories, {products.length} products
        </p>
        <div className="rounded border bg-background">
          <Table>
            <TableHeader>
              <TableRow className="text-xs">
                <TableHead className="py-1.5">Category</TableHead>
                <TableHead className="py-1.5 text-right"># Products</TableHead>
                <TableHead className="py-1.5 text-right">Avg Lifetime</TableHead>
                <TableHead className="py-1.5 text-right">Median</TableHead>
                <TableHead className="py-1.5 text-right">First 30d</TableHead>
                <TableHead className="py-1.5 text-right">Min</TableHead>
                <TableHead className="py-1.5 text-right">Max</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {categories.map((cat) => (
                <TableRow key={cat.category} className="text-xs">
                  <TableCell className="py-1.5 font-medium">{cat.category}</TableCell>
                  <TableCell className="py-1.5 text-right">{cat.productCount}</TableCell>
                  <TableCell className="py-1.5 text-right">{fmt(cat.avgLifetimeSales, 1)}</TableCell>
                  <TableCell className="py-1.5 text-right">{fmt(cat.medianLifetimeSales)}</TableCell>
                  <TableCell className="py-1.5 text-right">{fmt(cat.avgFirst30dSales, 1)}</TableCell>
                  <TableCell className="py-1.5 text-right">{fmt(cat.minSales)}</TableCell>
                  <TableCell className="py-1.5 text-right">{fmt(cat.maxSales)}</TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>
      </div>

      {/* Full product list */}
      <div>
        <p className="text-xs font-medium text-muted-foreground mb-2">All products in this line</p>
        <ScrollArea className="h-[350px] rounded border bg-background">
          <Table>
            <TableHeader className="sticky top-0 bg-background z-10">
              <TableRow className="text-xs">
                <TableHead className="py-1.5">Product</TableHead>
                <TableHead className="py-1.5">Category</TableHead>
                <TableHead className="py-1.5 text-right">Lifetime</TableHead>
                <TableHead className="py-1.5 text-right">First 30d</TableHead>
                <TableHead className="py-1.5 text-right">Stock</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {products
                .sort((a, b) => b.lifetimeSales - a.lifetimeSales)
                .map((p) => (
                  <TableRow key={p.pid} className="text-xs">
                    <TableCell className="py-1.5 max-w-[300px]">
                      <a
                        href={`https://backend.acherryontop.com/product/${p.pid}`}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="hover:underline block truncate"
                      >
                        {p.title}
                      </a>
                      <span className="text-muted-foreground">{p.sku}</span>
                    </TableCell>
                    <TableCell className="py-1.5 text-muted-foreground">{p.category}</TableCell>
                    <TableCell className="py-1.5 text-right font-medium">{fmt(p.lifetimeSales)}</TableCell>
                    <TableCell className="py-1.5 text-right">{fmt(p.first30dSales)}</TableCell>
                    <TableCell className="py-1.5 text-right">
                      <span className={p.currentStock === 0 ? 'text-red-500' : ''}>
                        {fmt(p.currentStock)}
                      </span>
                    </TableCell>
                  </TableRow>
                ))}
            </TableBody>
          </Table>
        </ScrollArea>
      </div>
    </div>
  );
}

// ─── Sub-component for Category view: product list with richer detail ────────

export function CategorySubComponent({ row }: { row: { original: CategoryGroup } }) {
  const { products } = row.original;

  return (
    <div className="p-4 bg-muted/30">
      <p className="text-xs font-medium text-muted-foreground mb-2">
        {products.length} products
      </p>
      <ScrollArea className="h-[350px] rounded border bg-background">
        <Table>
          <TableHeader className="sticky top-0 bg-background z-10">
            <TableRow className="text-xs">
              <TableHead className="py-1.5">Product</TableHead>
              <TableHead className="py-1.5">Line</TableHead>
              <TableHead className="py-1.5 text-right">Lifetime</TableHead>
              <TableHead className="py-1.5 text-right">First 30d</TableHead>
              <TableHead className="py-1.5 text-right">First 90d</TableHead>
              <TableHead className="py-1.5 text-right">Stock</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {products
              .sort((a, b) => b.lifetimeSales - a.lifetimeSales)
              .map((p) => (
                <TableRow key={p.pid} className="text-xs">
                  <TableCell className="py-1.5 max-w-[280px]">
                    <a
                      href={`https://backend.acherryontop.com/product/${p.pid}`}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="hover:underline block truncate"
                    >
                      {p.title}
                    </a>
                    <span className="text-muted-foreground">{p.sku}</span>
                  </TableCell>
                  <TableCell className="py-1.5 text-muted-foreground text-xs">{p.line || '—'}</TableCell>
                  <TableCell className="py-1.5 text-right font-medium">{fmt(p.lifetimeSales)}</TableCell>
                  <TableCell className="py-1.5 text-right">{fmt(p.first30dSales)}</TableCell>
                  <TableCell className="py-1.5 text-right">{fmt(p.first90dSales)}</TableCell>
                  <TableCell className="py-1.5 text-right">
                    <span className={p.currentStock === 0 ? 'text-red-500' : ''}>
                      {fmt(p.currentStock)}
                    </span>
                  </TableCell>
                </TableRow>
              ))}
          </TableBody>
        </Table>
      </ScrollArea>
    </div>
  );
}

// ─── Designer view columns ──────────────────────────────────────────────────

export const designerColumns: ColumnDef<DesignerGroup>[] = [
  {
    id: "expander",
    header: () => null,
    cell: ({ row }) =>
      row.getCanExpand() ? (
        <Button variant="ghost" onClick={() => row.toggleExpanded()} className="p-0 h-auto">
          {row.getIsExpanded() ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
        </Button>
      ) : null,
  },
  {
    accessorKey: "artist",
    header: "Designer",
    cell: ({ row }) => (
      <div>
        <div className="font-medium">{row.original.artist}</div>
        <div className="text-xs text-muted-foreground">
          {row.original.lineCount} line{row.original.lineCount !== 1 ? 's' : ''}
        </div>
      </div>
    ),
  },
  {
    accessorKey: "productCount",
    header: ({ column }) => (
      <Button variant="ghost" onClick={() => column.toggleSorting(column.getIsSorted() === "asc")} className="whitespace-nowrap">
        # Products <ArrowUpDown className="ml-1 h-4 w-4" />
      </Button>
    ),
    cell: ({ row }) => fmt(row.original.productCount),
  },
  {
    accessorKey: "avgLifetimeSales",
    header: ({ column }) => (
      <Button variant="ghost" onClick={() => column.toggleSorting(column.getIsSorted() === "asc")} className="whitespace-nowrap">
        Avg Lifetime <ArrowUpDown className="ml-1 h-4 w-4" />
      </Button>
    ),
    cell: ({ row }) => fmt(row.original.avgLifetimeSales, 1),
  },
  {
    accessorKey: "medianLifetimeSales",
    header: ({ column }) => (
      <Button variant="ghost" onClick={() => column.toggleSorting(column.getIsSorted() === "asc")} className="whitespace-nowrap">
        Median <ArrowUpDown className="ml-1 h-4 w-4" />
      </Button>
    ),
    cell: ({ row }) => fmt(row.original.medianLifetimeSales, 0),
  },
  {
    accessorKey: "avgFirst30dSales",
    header: ({ column }) => (
      <TooltipProvider delayDuration={0}>
        <Tooltip>
          <TooltipTrigger asChild>
            <Button variant="ghost" onClick={() => column.toggleSorting(column.getIsSorted() === "asc")} className="whitespace-nowrap">
              First 30d <ArrowUpDown className="ml-1 h-4 w-4" />
            </Button>
          </TooltipTrigger>
          <TooltipContent>Average sales in the first 30 days after product was received</TooltipContent>
        </Tooltip>
      </TooltipProvider>
    ),
    cell: ({ row }) => fmt(row.original.avgFirst30dSales, 1),
  },
  {
    accessorKey: "minSales",
    header: ({ column }) => (
      <Button variant="ghost" onClick={() => column.toggleSorting(column.getIsSorted() === "asc")} className="whitespace-nowrap">
        Min <ArrowUpDown className="ml-1 h-4 w-4" />
      </Button>
    ),
    cell: ({ row }) => fmt(row.original.minSales),
  },
  {
    accessorKey: "maxSales",
    header: ({ column }) => (
      <Button variant="ghost" onClick={() => column.toggleSorting(column.getIsSorted() === "asc")} className="whitespace-nowrap">
        Max <ArrowUpDown className="ml-1 h-4 w-4" />
      </Button>
    ),
    cell: ({ row }) => fmt(row.original.maxSales),
  },
  {
    accessorKey: "totalSales",
    header: ({ column }) => (
      <Button variant="ghost" onClick={() => column.toggleSorting(column.getIsSorted() === "asc")} className="whitespace-nowrap">
        Total <ArrowUpDown className="ml-1 h-4 w-4" />
      </Button>
    ),
    cell: ({ row }) => fmt(row.original.totalSales),
  },
];

// ─── Sub-component for Designer view ────────────────────────────────────────

export function DesignerSubComponent({ row }: { row: { original: DesignerGroup } }) {
  const { lines, categories } = row.original;

  return (
    <div className="p-4 space-y-4 bg-muted/30">
      {/* Per-line performance */}
      <div>
        <p className="text-xs font-medium text-muted-foreground mb-2">
          Line performance — {lines.length} lines
        </p>
        <div className="rounded border bg-background">
          <Table>
            <TableHeader>
              <TableRow className="text-xs">
                <TableHead className="py-1.5">Line</TableHead>
                <TableHead className="py-1.5">Received</TableHead>
                <TableHead className="py-1.5 text-right"># Products</TableHead>
                <TableHead className="py-1.5 text-right">Avg Lifetime</TableHead>
                <TableHead className="py-1.5 text-right">Median</TableHead>
                <TableHead className="py-1.5 text-right">First 30d</TableHead>
                <TableHead className="py-1.5 text-right">Min</TableHead>
                <TableHead className="py-1.5 text-right">Max</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {lines.map((l) => (
                <TableRow key={l.line} className="text-xs">
                  <TableCell className="py-1.5 font-medium">{l.line}</TableCell>
                  <TableCell className="py-1.5 text-muted-foreground whitespace-nowrap">
                    {l.dateFirstReceived
                      ? new Date(l.dateFirstReceived).toLocaleDateString('en-US', { month: 'short', year: 'numeric' })
                      : '—'}
                  </TableCell>
                  <TableCell className="py-1.5 text-right">{l.productCount}</TableCell>
                  <TableCell className="py-1.5 text-right">{fmt(l.avgLifetimeSales, 1)}</TableCell>
                  <TableCell className="py-1.5 text-right">{fmt(l.medianLifetimeSales)}</TableCell>
                  <TableCell className="py-1.5 text-right">{fmt(l.avgFirst30dSales, 1)}</TableCell>
                  <TableCell className="py-1.5 text-right">{fmt(l.minSales)}</TableCell>
                  <TableCell className="py-1.5 text-right">{fmt(l.maxSales)}</TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>
      </div>

      {/* Category averages across all their lines */}
      <div>
        <p className="text-xs font-medium text-muted-foreground mb-2">
          Category averages across all {row.original.artist} lines
        </p>
        <div className="rounded border bg-background">
          <Table>
            <TableHeader>
              <TableRow className="text-xs">
                <TableHead className="py-1.5">Category</TableHead>
                <TableHead className="py-1.5 text-right"># Products</TableHead>
                <TableHead className="py-1.5 text-right">Avg Lifetime</TableHead>
                <TableHead className="py-1.5 text-right">Median</TableHead>
                <TableHead className="py-1.5 text-right">First 30d</TableHead>
                <TableHead className="py-1.5 text-right">Min</TableHead>
                <TableHead className="py-1.5 text-right">Max</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {categories.map((cat) => (
                <TableRow key={cat.category} className="text-xs">
                  <TableCell className="py-1.5 font-medium">{cat.category}</TableCell>
                  <TableCell className="py-1.5 text-right">{cat.productCount}</TableCell>
                  <TableCell className="py-1.5 text-right">{fmt(cat.avgLifetimeSales, 1)}</TableCell>
                  <TableCell className="py-1.5 text-right">{fmt(cat.medianLifetimeSales)}</TableCell>
                  <TableCell className="py-1.5 text-right">{fmt(cat.avgFirst30dSales, 1)}</TableCell>
                  <TableCell className="py-1.5 text-right">{fmt(cat.minSales)}</TableCell>
                  <TableCell className="py-1.5 text-right">{fmt(cat.maxSales)}</TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>
      </div>
    </div>
  );
}

