import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import client from '../api/client'

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

function fmt(n) {
  if (n == null) return '—'
  return n.toLocaleString('el-GR', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + ' €'
}

function fmtTime(iso) {
  if (!iso) return '—'
  return new Date(iso).toLocaleTimeString('el-GR', { hour: '2-digit', minute: '2-digit' })
}

function fmtDateTime(iso) {
  if (!iso) return '—'
  const d = new Date(iso)
  return d.toLocaleString('el-GR', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' })
}

const MANAGER_ROLES = new Set(['superadmin', 'owner', 'store_manager', 'staff_manager'])
function roleBadge(role) {
  if (MANAGER_ROLES.has(role)) {
    return { label: 'Διευθυντής', bg: '#ede9fe', color: '#6d28d9' }
  }
  return { label: 'Σερβιτόρος', bg: '#e0f2fe', color: '#0369a1' }
}

// All payment methods with their display config
const PAY_METHODS = [
  { key: 'cash',     label: 'Μετρητά',    color: '#16a34a', bg: '#dcfce7' },
  { key: 'card',     label: 'Κάρτα',      color: '#2563eb', bg: '#dbeafe' },
  { key: 'transfer', label: 'Τρ. Μεταφ.', color: '#7c3aed', bg: '#ede9fe' },
  { key: 'treat',    label: 'Κεράστηκε',  color: '#b45309', bg: '#fef3c7' },
  { key: 'other',    label: 'Άλλο',       color: '#6b7280', bg: '#f3f4f6' },
]

// ── Sub-components ────────────────────────────────────────────────────────────

function TabBtn({ label, active, onClick, badge, warn }) {
  return (
    <button
      onClick={onClick}
      style={{
        padding: '9px 18px',
        border: 'none',
        background: 'none',
        fontSize: 13,
        fontWeight: active ? 700 : 500,
        color: active ? '#111315' : '#6b7280',
        cursor: 'pointer',
        borderBottom: active ? '2px solid #111315' : '2px solid transparent',
        transition: 'all 150ms',
        display: 'flex',
        alignItems: 'center',
        gap: 6,
        whiteSpace: 'nowrap',
      }}
    >
      {label}
      {badge != null && (
        <span style={{
          minWidth: 18, height: 18, borderRadius: 99,
          background: warn ? '#fee2e2' : '#f3f4f6',
          color: warn ? '#dc2626' : '#374151',
          fontSize: 11, fontWeight: 700,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          padding: '0 5px',
        }}>{badge}</span>
      )}
    </button>
  )
}

function StatPill({ label, value, accent = '#374151' }) {
  return (
    <div style={{
      background: '#f9fafb', border: '1px solid #f0f0ef',
      borderRadius: 10, padding: '12px 16px',
      display: 'flex', flexDirection: 'column', gap: 2,
    }}>
      <span style={{ fontSize: 11, color: '#9ca3af', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.04em' }}>{label}</span>
      <span style={{ fontSize: 22, fontWeight: 800, color: accent, letterSpacing: '-0.02em' }}>{value}</span>
    </div>
  )
}

function SectionTitle({ children }) {
  return (
    <div style={{
      fontSize: 11, fontWeight: 700, color: '#9ca3af',
      textTransform: 'uppercase', letterSpacing: '0.06em',
      marginBottom: 10,
    }}>{children}</div>
  )
}

function PaymentBar({ w, total }) {
  if (!total) return null
  const bars = PAY_METHODS.filter(m => (w[m.key] || 0) > 0)
  if (bars.length === 0) return null
  return (
    <div style={{ marginTop: 6 }}>
      <div style={{ display: 'flex', height: 7, borderRadius: 99, overflow: 'hidden', gap: 1 }}>
        {bars.map(m => (
          <div key={m.key} style={{ flex: w[m.key], background: m.color }}
            title={`${m.label}: ${Math.round((w[m.key] / total) * 100)}%`} />
        ))}
      </div>
      <div style={{ display: 'flex', gap: 10, marginTop: 5, flexWrap: 'wrap' }}>
        {bars.map(m => (
          <span key={m.key} style={{ fontSize: 10, color: m.color, fontWeight: 700 }}>
            ● {m.label} {fmt(w[m.key])}
          </span>
        ))}
      </div>
    </div>
  )
}

// ── Tabs ──────────────────────────────────────────────────────────────────────

function FinancialRow({ label, value, sub, accent, warn, indent = false }) {
  return (
    <div style={{
      display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
      padding: indent ? '4px 0 4px 16px' : '5px 0',
      borderBottom: indent ? 'none' : '1px solid #f9fafb',
    }}>
      <span style={{ fontSize: indent ? 12 : 13, color: warn ? '#d97706' : indent ? '#6b7280' : '#374151', flex: 1 }}>
        {warn && <span style={{ marginRight: 5 }}>⚠</span>}{label}
      </span>
      <div style={{ textAlign: 'right', flexShrink: 0 }}>
        <span style={{ fontSize: indent ? 12 : 13.5, fontWeight: indent ? 500 : 700, color: accent || '#111315', fontVariantNumeric: 'tabular-nums' }}>
          {value}
        </span>
        {sub && <div style={{ fontSize: 10.5, color: '#9ca3af' }}>{sub}</div>}
      </div>
    </div>
  )
}

function OverviewTab({ data }) {
  const waiters = data.waiters.filter(w => w.role === 'waiter')

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
      {/* Top stats */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 10 }}>
        <StatPill label="Συνολικά Έσοδα" value={fmt(data.total_revenue)} accent="#111315" />
        <StatPill label="Παραγγελίες" value={String(data.total_orders)} accent="#3758c9" />
        <StatPill label="Αντικείμενα" value={String(data.total_items_ordered)} accent="#7a44c9" />
        <StatPill label="Σερβιτόροι" value={String(waiters.length)} accent="#0d7a8a" />
      </div>

      {/* Hours */}
      <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
        <div style={{ background: '#f9fafb', border: '1px solid #f0f0ef', borderRadius: 10, padding: '10px 14px', flex: 1, minWidth: 130 }}>
          <div style={{ fontSize: 10, color: '#9ca3af', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.04em' }}>ΑΝΟΙΓΜΑ</div>
          <div style={{ fontSize: 14, fontWeight: 700, marginTop: 2 }}>{fmtDateTime(data.opened_at)}</div>
        </div>
        <div style={{ background: '#f9fafb', border: '1px solid #f0f0ef', borderRadius: 10, padding: '10px 14px', flex: 1, minWidth: 130 }}>
          <div style={{ fontSize: 10, color: '#9ca3af', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.04em' }}>ΚΛΕΙΣΙΜΟ</div>
          <div style={{ fontSize: 14, fontWeight: 700, marginTop: 2 }}>
            {data.closed_at ? fmtDateTime(data.closed_at) : <span style={{ color: '#16a34a' }}>Ημέρα Ενεργή</span>}
          </div>
        </div>
      </div>

      {/* Full P&L */}
      <div style={{ border: '1px solid #e5e7eb', borderRadius: 12, overflow: 'hidden' }}>
        {/* REVENUE */}
        <div style={{ padding: '10px 16px', background: '#f9fafb', borderBottom: '1px solid #e5e7eb' }}>
          <SectionTitle>Έσοδα</SectionTitle>
          <FinancialRow label="Σύνολο πωλήσεων" value={fmt(data.total_revenue)} accent="#111315" />
          {data.tabbed_revenue > 0 && (
            <FinancialRow label="Καρτέλες (μη εισπραχθέντα)" value={`− ${fmt(data.tabbed_revenue)}`} accent="#d97706" indent />
          )}
          <FinancialRow
            label="Καθαρά εισπραχθέντα"
            value={fmt(data.total_revenue - (data.tabbed_revenue || 0))}
            accent="#16a34a"
          />
        </div>

        {/* COGS */}
        <div style={{ padding: '10px 16px', borderBottom: '1px solid #e5e7eb' }}>
          <SectionTitle>Κόστος Πωληθέντων (COGS)</SectionTitle>
          <FinancialRow label="Κόστος καταγεγραμμένων" value={fmt(data.cogs_trackable)} accent="#374151" />
          {data.cogs_has_gap && (
            <FinancialRow
              label={`${data.cogs_uncosted_count} αντ. χωρίς κόστος (${fmt(data.cogs_uncosted_revenue)} έσοδα)`}
              value="?" warn indent
            />
          )}
          <FinancialRow
            label="Μικτό κέρδος"
            value={fmt(data.gross_profit)}
            accent={data.gross_profit >= 0 ? '#16a34a' : '#dc2626'}
            warn={data.cogs_has_gap}
            sub={data.cogs_has_gap ? 'Μερικό — υπάρχουν αντ. χωρίς κόστος' : undefined}
          />
        </div>

        {/* LABOR */}
        <div style={{ padding: '10px 16px', borderBottom: '1px solid #e5e7eb' }}>
          <SectionTitle>Μισθοδοσία</SectionTitle>
          <FinancialRow label="Κόστος εργασίας (καταγεγρ.)" value={fmt(data.total_labor_cost)} accent="#374151" />
          {data.labor_untracked_shifts > 0 && (
            <FinancialRow label={`${data.labor_untracked_shifts} βάρδιες χωρίς ωριαία αμοιβή`} value="?" warn indent />
          )}
        </div>

        {/* WASTE */}
        {(data.waste_item_count > 0) && (
          <div style={{ padding: '10px 16px', borderBottom: '1px solid #e5e7eb' }}>
            <SectionTitle>Αποβλήτα</SectionTitle>
            <FinancialRow
              label={`${data.waste_item_count} καταχωρήσεις`}
              value={fmt(data.waste_estimated_cost)}
              accent="#d97706"
            />
          </div>
        )}

        {/* EXPENSES */}
        {data.expenses_total > 0 && (
          <div style={{ padding: '10px 16px', borderBottom: '1px solid #e5e7eb' }}>
            <SectionTitle>Έξοδα (σήμερα)</SectionTitle>
            <FinancialRow label="Σύνολο εξόδων" value={fmt(data.expenses_total)} accent="#374151" />
            <FinancialRow label="Πλη��ωμένα σήμερα" value={fmt(data.expenses_paid_today)} accent="#374151" indent />
            {data.expenses_due > 0 && (
              <FinancialRow label="Ακόμη οφείλονται" value={fmt(data.expenses_due)} accent="#dc2626" warn indent />
            )}
          </div>
        )}

        {/* NET */}
        <div style={{ padding: '12px 16px', background: '#f9fafb' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <div>
              <div style={{ fontSize: 13, fontWeight: 700, color: '#374151' }}>
                Εκτιμώμενο Καθαρό Αποτέλεσμα
              </div>
              {data.net_has_unknowns && (
                <div style={{ fontSize: 11, color: '#d97706', marginTop: 1 }}>
                  ⚠ Μερικό — υπάρχουν άγνωστα κόστη
                </div>
              )}
            </div>
            <div style={{
              fontSize: 20, fontWeight: 800,
              color: data.net_estimate >= 0 ? '#16a34a' : '#dc2626',
              fontVariantNumeric: 'tabular-nums',
            }}>
              {fmt(data.net_estimate)}
            </div>
          </div>
        </div>
      </div>

      {/* Payment breakdown */}
      <div>
        <SectionTitle>Κατανομή Πληρωμών</SectionTitle>
        <div style={{ background: '#f9fafb', border: '1px solid #f0f0ef', borderRadius: 10, padding: '14px 16px' }}>
          {(() => {
            const totals = { cash: 0, card: 0, transfer: 0, treat: 0, other: 0 }
            for (const w of data.waiters) {
              for (const k of Object.keys(totals)) totals[k] += (w[k] || 0)
            }
            return <PaymentBar w={totals} total={data.total_revenue} />
          })()}
        </div>
      </div>

      {/* Cash reconciliation summary (if counted) */}
      {data.store_closing_cash != null && (
        <div>
          <SectionTitle>Ταμείο</SectionTitle>
          <div style={{ background: '#f9fafb', border: '1px solid #f0f0ef', borderRadius: 10, padding: '14px 16px', display: 'flex', flexDirection: 'column', gap: 6 }}>
            <FinancialRow label="Αναμενόμενο ταμείο" value={fmt(data.store_expected_closing)} />
            <FinancialRow label="Μετρημένο ταμείο" value={fmt(data.store_closing_cash)} />
            <FinancialRow
              label="Διαφορά"
              value={data.store_cash_discrepancy === 0 ? '✓ Εντάξει' : fmt(data.store_cash_discrepancy)}
              accent={data.store_cash_discrepancy === 0 ? '#16a34a' : '#dc2626'}
              warn={data.store_cash_discrepancy !== 0}
            />
          </div>
        </div>
      )}
    </div>
  )
}

function WaitersTab({ data }) {
  const [expanded, setExpanded] = useState(null)

  // Fixed column widths for the collapsed summary row
  const colPx = { orders: 88, tables: 88, items: 80, collected: 104 }

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
      {data.waiters.length === 0 && (
        <div style={{ textAlign: 'center', color: '#9ca3af', fontSize: 13, padding: '32px 0' }}>Δεν βρέθηκαν σερβιτόροι</div>
      )}
      {data.waiters.map(w => {
        const badge = roleBadge(w.role)
        const isOpen = expanded === w.waiter_id

        // Compute current cash in drawer: starting_cash + collected so far
        const drawerNow = (w.starting_cash ?? 0) + (w.total_collected ?? 0)

        return (
          <div key={w.waiter_id} style={{
            border: '1px solid #e5e7eb', borderRadius: 12, overflow: 'hidden',
          }}>
            <button
              onClick={() => setExpanded(isOpen ? null : w.waiter_id)}
              style={{
                width: '100%', background: 'white', border: 'none', cursor: 'pointer',
                padding: '14px 18px', display: 'flex', alignItems: 'center', gap: 12, textAlign: 'left',
              }}
            >
              {/* Avatar */}
              <div style={{
                width: 38, height: 38, borderRadius: 10, flexShrink: 0,
                background: badge.bg, color: badge.color,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 15, fontWeight: 800,
              }}>
                {w.waiter_name.charAt(0).toUpperCase()}
              </div>

              {/* Name + role */}
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 14, fontWeight: 700, color: '#111315' }}>{w.waiter_name}</div>
                <span style={{
                  fontSize: 10, fontWeight: 700, padding: '1px 6px', borderRadius: 99,
                  background: badge.bg, color: badge.color,
                }}>{badge.label}</span>
              </div>

              {/* 4 fixed-width metric columns */}
              <div style={{ display: 'flex', gap: 4, flexShrink: 0 }}>
                {[
                  { label: 'ΠΑΡΑΓΓΕΛΙΕΣ',   value: w.orders_opened,        width: colPx.orders,    color: '#111315' },
                  { label: 'ΕΞ. ΤΡΑΠΕΖΙΩΝ', value: w.tables_served ?? 0,   width: colPx.tables,    color: '#111315' },
                  { label: 'ΑΝΤΙΚ. ΕΙΣΠΡ.', value: w.items_paid,            width: colPx.items,     color: '#111315' },
                  { label: 'ΕΙΣΠΡΑΞΗ',       value: fmt(w.total_collected),  width: colPx.collected, color: '#16a34a' },
                ].map(col => (
                  <div key={col.label} style={{
                    width: col.width, flexShrink: 0, textAlign: 'right', padding: '0 6px',
                  }}>
                    <div style={{ fontSize: 10, color: '#9ca3af', fontWeight: 600, whiteSpace: 'nowrap' }}>{col.label}</div>
                    <div style={{ fontSize: 15, fontWeight: 800, color: col.color, whiteSpace: 'nowrap' }}>{col.value}</div>
                  </div>
                ))}
              </div>

              {/* Chevron */}
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#9ca3af" strokeWidth="2.5"
                strokeLinecap="round" strokeLinejoin="round"
                style={{ flexShrink: 0, transform: isOpen ? 'rotate(180deg)' : 'none', transition: 'transform 200ms' }}>
                <polyline points="6 9 12 15 18 9" />
              </svg>
            </button>

            {isOpen && (
              <div style={{ borderTop: '1px solid #f0f0ef', background: '#fafafa', padding: '14px 18px', display: 'flex', flexDirection: 'column', gap: 8 }}>
                {/* Row 1: shift timing + payroll */}
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8 }}>
                  {[
                    { label: 'ΕΝΑΡΞΗ ΒΑΡΔΙΑΣ', value: fmtTime(w.shift_started_at), color: '#111315' },
                    {
                      label: 'ΛΗΞΗ ΒΑΡΔΙΑΣ',
                      value: w.shift_ended_at ? fmtTime(w.shift_ended_at) : 'Βάρδια Ενεργή',
                      color: w.shift_ended_at ? '#111315' : '#16a34a',
                    },
                    {
                      label: 'ΜΙΣΘΟΣ / ΩΡΑ',
                      value: w.hourly_rate_snapshot != null ? fmt(w.hourly_rate_snapshot) : '—',
                      color: '#111315',
                    },
                    {
                      label: 'ΜΙΣΘΟΣ (εως τώρα)',
                      value: w.shift_pay != null ? fmt(w.shift_pay) : 'Δεν παρακολ.',
                      color: w.shift_pay != null ? '#059669' : '#9ca3af',
                    },
                  ].map(cell => (
                    <div key={cell.label} style={{ background: 'white', border: '1px solid #e5e7eb', borderRadius: 8, padding: '9px 12px' }}>
                      <div style={{ fontSize: 10, color: '#9ca3af', fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{cell.label}</div>
                      <div style={{ fontSize: 14, fontWeight: 700, color: cell.color, marginTop: 2, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{cell.value}</div>
                    </div>
                  ))}
                </div>
                {/* Row 2: cash + collections */}
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8 }}>
                  {[
                    {
                      label: 'ΑΡΧΙΚΑ ΜΕΤΡΗΤΑ',
                      value: w.starting_cash != null ? fmt(w.starting_cash) : '—',
                      color: '#111315',
                    },
                    {
                      label: 'ΤΑΜΕΙΟ ΤΩΡΑ',
                      value: fmt(drawerNow),
                      color: '#3758c9',
                    },
                    {
                      label: 'ΑΝΤΙΚ. ΕΙΣΠΡ.',
                      value: w.items_paid,
                      color: '#111315',
                    },
                    {
                      label: 'ΕΞ. ΤΡΑΠΕΖΙΩΝ',
                      value: w.tables_served ?? 0,
                      color: '#111315',
                    },
                  ].map(cell => (
                    <div key={cell.label} style={{ background: 'white', border: '1px solid #e5e7eb', borderRadius: 8, padding: '9px 12px' }}>
                      <div style={{ fontSize: 10, color: '#9ca3af', fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{cell.label}</div>
                      <div style={{ fontSize: 14, fontWeight: 700, color: cell.color, marginTop: 2, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{cell.value}</div>
                    </div>
                  ))}
                </div>
                <PaymentBar w={w} total={w.total_collected} />
              </div>
            )}
          </div>
        )
      })}
    </div>
  )
}

function ZonesTab({ data }) {
  const maxRev = Math.max(...data.zones.map(z => z.revenue), 1)
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
      {data.zones.length === 0 && (
        <div style={{ textAlign: 'center', color: '#9ca3af', fontSize: 13, padding: '32px 0' }}>Δεν βρέθηκαν ζώνες</div>
      )}
      {data.zones.map(z => (
        <div key={z.group_id} style={{
          border: '1px solid #e5e7eb', borderRadius: 12,
          padding: '16px 18px', background: 'white',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
            <div style={{
              width: 12, height: 12, borderRadius: 3, flexShrink: 0,
              background: z.color || '#9ca3af',
            }} />
            <span style={{ fontSize: 14, fontWeight: 700, color: '#111315', flex: 1 }}>{z.group_name}</span>
            <span style={{ fontSize: 20, fontWeight: 800, color: '#111315' }}>{fmt(z.revenue)}</span>
          </div>

          <div style={{ height: 6, background: '#f3f4f6', borderRadius: 99, marginBottom: 12, overflow: 'hidden' }}>
            <div style={{
              height: '100%', borderRadius: 99,
              background: z.color || '#9ca3af',
              width: `${Math.round((z.revenue / maxRev) * 100)}%`,
              transition: 'width 400ms ease',
            }} />
          </div>

          <div style={{ display: 'flex', gap: 20 }}>
            <div>
              <span style={{ fontSize: 11, color: '#9ca3af', fontWeight: 600 }}>ΠΑΡΑΓΓΕΛΙΕΣ </span>
              <span style={{ fontSize: 14, fontWeight: 700 }}>{z.orders}</span>
            </div>
            <div>
              <span style={{ fontSize: 11, color: '#9ca3af', fontWeight: 600 }}>ΑΝΤΙΚΕΙΜΕΝΑ </span>
              <span style={{ fontSize: 14, fontWeight: 700 }}>{z.items}</span>
            </div>
            {z.orders > 0 && (
              <div>
                <span style={{ fontSize: 11, color: '#9ca3af', fontWeight: 600 }}>Μ.Ο./ΠΑΡΑΓ. </span>
                <span style={{ fontSize: 14, fontWeight: 700 }}>{fmt(z.revenue / z.orders)}</span>
              </div>
            )}
          </div>
        </div>
      ))}
    </div>
  )
}

function PrintersTab({ data }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
      {data.printers.length === 0 && (
        <div style={{ textAlign: 'center', color: '#9ca3af', fontSize: 13, padding: '32px 0' }}>Δεν βρέθηκαν δεδομένα εκτύπωσης</div>
      )}
      {data.printers.map(p => {
        const successRate = p.jobs > 0 ? Math.round((p.success / p.jobs) * 100) : 0
        return (
          <div key={p.printer_id} style={{
            border: '1px solid #e5e7eb', borderRadius: 12,
            padding: '16px 18px', background: 'white',
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 12 }}>
              <div style={{
                width: 36, height: 36, borderRadius: 9, flexShrink: 0,
                background: '#f3f4f6', display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#6b7280" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <polyline points="6 9 6 2 18 2 18 9" />
                  <path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2" />
                  <rect x="6" y="14" width="12" height="8" />
                </svg>
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 14, fontWeight: 700, color: '#111315' }}>{p.printer_name}</div>
                <div style={{ fontSize: 11, color: '#9ca3af' }}>{p.ip_address}</div>
              </div>
              <div style={{ textAlign: 'right' }}>
                <div style={{ fontSize: 18, fontWeight: 800, color: '#111315' }}>{fmt(p.items_value)}</div>
                <div style={{ fontSize: 11, color: '#9ca3af', marginTop: 1 }}>αξία εκτυπ.</div>
              </div>
              <span style={{
                fontSize: 12, fontWeight: 700, padding: '3px 10px', borderRadius: 99, marginLeft: 4,
                background: successRate === 100 ? '#dcfce7' : successRate >= 80 ? '#fef9c3' : '#fee2e2',
                color: successRate === 100 ? '#16a34a' : successRate >= 80 ? '#a16207' : '#dc2626',
              }}>{successRate}%</span>
            </div>

            <div style={{ height: 6, background: '#f3f4f6', borderRadius: 99, marginBottom: 12, overflow: 'hidden' }}>
              <div style={{ height: '100%', display: 'flex' }}>
                <div style={{ flex: p.success, background: '#16a34a' }} />
                <div style={{ flex: p.failed, background: '#dc2626' }} />
              </div>
            </div>

            <div style={{ display: 'flex', gap: 20 }}>
              <div><span style={{ fontSize: 11, color: '#9ca3af', fontWeight: 600 }}>ΕΡΓΑΣΙΕΣ </span><span style={{ fontSize: 14, fontWeight: 700 }}>{p.jobs}</span></div>
              <div><span style={{ fontSize: 11, color: '#16a34a', fontWeight: 600 }}>ΕΠΙΤΥΧΕΙΣ </span><span style={{ fontSize: 14, fontWeight: 700 }}>{p.success}</span></div>
              {p.failed > 0 && <div><span style={{ fontSize: 11, color: '#dc2626', fontWeight: 600 }}>ΑΠΟΤΥΧΕΣ </span><span style={{ fontSize: 14, fontWeight: 700 }}>{p.failed}</span></div>}
            </div>
          </div>
        )
      })}
    </div>
  )
}

function CashReconciliationTab({ data, storeCash, onStoreCashChange }) {
  const expected = data.store_expected_closing ?? 0
  const counted = storeCash !== '' ? parseFloat(storeCash) : null
  const discrepancy = counted != null ? counted - expected : null
  const isShort = discrepancy != null && discrepancy < -0.005
  const isOver  = discrepancy != null && discrepancy > 0.005
  const isClean = discrepancy != null && !isShort && !isOver

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      <div style={{ border: '1px solid #e5e7eb', borderRadius: 12, padding: '16px 18px', background: '#f9fafb' }}>
        <div style={{ fontSize: 11, fontWeight: 700, color: '#9ca3af', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 10 }}>Σύνοψη Εισπράξεων Βάρδιας</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6, fontSize: 13.5 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between' }}>
            <span style={{ color: '#6b7280' }}>Σύνολο εισπράξεων σερβιτόρων</span>
            <span style={{ fontWeight: 700, color: '#111315' }}>{fmt(data.total_waiter_collected)}</span>
          </div>
          {data.store_opening_cash != null && (
            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
              <span style={{ color: '#6b7280' }}>Αρχικό ταμείο</span>
              <span style={{ fontWeight: 600, color: '#111315' }}>{fmt(data.store_opening_cash)}</span>
            </div>
          )}
          <div style={{ display: 'flex', justifyContent: 'space-between', borderTop: '1px solid #e5e7eb', paddingTop: 6, marginTop: 2 }}>
            <span style={{ color: '#374151', fontWeight: 600 }}>Αναμενόμενο ταμείο τώρα</span>
            <span style={{ fontWeight: 800, color: '#111315', fontSize: 15 }}>{fmt(expected)}</span>
          </div>
        </div>
      </div>

      <div>
        <label style={{ fontSize: 13, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 6 }}>
          Μετρήστε το ταμείο — πόσα μετρητά υπάρχουν;
          <span style={{ fontWeight: 400, color: '#9ca3af' }}> (προαιρετικό)</span>
        </label>
        <input
          type="number"
          step="0.01"
          min="0"
          value={storeCash}
          onChange={e => onStoreCashChange(e.target.value)}
          placeholder="0.00"
          style={{
            width: '100%', padding: '10px 14px', border: '1.5px solid #e5e7eb',
            borderRadius: 10, fontSize: 18, fontWeight: 700, color: '#111315',
            outline: 'none', boxSizing: 'border-box', background: 'white',
          }}
        />
      </div>

      {discrepancy != null && (
        <div style={{
          padding: '14px 16px', borderRadius: 10,
          background: isClean ? '#f0fdf4' : '#fef2f2',
          border: `1.5px solid ${isClean ? '#86efac' : '#fca5a5'}`,
        }}>
          <div style={{ fontSize: 14, fontWeight: 700, color: isClean ? '#16a34a' : '#dc2626', marginBottom: 4 }}>
            {isClean && '✓ Ταμείο εντάξει'}
            {isShort && `⚠ Έλλειμμα ${fmt(Math.abs(discrepancy))}`}
            {isOver  && `⚠ Πλεόνασμα ${fmt(Math.abs(discrepancy))}`}
          </div>
          <div style={{ fontSize: 12.5, color: isClean ? '#166534' : '#7f1d1d', lineHeight: 1.5 }}>
            {isClean && 'Το φυσικό ταμείο συμφωνεί με τις καταγεγραμμένες εισπράξεις.'}
            {isShort && `Το ταμείο έχει ${fmt(Math.abs(discrepancy))} λιγότερα από το αναμενόμενο. Το κενό δεν αποδίδεται σε κάποιον σερβιτόρο συγκεκριμένα.`}
            {isOver  && `Το ταμείο έχει ${fmt(Math.abs(discrepancy))} περισσότερα από το αναμενόμενο.`}
          </div>
        </div>
      )}

      {storeCash === '' && (
        <p style={{ fontSize: 12, color: '#9ca3af', margin: 0 }}>
          Αν παραλείψετε τη μέτρηση, η επαλήθευση δεν θα καταγραφεί.
        </p>
      )}
    </div>
  )
}

function ChecksTab({ data, onForceClose, closing, isOpen }) {
  const { checks } = data
  const allGood = checks.open_orders === 0
  const hasUnpaid = checks.with_unpaid_items > 0
  const hasActiveShifts = checks.active_shifts > 0

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>

      <div style={{
        border: `1px solid ${checks.open_orders > 0 ? '#fecaca' : '#bbf7d0'}`,
        borderRadius: 12, padding: '16px 18px', background: checks.open_orders > 0 ? '#fff5f5' : '#f0fdf4',
        display: 'flex', alignItems: 'flex-start', gap: 12,
      }}>
        <div style={{
          width: 34, height: 34, borderRadius: 99, flexShrink: 0, marginTop: 1,
          background: checks.open_orders > 0 ? '#fee2e2' : '#dcfce7',
          display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 15,
        }}>
          {checks.open_orders > 0 ? '⚠️' : '✓'}
        </div>
        <div>
          <div style={{ fontSize: 14, fontWeight: 700, color: '#111315' }}>Ανοιχτά Τραπέζια</div>
          {checks.open_orders > 0 ? (
            <div style={{ fontSize: 13, color: '#dc2626', marginTop: 2 }}>
              {checks.open_orders} τραπέζια ακόμα ανοιχτά
              {hasUnpaid && ` · ${checks.with_unpaid_items} με απλήρωτα αντικείμενα`}
            </div>
          ) : (
            <div style={{ fontSize: 13, color: '#16a34a', marginTop: 2 }}>Όλα τα τραπέζια έχουν κλείσει</div>
          )}
        </div>
      </div>

      <div style={{
        border: `1px solid ${hasActiveShifts ? '#fde68a' : '#bbf7d0'}`,
        borderRadius: 12, padding: '16px 18px', background: hasActiveShifts ? '#fffbeb' : '#f0fdf4',
        display: 'flex', alignItems: 'flex-start', gap: 12,
      }}>
        <div style={{
          width: 34, height: 34, borderRadius: 99, flexShrink: 0, marginTop: 1,
          background: hasActiveShifts ? '#fef3c7' : '#dcfce7',
          display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 15,
        }}>
          {hasActiveShifts ? '⏳' : '✓'}
        </div>
        <div>
          <div style={{ fontSize: 14, fontWeight: 700, color: '#111315' }}>Ενεργές Βάρδιες</div>
          {hasActiveShifts ? (
            <div style={{ fontSize: 13, color: '#92400e', marginTop: 2 }}>
              {checks.active_shifts} βάρδι{checks.active_shifts === 1 ? 'α' : 'ες'} ακόμα ενεργ{checks.active_shifts === 1 ? 'ή' : 'ές'} — θα κλείσουν αυτόματα
            </div>
          ) : (
            <div style={{ fontSize: 13, color: '#16a34a', marginTop: 2 }}>Δεν υπάρχουν ενεργές βάρδιες</div>
          )}
        </div>
      </div>

      {allGood ? (
        <div style={{
          border: '1px solid #bbf7d0', borderRadius: 12, padding: '16px 18px',
          background: '#f0fdf4', display: 'flex', alignItems: 'center', gap: 10,
        }}>
          <span style={{ fontSize: 20 }}>✅</span>
          <div style={{ fontSize: 14, fontWeight: 600, color: '#166534' }}>
            Ο έλεγχος πέρασε — η ημέρα είναι έτοιμη να κλείσει.
          </div>
        </div>
      ) : hasUnpaid ? (
        <div style={{ border: '1px solid #fecaca', borderRadius: 12, padding: '16px 18px', background: '#fff5f5' }}>
          <div style={{ fontSize: 13, color: '#7f1d1d', lineHeight: 1.5 }}>
            <strong>Προσοχή:</strong> Υπάρχουν απλήρωτα αντικείμενα. Αν κλείσετε αναγκαστικά, τα απλήρωτα ποσά δεν θα καταγραφούν στις αναφορές.
          </div>
        </div>
      ) : (
        <div style={{ border: '1px solid #fde68a', borderRadius: 12, padding: '16px 18px', background: '#fffbeb' }}>
          <div style={{ fontSize: 13, color: '#78350f', lineHeight: 1.5 }}>
            Υπάρχουν ανοιχτά τραπέζια χωρίς απλήρωτα αντικείμενα. Θα κλείσουν αυτόματα.
          </div>
        </div>
      )}

      {isOpen && (
        <button
          onClick={onForceClose}
          disabled={closing}
          style={{
            marginTop: 4, height: 46, borderRadius: 10, border: 'none',
            cursor: closing ? 'default' : 'pointer',
            background: hasUnpaid ? '#dc2626' : '#111315',
            color: 'white', fontSize: 14, fontWeight: 700,
            opacity: closing ? 0.7 : 1, transition: 'opacity 150ms',
          }}
        >
          {closing ? 'Κλείσιμο…' : hasUnpaid ? '⚠ Αναγκαστικό Κλείσιμο' : 'Κλείσε Ημέρα'}
        </button>
      )}
    </div>
  )
}

// ── Main modal ────────────────────────────────────────────────────────────────

export default function WorkdaySummaryModal({ dayId, onClose, showCloseAction = false, onDayClosed }) {
  const [tab, setTab] = useState('overview')
  const [closing, setClosing] = useState(false)
  const [storeCash, setStoreCash] = useState('')  // Phase 2E: store cash count

  const { data, isLoading, error } = useQuery({
    queryKey: ['workday-summary', dayId ?? 'current'],
    queryFn: () => client.get('/api/business-day/summary' + (dayId ? `?day_id=${dayId}` : '')).then(r => r.data),
    refetchInterval: showCloseAction ? 15_000 : false,
  })

  async function handleClose(force = false) {
    setClosing(true)
    try {
      const payload = { force }
      if (storeCash !== '') payload.store_closing_cash = parseFloat(storeCash)
      await client.post('/api/business-day/close', payload)
      onDayClosed?.()
    } catch (e) {
      const detail = e.response?.data?.detail
      if (e.response?.status === 409 && detail?.open_orders) {
        setTab('checks')
      } else {
        toast.error(typeof detail === 'string' ? detail : 'Σφάλμα κλεισίματος')
      }
    } finally {
      setClosing(false)
    }
  }

  const tabs = [
    { id: 'overview',  label: 'Επισκόπηση' },
    { id: 'waiters',   label: 'Προσωπικό', badge: data?.waiters?.length },
    { id: 'zones',     label: 'Ζώνες',     badge: data?.zones?.length },
    { id: 'printers',  label: 'Εκτυπωτές', badge: data?.printers?.length },
    ...(showCloseAction ? [
      { id: 'cash', label: 'Ταμείο' },
      {
        id: 'checks', label: 'Έλεγχοι',
        badge: data?.checks ? (data.checks.open_orders + data.checks.active_shifts) : null,
        warn: data?.checks?.with_unpaid_items > 0,
      },
    ] : []),
  ]

  const isOpen = data?.status === 'open'

  return (
    <div
      style={{
        position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.45)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        zIndex: 1000, padding: 16,
      }}
      onClick={e => { if (e.target === e.currentTarget) onClose() }}
    >
      <div style={{
        background: 'white', borderRadius: 16, width: '100%', maxWidth: 760,
        maxHeight: '92vh', display: 'flex', flexDirection: 'column',
        boxShadow: '0 20px 60px rgba(0,0,0,0.18)',
        overflow: 'hidden',
      }}>
        {/* Header */}
        <div style={{
          padding: '20px 24px 0', borderBottom: '1px solid #f0f0ef',
          display: 'flex', flexDirection: 'column', gap: 0,
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 14 }}>
            <div style={{
              width: 36, height: 36, borderRadius: 9, background: '#111315',
              display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
            }}>
              <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
                <rect x="3" y="3" width="18" height="18" rx="2" ry="2" />
                <line x1="3" y1="9" x2="21" y2="9" />
                <line x1="9" y1="21" x2="9" y2="9" />
              </svg>
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 17, fontWeight: 800, color: '#111315' }}>
                {showCloseAction ? 'Κλείσιμο Εργάσιμης Ημέρας' : 'Στατιστικά Ημέρας'}
              </div>
              {data && (
                <div style={{ fontSize: 11, color: '#9ca3af', marginTop: 1 }}>
                  {data.status === 'open'
                    ? <span style={{ color: '#16a34a', fontWeight: 600 }}>● Ημέρα Ενεργή</span>
                    : <span>Κλειστή</span>
                  }
                  {' · '}Άνοιγμα {fmtDateTime(data?.opened_at)}
                </div>
              )}
            </div>
            <button
              onClick={onClose}
              style={{
                width: 32, height: 32, borderRadius: 8, border: '1px solid #e5e7eb',
                background: 'white', cursor: 'pointer', display: 'flex',
                alignItems: 'center', justifyContent: 'center', flexShrink: 0,
              }}
            >
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#6b7280" strokeWidth="2.5" strokeLinecap="round">
                <line x1="18" y1="6" x2="6" y2="18" /><line x1="6" y1="6" x2="18" y2="18" />
              </svg>
            </button>
          </div>

          <div style={{ display: 'flex', gap: 0, overflowX: 'auto' }}>
            {tabs.map(t => (
              <TabBtn key={t.id} label={t.label} active={tab === t.id}
                onClick={() => setTab(t.id)} badge={t.badge} warn={t.warn} />
            ))}
          </div>
        </div>

        {/* Body */}
        <div style={{ flex: 1, overflowY: 'auto', padding: '22px 24px' }}>
          {isLoading && (
            <div style={{ textAlign: 'center', color: '#9ca3af', fontSize: 13, padding: '48px 0' }}>Φόρτωση…</div>
          )}
          {error && (
            <div style={{ textAlign: 'center', color: '#dc2626', fontSize: 13, padding: '48px 0' }}>Σφάλμα φόρτωσης δεδομένων</div>
          )}
          {data && (
            <>
              {tab === 'overview'  && <OverviewTab data={data} />}
              {tab === 'waiters'   && <WaitersTab  data={data} />}
              {tab === 'zones'     && <ZonesTab    data={data} />}
              {tab === 'printers'  && <PrintersTab data={data} />}
              {tab === 'cash'      && (
                <CashReconciliationTab
                  data={data}
                  storeCash={storeCash}
                  onStoreCashChange={setStoreCash}
                />
              )}
              {tab === 'checks'    && (
                <ChecksTab
                  data={data}
                  isOpen={isOpen}
                  onForceClose={() => handleClose(data.checks.open_orders > 0)}
                  closing={closing}
                />
              )}
            </>
          )}
        </div>

        {/* Footer — only shown when in close-flow and not already on checks tab */}
        {showCloseAction && data && tab !== 'checks' && (
          <div style={{
            padding: '14px 24px', borderTop: '1px solid #f0f0ef',
            display: 'flex', gap: 10, justifyContent: 'flex-end', background: 'white',
          }}>
            <button onClick={onClose} style={{
              height: 40, padding: '0 18px', borderRadius: 9,
              border: '1px solid #e5e7eb', background: 'white',
              fontSize: 13, fontWeight: 600, cursor: 'pointer', color: '#374151',
            }}>Ακύρωση</button>
            {tab !== 'cash' ? (
              <button onClick={() => setTab('cash')} style={{
                height: 40, padding: '0 20px', borderRadius: 9,
                background: '#111315', border: 'none', color: 'white',
                fontSize: 13, fontWeight: 700, cursor: 'pointer',
              }}>Μέτρηση Ταμείου →</button>
            ) : (
              <button onClick={() => setTab('checks')} style={{
                height: 40, padding: '0 20px', borderRadius: 9,
                background: '#111315', border: 'none', color: 'white',
                fontSize: 13, fontWeight: 700, cursor: 'pointer',
              }}>Προχωρήστε στους Ελέγχους →</button>
            )}
          </div>
        )}
      </div>
    </div>
  )
}
