import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { PieChart, Pie, Cell, Tooltip, ResponsiveContainer } from 'recharts'
import { FileText, X, ChevronDown, Loader2 } from 'lucide-react'
import toast from 'react-hot-toast'
import client from '../../../api/client'
import { FilterBar, FilterSelect, FilterDateInput, WorkDayDateToggle } from '../shared/FilterBar'
import { Panel, DataTable, THead, TH, TR, TD, ChartTooltip } from '../shared/TablePrimitives'
import EmptyState from '../shared/EmptyState'
import SkeletonTable from '../shared/SkeletonTable'
import { fmtEUR, fmtNum, fmtDate, fmtTime, fmtDateStr, CHART_PALETTE } from '../shared/reportDesignTokens'

function today() { return new Date().toISOString().slice(0, 10) }
function monthAgo() { const d = new Date(); d.setDate(d.getDate() - 30); return d.toISOString().slice(0, 10) }

// ─── SVG donut chart (inline, for print window) ───────────────────────────────

function svgDonut(categories, size = 200) {
  const total = categories.reduce((s, c) => s + c.revenue, 0)
  if (!total) return ''
  const cx = size / 2, cy = size / 2, R = size * 0.42, r = size * 0.22
  let angle = -Math.PI / 2
  const slices = categories.map((c, i) => {
    const frac = c.revenue / total
    const a0 = angle, a1 = angle + frac * 2 * Math.PI
    angle = a1
    const x0 = cx + R * Math.cos(a0), y0 = cy + R * Math.sin(a0)
    const x1 = cx + R * Math.cos(a1), y1 = cy + R * Math.sin(a1)
    const xi0 = cx + r * Math.cos(a0), yi0 = cy + r * Math.sin(a0)
    const xi1 = cx + r * Math.cos(a1), yi1 = cy + r * Math.sin(a1)
    const large = frac > 0.5 ? 1 : 0
    const color = c.color || CHART_PALETTE[i % CHART_PALETTE.length]
    const d = `M${xi0},${yi0} L${x0},${y0} A${R},${R} 0 ${large},1 ${x1},${y1} L${xi1},${yi1} A${r},${r} 0 ${large},0 ${xi0},${yi0} Z`
    return `<path d="${d}" fill="${color}" />`
  }).join('')
  return `<svg width="${size}" height="${size}" xmlns="http://www.w3.org/2000/svg">${slices}</svg>`
}

// ─── Print modal ─────────────────────────────────────────────────────────────

const PRINT_TYPES = [
  { id: 'smart', label: 'Έξυπνη Σύνοψη', desc: 'Κατηγορίες με τεμάχια, έσοδα και ποσοστό' },
  { id: 'full',  label: 'Πλήρης Ανάλυση', desc: 'Κατηγορίες με γράφημα πίτας και αναλυτική εικόνα' },
]

function CategoryPrintModal({ onClose, categories, allProducts, soldProducts, printers, queryParams, periodLabel }) {
  const [printType, setPrintType] = useState('smart')
  const [targetPrinter, setTargetPrinter] = useState('browser')
  const [printing, setPrinting] = useState(false)

  const printerOptions = [
    { value: 'browser', label: 'Εκτύπωση μέσω browser (PDF)' },
    ...printers.map(p => ({ value: String(p.id), label: p.name })),
  ]

  function periodRow() {
    if (queryParams.business_day_id)
      return `<div class="row"><span>Εργάσιμη Μέρα</span><span>${periodLabel}</span></div>`
    const f = queryParams.from ? fmtDateStr(queryParams.from.slice(0, 10)) : '—'
    const t = queryParams.to   ? fmtDateStr(queryParams.to.slice(0, 10))   : '—'
    return `<div class="row"><span>Από</span><span>${f}</span></div><div class="row"><span>Έως</span><span>${t}</span></div>`
  }

  function handleBrowserPrint() {
    const win = window.open('', '_blank', 'width=820,height=800')
    if (!win) { onClose(); return }

    const totalRev = categories.reduce((s, c) => s + c.revenue, 0)
    const totalQty = categories.reduce((s, c) => s + c.units_sold, 0)

    let body = ''
    if (printType === 'smart') {
      const rows = categories.map(c => {
        const pctRev = c.pct_rev ?? c.pct ?? 0
        const pctQty = totalQty ? (c.units_sold / totalQty * 100).toFixed(1) : '0'
        return `<tr>
          <td>${c.category_name}</td>
          <td class="num">${fmtNum(c.units_sold)}</td>
          <td class="num">${fmtEUR(c.revenue)}</td>
          <td class="num">${pctRev}%</td>
          <td class="num">${pctQty}%</td>
        </tr>`
      }).join('')
      body = `<table>
        <thead><tr><th>Κατηγορία</th><th class="num">Τεμ.</th><th class="num">Έσοδα</th><th class="num">% Έσ.</th><th class="num">% Τεμ.</th></tr></thead>
        <tbody>${rows}</tbody>
        <tfoot><tr><td>Σύνολο</td><td class="num">${fmtNum(totalQty)}</td><td class="num">${fmtEUR(totalRev)}</td><td class="num">100%</td><td class="num">100%</td></tr></tfoot>
      </table>`
    } else {
      // Build sold-product lookup: product_id → {qty_sold, revenue, category_id}
      const soldMap = {}
      for (const p of soldProducts) soldMap[p.product_id] = p
      // Group allProducts by category_id
      const productsByCategory = {}
      for (const ap of allProducts) {
        if (!productsByCategory[ap.category_id]) productsByCategory[ap.category_id] = []
        productsByCategory[ap.category_id].push(ap)
      }

      const donut = svgDonut(categories)
      const legend = categories.map((c, i) => {
        const color = c.color || CHART_PALETTE[i % CHART_PALETTE.length]
        const pctRev = c.pct_rev ?? c.pct ?? 0
        const pctQty = totalQty ? (c.units_sold / totalQty * 100).toFixed(1) : 0
        return `<div class="legend-row"><span class="legend-dot" style="background:${color}"></span><span class="legend-name">${c.category_name}</span><span class="legend-val">${pctRev}% έσ. / ${pctQty}% τεμ.</span></div>`
      }).join('')

      // Full category blocks with per-product breakdown
      const catBlocks = categories.map((c, i) => {
        const color = c.color || CHART_PALETTE[i % CHART_PALETTE.length]
        const pctRev = c.pct_rev ?? c.pct ?? 0
        const pctQtyOfTotal = totalQty ? (c.units_sold / totalQty * 100).toFixed(1) : 0

        const catProducts = (productsByCategory[c.category_id] || [])
          .map(ap => {
            const sold = soldMap[ap.id]
            return { name: ap.name, qty: sold ? sold.qty_sold : 0, revenue: sold ? sold.revenue : 0 }
          })
          .filter(p => p.qty > 0)
          .sort((a, b) => b.qty - a.qty)
        const catTotalQty = catProducts.reduce((s, p) => s + p.qty, 0)
        const catTotalRev = catProducts.reduce((s, p) => s + p.revenue, 0)

        const productRows = catProducts.map(p => {
          const pctProdRev = catTotalRev ? (p.revenue / catTotalRev * 100).toFixed(1) : '0'
          const pctProdQty = catTotalQty ? (p.qty / catTotalQty * 100).toFixed(1) : '0'
          return `<tr>
            <td class="prod-name">${p.name}</td>
            <td class="num">${fmtNum(p.qty)}</td>
            <td class="num">${fmtEUR(p.revenue)}</td>
            <td class="num">${pctProdRev}%</td>
            <td class="num">${pctProdQty}%</td>
          </tr>`
        }).join('')

        return `<div class="cat-full-block" style="border-left: 4px solid ${color}">
          <div class="cat-full-header">
            <span class="cat-full-name">${c.category_name}</span>
            <span class="cat-full-rev">${fmtEUR(c.revenue)}</span>
          </div>
          <div class="cat-full-sub">${fmtNum(c.units_sold)} τεμ. &nbsp;·&nbsp; ${c.product_count} προϊόντα &nbsp;·&nbsp; ${pctRev}% εσόδων &nbsp;·&nbsp; ${pctQtyOfTotal}% τεμ.</div>
          ${catProducts.length ? `
          <table class="prod-table">
            <colgroup><col/><col style="width:52px"/><col style="width:64px"/><col style="width:48px"/><col style="width:48px"/></colgroup>
            <thead><tr><th>Προϊόν</th><th class="num">Τεμ.</th><th class="num">Έσοδα</th><th class="num">% Έσ.</th><th class="num">% Τεμ.</th></tr></thead>
            <tbody>${productRows}</tbody>
          </table>` : '<div class="no-sales">Δεν υπάρχουν πωλήσεις σε αυτή την περίοδο</div>'}
        </div>`
      }).join('')

      body = `
        <div class="chart-row">
          <div class="donut-wrap">${donut}</div>
          <div class="legend">${legend}</div>
        </div>
        ${catBlocks}`
    }

    const title = printType === 'smart' ? 'Σύνοψη Κατηγοριών' : 'Πλήρης Ανάλυση Κατηγοριών'
    const styles = `<style>
      * { box-sizing: border-box; margin: 0; padding: 0; }
      body { font-family: Arial, sans-serif; font-size: 12px; color: #000; padding: 24px; max-width: 760px; }
      h1 { font-size: 16px; font-weight: bold; border-bottom: 2px solid #000; padding-bottom: 6px; margin-bottom: 12px; font-family: 'Courier New', monospace; }
      .meta { margin-bottom: 16px; font-family: 'Courier New', monospace; }
      .row { display: flex; justify-content: space-between; padding: 2px 0; }
      table { width: 100%; border-collapse: collapse; font-size: 11px; margin-top: 12px; font-family: 'Courier New', monospace; }
      th { text-align: left; border-bottom: 1px solid #000; padding: 4px 6px; font-size: 10px; text-transform: uppercase; }
      td { padding: 3px 6px; border-bottom: 1px dotted #ccc; }
      .num { text-align: right; font-weight: bold; }
      tfoot td { border-top: 2px solid #000; border-bottom: none; font-weight: bold; padding-top: 6px; }
      .chart-row { display: flex; align-items: flex-start; gap: 24px; margin: 16px 0; }
      .donut-wrap { flex-shrink: 0; }
      .legend { display: flex; flex-direction: column; gap: 6px; justify-content: center; }
      .legend-row { display: flex; align-items: center; gap: 8px; font-size: 12px; }
      .legend-dot { display: inline-block; width: 12px; height: 12px; border-radius: 2px; flex-shrink: 0; }
      .legend-name { flex: 1; }
      .legend-val { font-weight: bold; min-width: 40px; text-align: right; }
      .cards-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-top: 16px; }
      .cat-card { padding: 10px 12px; border: 1px solid #e2e8f0; border-radius: 4px; }
      .cat-name { font-size: 11px; font-weight: bold; text-transform: uppercase; letter-spacing: .05em; color: #475569; margin-bottom: 4px; }
      .cat-rev { font-size: 20px; font-weight: bold; font-family: 'Courier New', monospace; margin-bottom: 2px; }
      .cat-sub { font-size: 10px; color: #64748b; }
      .cat-full-block { padding: 12px 14px; border: 1px solid #e2e8f0; border-radius: 4px; margin-bottom: 14px; }
      .cat-full-header { display: flex; justify-content: space-between; align-items: baseline; margin-bottom: 2px; }
      .cat-full-name { font-size: 13px; font-weight: bold; text-transform: uppercase; letter-spacing: .05em; }
      .cat-full-rev { font-size: 13px; font-weight: bold; font-family: 'Courier New', monospace; color: #334155; }
      .cat-full-sub { font-size: 10px; color: #64748b; margin-bottom: 8px; }
      .prod-table { width: 100%; border-collapse: collapse; font-size: 10px; margin-top: 6px; table-layout: fixed; }
      .prod-table th, .prod-table td { padding: 2px 4px; border-bottom: 1px dotted #e2e8f0; font-size: 10px; }
      .prod-table thead th { border-bottom: 1px solid #cbd5e1; font-size: 9px; text-transform: uppercase; color: #64748b; font-weight: bold; }
      .prod-table th.num, .prod-table td.num { text-align: right; font-weight: bold; }
      .prod-table th:first-child, .prod-table td:first-child { text-align: left; }
      .prod-name { color: #1e293b; }
      .no-sales { font-size: 10px; color: #94a3b8; font-style: italic; margin-top: 4px; }
      @media print { body { padding: 0; } }
    </style>`

    win.document.write(`<!DOCTYPE html><html><head><meta charset="UTF-8"><title>${title}</title>${styles}</head><body>
      <h1>${title}</h1>
      <div class="meta">
        ${periodRow()}
        <div class="row"><span>Κατηγορίες</span><span>${categories.length}</span></div>
      </div>
      ${body}
    </body></html>`)
    win.document.close()
    win.focus()
    win.print()
    onClose()
  }

  async function handleThermalPrint() {
    const body = { printer_id: parseInt(targetPrinter, 10), mode: printType }
    if (queryParams.business_day_id) {
      body.business_day_id = parseInt(queryParams.business_day_id, 10)
    } else {
      body.from_dt = queryParams.from
      body.to_dt = queryParams.to
    }
    setPrinting(true)
    try {
      await client.post('/api/reports/print/categories', body)
      toast.success('Η εκτύπωση στάλθηκε στον εκτυπωτή')
      onClose()
    } catch {
      toast.error('Αποτυχία αποστολής στον εκτυπωτή')
    } finally {
      setPrinting(false)
    }
  }

  function handlePrint() {
    if (targetPrinter === 'browser') handleBrowserPrint()
    else handleThermalPrint()
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4" onMouseDown={e => { if (e.target === e.currentTarget) onClose() }}>
      <div className="relative w-full max-w-md rounded-xl border border-slate-200 bg-white shadow-xl">
        <div className="flex items-center justify-between border-b border-slate-100 px-5 py-4">
          <h2 className="text-[15px] font-semibold text-slate-900">Εκτύπωση Κατηγοριών</h2>
          <button onClick={onClose} className="rounded-md p-1 text-slate-400 transition hover:bg-slate-100 hover:text-slate-600"><X className="h-4 w-4" /></button>
        </div>
        <div className="px-5 py-4 space-y-4 text-[13px] text-slate-700">
          <div>
            <div className="mb-2 text-[11px] font-medium uppercase tracking-[0.08em] text-slate-500">Τύπος Εκτύπωσης</div>
            <div className="space-y-2">
              {PRINT_TYPES.map(pt => (
                <label key={pt.id} className={`flex cursor-pointer items-start gap-3 rounded-lg border p-3 transition ${printType === pt.id ? 'border-sky-400 bg-sky-50' : 'border-slate-200 hover:border-slate-300 hover:bg-slate-50'}`}>
                  <input type="radio" name="printType" value={pt.id} checked={printType === pt.id} onChange={() => setPrintType(pt.id)} className="mt-0.5 accent-sky-500" />
                  <div>
                    <div className="font-medium text-slate-800">{pt.label}</div>
                    <div className="text-[12px] text-slate-500">{pt.desc}</div>
                  </div>
                </label>
              ))}
            </div>
          </div>
          <div>
            <div className="mb-2 text-[11px] font-medium uppercase tracking-[0.08em] text-slate-500">Εκτυπωτής Προορισμού</div>
            <div className="relative">
              <select value={targetPrinter} onChange={e => setTargetPrinter(e.target.value)} className="w-full appearance-none rounded-md border border-slate-200 bg-white py-2 pl-3 pr-8 text-[13px] text-slate-700 shadow-[0_1px_0_rgba(15,23,42,0.04)] focus:border-sky-400 focus:outline-none focus:ring-2 focus:ring-sky-100">
                {printerOptions.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
              </select>
              <ChevronDown className="pointer-events-none absolute right-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-slate-400" />
            </div>
          </div>
          <div className="flex items-center justify-end gap-2 border-t border-slate-100 pt-2">
            <button onClick={onClose} className="inline-flex items-center justify-center gap-2 rounded-md border border-slate-200 bg-white px-3.5 py-2 text-[13px] font-medium text-slate-700 shadow-[0_1px_0_rgba(15,23,42,0.04)] transition hover:bg-slate-50 hover:border-slate-300">Ακύρωση</button>
            <button onClick={handlePrint} disabled={printing} className="inline-flex items-center justify-center gap-2 rounded-md bg-sky-500 px-3.5 py-2 text-[13px] font-medium text-white shadow-[0_1px_0_rgba(15,23,42,0.08)] transition hover:bg-sky-600 active:bg-sky-700 disabled:opacity-60 disabled:pointer-events-none">
              {printing ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <FileText className="h-3.5 w-3.5" />}
              {printing ? 'Αποστολή...' : 'Εκτύπωση'}
            </button>
          </div>
        </div>
      </div>
    </div>
  )
}

// ─── Main Component ───────────────────────────────────────────────────────────

export default function CategoryPerformance() {
  const [mode, setMode] = useState('range')
  const [from, setFrom] = useState(monthAgo())
  const [to, setTo] = useState(today())
  const [businessDayId, setBusinessDayId] = useState('all')
  const [showPrintModal, setShowPrintModal] = useState(false)
  const [pieMetric, setPieMetric] = useState('revenue')

  const { data: bdData } = useQuery({ queryKey: ['business-days-list'], queryFn: () => client.get('/api/reports/business-days').then(r => r.data), staleTime: 60 * 1000 })
  const { data: printersData } = useQuery({ queryKey: ['meta-printers'], queryFn: () => client.get('/api/reports/meta/printers').then(r => r.data), staleTime: 5 * 60 * 1000 })
  const { data: allProductsData } = useQuery({ queryKey: ['meta-products'], queryFn: () => client.get('/api/reports/meta/products').then(r => r.data), staleTime: 5 * 60 * 1000 })

  const queryParams = {
    ...(mode === 'workday' && businessDayId !== 'all' ? { business_day_id: businessDayId } : {}),
    ...(mode === 'range' ? { from: from + 'T00:00:00', to: to + 'T23:59:59' } : {}),
  }

  const { data, isLoading, isError, refetch } = useQuery({
    queryKey: ['category-performance', mode, from, to, businessDayId],
    queryFn: () => client.get('/api/reports/categories/performance', { params: queryParams }).then(r => r.data),
    staleTime: 60 * 1000,
  })

  const { data: productsData } = useQuery({
    queryKey: ['product-performance-for-cat', mode, from, to, businessDayId],
    queryFn: () => client.get('/api/reports/products/performance', { params: queryParams }).then(r => r.data),
    staleTime: 60 * 1000,
  })

  const bdOptions = [{ value: 'all', label: 'Όλες οι Εργάσιμες Μέρες' }, ...((bdData?.business_days || []).map(bd => ({ value: String(bd.id), label: `${fmtDate(bd.opened_at)} · ${fmtTime(bd.opened_at)}` })))]
  const printers = printersData?.printers || []
  const allProducts = allProductsData?.products || []
  const soldProducts = productsData?.products || []
  const categories = data?.categories || []
  const anyHasCost = categories.some(c => (c.total_cost || 0) > 0)
  const pieCategories = pieMetric === 'profit'
    ? categories.filter(c => (c.trackable_profit || 0) > 0)
    : categories
  const pieData = pieCategories.map((c, i) => ({
    name: c.category_name,
    value: pieMetric === 'profit' ? c.trackable_profit : c.revenue,
    color: c.color || CHART_PALETTE[i % CHART_PALETTE.length],
  }))

  const periodLabel = mode === 'workday'
    ? (bdOptions.find(o => o.value === businessDayId)?.label || 'Εργάσιμη Μέρα')
    : `${fmtDateStr(from)} → ${fmtDateStr(to)}`

  if (isLoading) return <div className="flex-1 overflow-y-auto p-6"><SkeletonTable rows={6} columns={5} showChart /></div>
  if (isError) return (
    <div className="flex flex-col flex-1 min-h-0">
      <FilterBar><span className="text-[12px] text-slate-500">Αδυναμία φόρτωσης δεδομένων</span></FilterBar>
      <div className="flex flex-1 items-center justify-center"><button onClick={() => refetch()} className="rounded-md border border-slate-200 px-4 py-2 text-sm hover:bg-slate-50">Επανάληψη</button></div>
    </div>
  )

  return (
    <div className="flex flex-col flex-1 min-h-0">
      <FilterBar right={
        <button onClick={() => setShowPrintModal(true)} className="inline-flex items-center gap-1.5 rounded-md border border-slate-200 bg-white px-2.5 py-1.5 text-[12px] font-medium text-slate-600 shadow-[0_1px_0_rgba(15,23,42,0.04)] transition hover:border-slate-300 hover:bg-slate-50 hover:text-slate-900">
          <FileText className="h-3.5 w-3.5" />Εκτύπωση Σύνοψης
        </button>
      }>
        <WorkDayDateToggle mode={mode} onChange={setMode} />
        {mode === 'workday' ? (
          <FilterSelect value={businessDayId} onChange={setBusinessDayId} options={bdOptions} width="w-72" label="Μέρα" />
        ) : (
          <>
            <FilterDateInput value={from} onChange={setFrom} label="Από" />
            <FilterDateInput value={to} onChange={setTo} label="Έως" />
          </>
        )}
      </FilterBar>

      <div className="flex-1 overflow-y-auto p-6">
        {categories.length === 0 ? (
          <EmptyState title="Δεν υπάρχουν δεδομένα κατηγοριών" description="Δεν υπάρχουν πωλήσεις σε αυτή την περίοδο." />
        ) : (
          <>
            <div className="grid grid-cols-12 gap-4">
              <div className="col-span-5">
                <Panel title={pieMetric === 'profit' ? 'Κατανομή Κέρδους' : 'Κατανομή Εσόδων'} right={
                  anyHasCost ? (
                    <div className="inline-flex rounded-md border border-slate-200 bg-slate-50 p-0.5 text-[11px]">
                      {[['revenue', 'Έσοδα'], ['profit', 'Κέρδος']].map(([m, label]) => (
                        <button key={m} onClick={() => setPieMetric(m)} className={`rounded px-2 py-1 font-medium transition ${pieMetric === m ? 'bg-white text-slate-900 shadow-sm ring-1 ring-slate-200' : 'text-slate-500'}`}>{label}</button>
                      ))}
                    </div>
                  ) : null
                }>
                  {pieData.length === 0 ? (
                    <div className="flex items-center justify-center py-8 text-[12px] text-slate-400">Δεν υπάρχουν δεδομένα κέρδους</div>
                  ) : (
                    <div style={{ height: 280 }}>
                      <ResponsiveContainer width="100%" height="100%">
                        <PieChart>
                          <Pie data={pieData} dataKey="value" nameKey="name" innerRadius={60} outerRadius={100} paddingAngle={2}>
                            {pieData.map((d, i) => <Cell key={i} fill={d.color} />)}
                          </Pie>
                          <Tooltip content={<ChartTooltip formatter={v => fmtEUR(v)} />} />
                        </PieChart>
                      </ResponsiveContainer>
                    </div>
                  )}
                </Panel>
              </div>
              <div className="col-span-7 grid grid-cols-2 gap-4">
                {categories.map((c, i) => {
                  const margin = c.revenue > 0 && (c.trackable_profit || 0) > 0
                    ? ((c.trackable_profit / c.revenue) * 100).toFixed(0) + '%'
                    : null
                  return (
                    <div key={c.category_id} className="rounded-lg border border-slate-200 bg-white p-5 shadow-[0_1px_0_rgba(15,23,42,0.04)]">
                      <div className="flex items-center gap-2">
                        <span className="h-2.5 w-2.5 rounded-sm flex-shrink-0" style={{ backgroundColor: c.color || CHART_PALETTE[i % CHART_PALETTE.length] }} />
                        <span className="text-[12px] font-semibold uppercase tracking-wider text-slate-700">{c.category_name}</span>
                      </div>
                      <div className="mt-3 font-mono text-[24px] font-medium tabular-nums text-slate-900">{fmtEUR(c.revenue)}</div>
                      <div className="mt-1 flex justify-between text-[11px] text-slate-500">
                        <span>{c.units_sold} τεμ. · {c.product_count} προϊόντα</span>
                        <span className="font-mono">{c.pct_rev ?? c.pct}%</span>
                      </div>
                      {(c.trackable_profit || 0) > 0 && (
                        <div className="mt-2 flex items-center justify-between border-t border-slate-100 pt-2">
                          <span className="text-[11px] font-medium text-green-700">{fmtEUR(c.trackable_profit)} κέρδος</span>
                          {margin && <span className="text-[10px] text-slate-400">{margin}{c.has_gap && ' ⚠'}</span>}
                        </div>
                      )}
                    </div>
                  )
                })}
              </div>
            </div>
            <div className="mt-4">
              <Panel title="Κατηγορίες" padded={false}>
                <DataTable>
                  <THead>
                    <TH>Κατηγορία</TH>
                    <TH align="right">Προϊόντα</TH>
                    <TH align="right">Τεμάχια</TH>
                    <TH align="right">Έσοδα</TH>
                    {anyHasCost && <TH align="right">Κόστος</TH>}
                    {anyHasCost && <TH align="right">Κέρδος</TH>}
                    <TH align="right">% Εσόδων</TH>
                    {anyHasCost && <TH align="right">% Κέρδους</TH>}
                  </THead>
                  <tbody>
                    {categories.map((c, i) => {
                      const margin = c.revenue > 0 && (c.trackable_profit || 0) > 0
                        ? ((c.trackable_profit / c.revenue) * 100).toFixed(0) + '%'
                        : null
                      return (
                        <TR key={c.category_id} striped>
                          <TD><span className="inline-flex items-center gap-2 font-medium text-slate-900"><span className="h-2 w-2 rounded-sm flex-shrink-0" style={{ backgroundColor: c.color || CHART_PALETTE[i % CHART_PALETTE.length] }} />{c.category_name}</span></TD>
                          <TD mono align="right">{c.product_count}</TD>
                          <TD mono align="right">{fmtNum(c.units_sold)}</TD>
                          <TD mono align="right" className="font-semibold text-slate-900">{fmtEUR(c.revenue)}</TD>
                          {anyHasCost && (
                            <TD mono align="right" className="text-slate-600">
                              {(c.total_cost || 0) > 0 ? fmtEUR(c.total_cost) : <span className="text-slate-300">—</span>}
                            </TD>
                          )}
                          {anyHasCost && (
                            <TD mono align="right">
                              {(c.trackable_profit || 0) > 0 ? (
                                <span className="text-green-700">
                                  {fmtEUR(c.trackable_profit)}
                                  {margin && <span className="ml-1 text-[10px] text-slate-400">({margin}){c.has_gap && ' ⚠'}</span>}
                                </span>
                              ) : <span className="text-slate-300">—</span>}
                            </TD>
                          )}
                          <TD mono align="right">{c.pct_rev ?? c.pct}%</TD>
                          {anyHasCost && (
                            <TD mono align="right">
                              {(c.pct_profit || 0) > 0
                                ? <span className="text-green-700">{c.pct_profit}%</span>
                                : <span className="text-slate-300">—</span>
                              }
                            </TD>
                          )}
                        </TR>
                      )
                    })}
                  </tbody>
                </DataTable>
              </Panel>
            </div>
          </>
        )}
      </div>

      {showPrintModal && (
        <CategoryPrintModal
          onClose={() => setShowPrintModal(false)}
          categories={categories}
          allProducts={allProducts}
          soldProducts={soldProducts}
          printers={printers}
          queryParams={queryParams}
          periodLabel={periodLabel}
        />
      )}
    </div>
  )
}
