// AdminPanel.jsx — Yönetim paneli (Genel, Analitik, Masalar, Menü, Kullanıcılar, Sistem)
const { useState, useEffect, useMemo } = React;

// ============================================================================
// Helpers
// ============================================================================

const PALETTE = ['#E8590C', '#16A34A', '#7C3AED', '#0EA5E9', '#EC4899', '#14B8A6', '#EAB308', '#F97316', '#84CC16'];

function pctChange(curr, prev) {
  if (!prev || prev === 0) return curr ? 100 : null;
  return ((curr - prev) / prev) * 100;
}

function ymd(d) {
  const x = new Date(d);
  const y = x.getFullYear();
  const m = String(x.getMonth() + 1).padStart(2, '0');
  const day = String(x.getDate()).padStart(2, '0');
  return `${y}-${m}-${day}`;
}

function startOfDay(d) {
  const x = new Date(d);
  x.setHours(0, 0, 0, 0);
  return x;
}

function addDays(d, n) {
  const x = new Date(d);
  x.setDate(x.getDate() + n);
  return x;
}

function startOfMonth(d) {
  const x = new Date(d);
  x.setDate(1); x.setHours(0, 0, 0, 0);
  return x;
}

function dateRangeFromPreset(preset, customFrom, customTo) {
  const now = new Date();
  const today0 = startOfDay(now);
  switch (preset) {
    case 'today':
      return { from: today0, to: addDays(today0, 1), label: 'Bugün', days: 1 };
    case 'yesterday':
      return { from: addDays(today0, -1), to: today0, label: 'Dün', days: 1 };
    case '7d':
      return { from: addDays(today0, -6), to: addDays(today0, 1), label: 'Son 7 Gün', days: 7 };
    case '30d':
      return { from: addDays(today0, -29), to: addDays(today0, 1), label: 'Son 30 Gün', days: 30 };
    case 'month': {
      const f = startOfMonth(now);
      return { from: f, to: addDays(today0, 1), label: 'Bu Ay', days: Math.max(1, Math.round((addDays(today0, 1) - f) / 86400000)) };
    }
    case 'custom': {
      const f = customFrom ? startOfDay(new Date(customFrom)) : today0;
      const t = customTo ? addDays(startOfDay(new Date(customTo)), 1) : addDays(today0, 1);
      const days = Math.max(1, Math.round((t - f) / 86400000));
      const fmtD = (d) => d.toLocaleDateString('tr-TR', { day: 'numeric', month: 'short' });
      return { from: f, to: t, label: `${fmtD(f)} → ${fmtD(addDays(t, -1))}`, days };
    }
    default:
      return dateRangeFromPreset('today');
  }
}

function previousRange(range) {
  const span = range.to - range.from;
  return { from: new Date(range.from.getTime() - span), to: new Date(range.to.getTime() - span) };
}

function filterOrders(orders, from, to) {
  return orders.filter(o => {
    const d = new Date(o.closedAt);
    return d >= from && d < to;
  });
}

function aggregate(orders) {
  let revenue = 0, count = orders.length, items = 0, cash = 0, card = 0;
  for (const o of orders) {
    revenue += o.total;
    if (o.paymentMethod === 'cash') cash += o.total; else card += o.total;
    for (const it of o.items) items += it.qty;
  }
  return { revenue, count, items, cash, card, avg: count ? revenue / count : 0 };
}

function groupByDay(orders, from, to) {
  const days = [];
  for (let d = new Date(from); d < to; d = addDays(d, 1)) {
    days.push({ date: new Date(d), key: ymd(d), orders: [] });
  }
  for (const o of orders) {
    const k = ymd(new Date(o.closedAt));
    const day = days.find(d => d.key === k);
    if (day) day.orders.push(o);
  }
  return days.map(d => ({ ...d, ...aggregate(d.orders) }));
}

function groupByHour(orders) {
  const hours = Array.from({ length: 24 }, (_, h) => ({ h, orders: [] }));
  for (const o of orders) {
    const h = new Date(o.closedAt).getHours();
    hours[h].orders.push(o);
  }
  return hours.map(({ h, orders }) => ({ h, ...aggregate(orders) }));
}

function groupByWaiter(orders) {
  const m = {};
  for (const o of orders) {
    const w = o.waiter || '—';
    if (!m[w]) m[w] = { name: w, orders: [], itemCounts: {} };
    m[w].orders.push(o);
    for (const it of o.items) m[w].itemCounts[it.name] = (m[w].itemCounts[it.name] || 0) + it.qty;
  }
  return Object.values(m).map(w => {
    const agg = aggregate(w.orders);
    const top = Object.entries(w.itemCounts).sort((a, b) => b[1] - a[1])[0];
    return { ...w, ...agg, topItem: top ? { name: top[0], qty: top[1] } : null };
  }).sort((a, b) => b.revenue - a.revenue);
}

function groupByItem(orders, top = 8) {
  const m = {};
  for (const o of orders) for (const it of o.items) {
    if (!m[it.name]) m[it.name] = { name: it.name, qty: 0, revenue: 0 };
    m[it.name].qty += it.qty;
    m[it.name].revenue += it.qty * it.price;
  }
  return Object.values(m).sort((a, b) => b.qty - a.qty).slice(0, top);
}

function groupByCategory(orders) {
  const menu = Store.getMenu();
  const itemCat = {};
  menu.forEach(m => { itemCat[m.name] = m.cat; });
  const m = {};
  for (const o of orders) for (const it of o.items) {
    const cat = itemCat[it.name] || 'Diğer';
    if (!m[cat]) m[cat] = { name: cat, qty: 0, revenue: 0 };
    m[cat].qty += it.qty;
    m[cat].revenue += it.qty * it.price;
  }
  return Object.values(m).sort((a, b) => b.revenue - a.revenue);
}

// ============================================================================
// Generic UI components
// ============================================================================

function Section({ title, subtitle, action, children, padded = true }) {
  return (
    <div style={{
      background: 'white', borderRadius: 14,
      border: '1px solid var(--border)', boxShadow: 'var(--shadow)',
      overflow: 'hidden',
    }}>
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '14px 18px', borderBottom: '1px solid var(--border)',
        gap: 10, flexWrap: 'wrap',
      }}>
        <div style={{ minWidth: 0 }}>
          <div style={{ fontSize: 14, fontWeight: 700, letterSpacing: '-0.01em' }}>{title}</div>
          {subtitle && <div style={{ fontSize: 11, color: 'var(--text-3)', marginTop: 2 }}>{subtitle}</div>}
        </div>
        {action}
      </div>
      <div style={{ padding: padded ? 18 : 0 }}>{children}</div>
    </div>
  );
}

function StatCard({ label, value, sub, accent = 'var(--accent)', icon, trend }) {
  return (
    <div style={{
      background: 'white', borderRadius: 14, padding: '16px 18px',
      boxShadow: 'var(--shadow)', border: '1px solid var(--border)',
      display: 'flex', flexDirection: 'column', gap: 4,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        {icon && <span style={{ fontSize: 14 }}>{icon}</span>}
        <span style={{ fontSize: 11, color: 'var(--text-2)', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.05em' }}>{label}</span>
      </div>
      <div style={{ fontSize: 24, fontWeight: 800, color: accent, letterSpacing: '-0.02em', lineHeight: 1.1, marginTop: 2 }}>{value}</div>
      {(sub || trend !== undefined) && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 4 }}>
          {trend !== undefined && trend !== null && (
            <span style={{
              fontSize: 11, fontWeight: 700, padding: '2px 6px', borderRadius: 4,
              background: trend >= 0 ? 'var(--green-bg)' : '#FEF2F2',
              color: trend >= 0 ? 'var(--green)' : 'var(--red)',
            }}>
              {trend >= 0 ? '▲' : '▼'} {Math.abs(Math.round(trend))}%
            </span>
          )}
          {sub && <span style={{ fontSize: 11, color: 'var(--text-3)', fontWeight: 500 }}>{sub}</span>}
        </div>
      )}
    </div>
  );
}

function FilterPill({ active, onClick, children }) {
  return (
    <button onClick={onClick} style={{
      padding: '7px 14px', borderRadius: 20,
      border: '1.5px solid', borderColor: active ? 'var(--accent)' : 'var(--border)',
      background: active ? 'var(--accent-light)' : 'white',
      color: active ? 'var(--accent)' : 'var(--text-2)',
      fontFamily: 'inherit', fontSize: 13, fontWeight: 700, cursor: 'pointer',
      whiteSpace: 'nowrap', transition: 'all 0.12s',
    }}>{children}</button>
  );
}

function EmptyState({ icon = '📊', message, sub }) {
  return (
    <div style={{ textAlign: 'center', padding: '32px 20px', color: 'var(--text-3)' }}>
      <div style={{ fontSize: 36 }}>{icon}</div>
      <div style={{ fontSize: 14, fontWeight: 600, marginTop: 8, color: 'var(--text-2)' }}>{message}</div>
      {sub && <div style={{ fontSize: 12, marginTop: 4 }}>{sub}</div>}
    </div>
  );
}

function ConfirmDialog({ title, message, confirmLabel = 'Onayla', danger, onConfirm, onCancel }) {
  return (
    <div className="modal-overlay" onClick={onCancel}>
      <div className="modal-box" style={{ width: 380, padding: 26 }} onClick={e => e.stopPropagation()}>
        <div style={{ fontSize: 36, textAlign: 'center', marginBottom: 8 }}>⚠️</div>
        <div style={{ fontWeight: 700, fontSize: 17, textAlign: 'center', marginBottom: 8 }}>{title}</div>
        <div style={{ color: 'var(--text-2)', fontSize: 14, textAlign: 'center', marginBottom: 20, lineHeight: 1.5 }}>{message}</div>
        <div style={{ display: 'flex', gap: 10 }}>
          <button className="btn btn-ghost" style={{ flex: 1 }} onClick={onCancel}>İptal</button>
          <button className={danger ? 'btn btn-danger' : 'btn btn-primary'} style={{ flex: 1 }} onClick={onConfirm}>{confirmLabel}</button>
        </div>
      </div>
    </div>
  );
}

// ============================================================================
// Charts
// ============================================================================

function BarChart({ data, height = 200, format = (v) => v, color = 'var(--accent)' }) {
  const max = Math.max(...data.map(d => d.value), 1);
  const [hover, setHover] = useState(null);
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'flex-end', height, gap: 4, paddingBottom: 6, borderBottom: '1px solid var(--border)' }}>
        {data.map((d, i) => {
          const pct = (d.value / max) * 100;
          const isHover = hover === i;
          return (
            <div key={i} style={{
              flex: 1, minWidth: 0, height: '100%',
              display: 'flex', flexDirection: 'column', justifyContent: 'flex-end', alignItems: 'center',
              position: 'relative', cursor: 'pointer',
            }}
              onMouseEnter={() => setHover(i)} onMouseLeave={() => setHover(null)}
              onTouchStart={() => setHover(i)}
            >
              {isHover && (
                <div style={{
                  position: 'absolute', bottom: 'calc(100% + 8px)', left: '50%', transform: 'translateX(-50%)',
                  background: 'var(--text)', color: 'white',
                  padding: '6px 10px', borderRadius: 6, fontSize: 12, fontWeight: 600,
                  whiteSpace: 'nowrap', pointerEvents: 'none', zIndex: 10,
                }}>
                  <div style={{ fontWeight: 600, fontSize: 11, opacity: 0.85 }}>{d.tooltip || d.label}</div>
                  <div style={{ fontWeight: 700, fontSize: 13, marginTop: 1 }}>{format(d.value)}</div>
                </div>
              )}
              <div style={{
                width: '100%', maxWidth: 36,
                height: pct ? `max(2px, ${pct}%)` : 2,
                background: d.value > 0 ? (isHover ? color : color + 'cc') : 'var(--border)',
                borderRadius: '4px 4px 0 0',
                transition: 'background 0.15s',
              }} />
            </div>
          );
        })}
      </div>
      <div style={{ display: 'flex', gap: 4, marginTop: 6 }}>
        {data.map((d, i) => (
          <div key={i} style={{
            flex: 1, fontSize: 10, color: 'var(--text-3)', textAlign: 'center',
            whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', fontWeight: 500,
          }}>{d.label}</div>
        ))}
      </div>
    </div>
  );
}

function LineChart({ data, height = 200, format = (v) => v, color = 'var(--accent)' }) {
  const max = Math.max(...data.map(d => d.value), 1);
  const [hover, setHover] = useState(null);
  const W = 100, H = 100;
  const pts = data.map((d, i) => {
    const xpct = data.length > 1 ? (i / (data.length - 1)) * W : W / 2;
    const ypct = (d.value / max) * H;
    return { xpct, ypct, ...d };
  });
  const svgPts = pts.map(p => `${p.xpct},${H - p.ypct}`).join(' ');
  const areaPts = `0,${H} ${svgPts} ${W},${H}`;
  return (
    <div>
      <div style={{ position: 'relative', height, paddingBottom: 4, borderBottom: '1px solid var(--border)' }}>
        <svg viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" style={{ width: '100%', height: '100%', display: 'block' }}>
          <defs>
            <linearGradient id={`lc-grad-${color.replace(/[^a-z0-9]/gi, '')}`} x1="0" x2="0" y1="0" y2="1">
              <stop offset="0%" stopColor={color} stopOpacity="0.3" />
              <stop offset="100%" stopColor={color} stopOpacity="0" />
            </linearGradient>
          </defs>
          <polygon points={areaPts} fill={`url(#lc-grad-${color.replace(/[^a-z0-9]/gi, '')})`} />
          <polyline points={svgPts} fill="none" stroke={color} strokeWidth="2.5"
            vectorEffect="non-scaling-stroke" strokeLinejoin="round" strokeLinecap="round" />
        </svg>
        {pts.map((p, i) => (
          <div key={i}
            onMouseEnter={() => setHover(i)} onMouseLeave={() => setHover(null)}
            onTouchStart={() => setHover(i)}
            style={{
              position: 'absolute', top: `${100 - p.ypct}%`, left: `${p.xpct}%`,
              width: 16, height: 16, marginLeft: -8, marginTop: -8,
              cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
            <div style={{
              width: hover === i ? 12 : 8, height: hover === i ? 12 : 8,
              background: color, borderRadius: '50%',
              border: '2px solid white', boxShadow: '0 1px 3px rgba(0,0,0,0.15)',
              transition: 'all 0.15s',
            }} />
          </div>
        ))}
        {hover !== null && (() => {
          const p = pts[hover];
          const isRight = p.xpct > 70;
          return (
            <div style={{
              position: 'absolute', top: `${100 - p.ypct}%`, left: `${p.xpct}%`,
              transform: `translate(${isRight ? '-100%' : '0'}, calc(-100% - 18px))`,
              background: 'var(--text)', color: 'white',
              padding: '6px 10px', borderRadius: 6, fontSize: 12, fontWeight: 600,
              whiteSpace: 'nowrap', pointerEvents: 'none', zIndex: 10,
            }}>
              <div style={{ fontWeight: 600, fontSize: 11, opacity: 0.85 }}>{p.tooltip || p.label}</div>
              <div style={{ fontWeight: 700, fontSize: 13, marginTop: 1 }}>{format(p.value)}</div>
            </div>
          );
        })()}
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 6, fontSize: 10, color: 'var(--text-3)', fontWeight: 500 }}>
        {data.map((d, i) => (
          <span key={i} style={{
            flex: 1,
            textAlign: i === 0 ? 'left' : i === data.length - 1 ? 'right' : 'center',
          }}>{d.label}</span>
        ))}
      </div>
    </div>
  );
}

function DonutChart({ data, size = 140, centerLabel, centerValue }) {
  const sum = data.reduce((s, d) => s + d.value, 0) || 1;
  const r = 40, cx = 50, cy = 50;
  const C = 2 * Math.PI * r;
  let offset = 0;
  return (
    <div style={{ position: 'relative', width: size, height: size, flexShrink: 0 }}>
      <svg viewBox="0 0 100 100" style={{ width: '100%', height: '100%', transform: 'rotate(-90deg)' }}>
        <circle cx={cx} cy={cy} r={r} fill="none" stroke="var(--border)" strokeWidth="14" />
        {data.map((d, i) => {
          const len = (d.value / sum) * C;
          const dash = `${len} ${C - len}`;
          const elem = (
            <circle key={i} cx={cx} cy={cy} r={r} fill="none"
              stroke={d.color || PALETTE[i % PALETTE.length]} strokeWidth="14"
              strokeDasharray={dash} strokeDashoffset={-offset}
              style={{ transition: 'stroke-dasharray 0.4s' }} />
          );
          offset += len;
          return elem;
        })}
      </svg>
      <div style={{
        position: 'absolute', inset: 0,
        display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
      }}>
        {centerLabel && <div style={{ fontSize: 10, color: 'var(--text-3)', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.05em' }}>{centerLabel}</div>}
        {centerValue && <div style={{ fontSize: 16, fontWeight: 800, color: 'var(--text)' }}>{centerValue}</div>}
      </div>
    </div>
  );
}

function HBarList({ items, format = (v) => v, color = 'var(--accent)', emptyMessage = 'Veri yok' }) {
  if (!items.length) return <EmptyState icon="📭" message={emptyMessage} />;
  const max = Math.max(...items.map(i => i.value), 1);
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
      {items.map((it, i) => (
        <div key={i}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 5, gap: 8 }}>
            <span style={{ fontSize: 13, fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{it.label}</span>
            <span style={{ fontSize: 13, fontWeight: 700, color: 'var(--text)', flexShrink: 0 }}>{format(it.value)}</span>
          </div>
          <div style={{ height: 6, borderRadius: 3, background: 'var(--border)', overflow: 'hidden' }}>
            <div style={{ width: `${(it.value / max) * 100}%`, height: '100%', background: it.color || color, transition: 'width 0.4s', borderRadius: 3 }} />
          </div>
        </div>
      ))}
    </div>
  );
}

// ============================================================================
// Tabs
// ============================================================================

// ----- Dashboard -----
function DashboardTab({ onJumpToAnalytics }) {
  const orders = Store.getOrders();
  const tables = Store.getTables();
  const today = dateRangeFromPreset('today');
  const yesterday = dateRangeFromPreset('yesterday');
  const todayOrders = filterOrders(orders, today.from, today.to);
  const yOrders = filterOrders(orders, yesterday.from, yesterday.to);
  const a = aggregate(todayOrders);
  const yA = aggregate(yOrders);

  const occupied = tables.filter(t => t.occupied).length;
  const occupiedRevenue = tables.reduce((s, t) => s + (t.orders || []).reduce((ss, o) => ss + o.price * o.qty, 0), 0);

  const hourly = groupByHour(todayOrders);
  const hourlyData = hourly.filter(h => h.h >= 7 && h.h <= 23).map(h => ({
    label: String(h.h).padStart(2, '0'),
    value: h.revenue,
    tooltip: `${String(h.h).padStart(2, '0')}:00 – ${String((h.h + 1) % 24).padStart(2, '0')}:00`,
  }));

  const topItems = groupByItem(todayOrders, 5);
  const waiterPerf = groupByWaiter(todayOrders).slice(0, 5);

  const dateStr = new Date().toLocaleDateString('tr-TR', { weekday: 'long', day: 'numeric', month: 'long' });

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <div>
        <div style={{ fontSize: 22, fontWeight: 800, letterSpacing: '-0.02em' }}>Genel Bakış</div>
        <div style={{ fontSize: 13, color: 'var(--text-2)', marginTop: 2 }}>{dateStr}</div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(170px, 1fr))', gap: 12 }}>
        <StatCard icon="💰" label="Bugünkü Ciro" accent="var(--accent)" value={fmt(a.revenue)} trend={pctChange(a.revenue, yA.revenue)} sub="dünden" />
        <StatCard icon="🧾" label="Sipariş" accent="var(--green)" value={a.count} trend={pctChange(a.count, yA.count)} sub="dünden" />
        <StatCard icon="📊" label="Ort. Hesap" accent="#7C3AED" value={fmt(Math.round(a.avg))} trend={pctChange(a.avg, yA.avg)} sub="dünden" />
        <StatCard icon="🪑" label="Doluluk" accent="#0EA5E9" value={`${occupied}/${tables.length}`} sub={`${Math.round(occupied / Math.max(tables.length, 1) * 100)}% · ${fmt(occupiedRevenue)} açık`} />
      </div>

      <Section title="Bugün Saatlik Satış" subtitle={a.count > 0 ? `${a.count} sipariş, ${fmt(a.revenue)} toplam` : null}
        action={<button className="btn btn-ghost" style={{ fontSize: 12 }} onClick={onJumpToAnalytics}>Detay →</button>}>
        {a.count > 0
          ? <BarChart data={hourlyData} format={fmt} height={200} />
          : <EmptyState icon="☕" message="Bugün henüz satış yok" sub="İlk siparişten sonra burada grafiği göreceksin" />}
      </Section>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 14 }}>
        <Section title="En Çok Satanlar" subtitle="Bugün">
          <HBarList
            items={topItems.map((it, i) => ({ label: it.name, value: it.qty, color: PALETTE[i % PALETTE.length] }))}
            format={(v) => `${v} adet`}
            emptyMessage="Henüz satış yok"
          />
        </Section>
        <Section title="Garson Performansı" subtitle="Bugün">
          <HBarList
            items={waiterPerf.map((w, i) => ({ label: `${w.name} · ${w.count} sip.`, value: w.revenue, color: PALETTE[i % PALETTE.length] }))}
            format={fmt}
            emptyMessage="Henüz garson satışı yok"
          />
        </Section>
      </div>
    </div>
  );
}

// ----- Analytics -----
function AnalyticsTab() {
  const orders = Store.getOrders();
  const [preset, setPreset] = useState('7d');
  const [customFrom, setCustomFrom] = useState(ymd(addDays(new Date(), -7)));
  const [customTo, setCustomTo] = useState(ymd(new Date()));
  const [waiterFilter, setWaiterFilter] = useState('all');
  const [exporting, setExporting] = useState(false);
  const [exportError, setExportError] = useState(null);

  const range = useMemo(
    () => dateRangeFromPreset(preset, customFrom, customTo),
    [preset, customFrom, customTo]
  );
  const prev = useMemo(() => previousRange(range), [range]);

  const periodOrders = filterOrders(orders, range.from, range.to);
  const filteredOrders = waiterFilter === 'all' ? periodOrders : periodOrders.filter(o => o.waiter === waiterFilter);
  const prevOrders = filterOrders(orders, prev.from, prev.to);
  const prevFiltered = waiterFilter === 'all' ? prevOrders : prevOrders.filter(o => o.waiter === waiterFilter);

  const a = aggregate(filteredOrders);
  const pA = aggregate(prevFiltered);

  const allWaiters = useMemo(
    () => [...new Set(orders.map(o => o.waiter).filter(Boolean))].sort(),
    [orders]
  );
  const byWaiter = groupByWaiter(periodOrders);
  const byDay = groupByDay(filteredOrders, range.from, range.to);
  const hourly = groupByHour(filteredOrders);
  const items = groupByItem(filteredOrders, 10);
  const cats = groupByCategory(filteredOrders);

  const dayLabel = (d) => d.toLocaleDateString('tr-TR', { day: 'numeric', month: 'short' });
  const dayTooltip = (d) => d.toLocaleDateString('tr-TR', { weekday: 'long', day: 'numeric', month: 'long' });

  const handleExport = async () => {
    setExporting(true);
    setExportError(null);
    try {
      const fromStr = ymd(range.from);
      const toStr = ymd(addDays(range.to, -1));  // server treats `to` as inclusive day
      await Store.downloadXlsx({
        from: fromStr, to: toStr,
        waiter: waiterFilter !== 'all' ? waiterFilter : null,
      });
    } catch (e) {
      setExportError(e.message || 'İndirme başarısız');
      setTimeout(() => setExportError(null), 5000);
    } finally {
      setExporting(false);
    }
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap' }}>
        <div>
          <div style={{ fontSize: 22, fontWeight: 800, letterSpacing: '-0.02em' }}>Analitik</div>
          <div style={{ fontSize: 13, color: 'var(--text-2)', marginTop: 2 }}>
            {range.label} · {filteredOrders.length} sipariş
            {waiterFilter !== 'all' && <> · <strong>{waiterFilter}</strong></>}
          </div>
        </div>
        <button onClick={handleExport} disabled={exporting || filteredOrders.length === 0}
          title={filteredOrders.length === 0 ? 'İndirilebilecek sipariş yok' : 'Seçili dönem için Excel indir'}
          style={{
            display: 'inline-flex', alignItems: 'center', gap: 8,
            padding: '10px 16px', borderRadius: 10,
            border: '1.5px solid var(--green-border)',
            background: filteredOrders.length === 0 ? 'var(--bg)' : 'var(--green-bg)',
            color: filteredOrders.length === 0 ? 'var(--text-3)' : 'var(--green)',
            fontFamily: 'inherit', fontSize: 13, fontWeight: 700,
            cursor: filteredOrders.length === 0 || exporting ? 'not-allowed' : 'pointer',
            opacity: exporting ? 0.6 : 1, transition: 'all 0.12s',
          }}>
          <span style={{ fontSize: 16 }}>📥</span>
          {exporting ? 'Hazırlanıyor…' : 'Excel İndir'}
        </button>
      </div>
      {exportError && (
        <div style={{ padding: '10px 14px', background: '#FEF2F2', border: '1px solid #FECACA', borderRadius: 8, color: 'var(--red)', fontSize: 13, fontWeight: 600 }}>
          {exportError}
        </div>
      )}

      {/* Filters */}
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, alignItems: 'center' }}>
        {[
          { id: 'today', label: 'Bugün' },
          { id: 'yesterday', label: 'Dün' },
          { id: '7d', label: '7 Gün' },
          { id: '30d', label: '30 Gün' },
          { id: 'month', label: 'Bu Ay' },
          { id: 'custom', label: 'Özel' },
        ].map(p => (
          <FilterPill key={p.id} active={preset === p.id} onClick={() => setPreset(p.id)}>{p.label}</FilterPill>
        ))}
        {preset === 'custom' && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '4px 10px', border: '1.5px solid var(--accent)', borderRadius: 20, background: 'white' }}>
            <input type="date" value={customFrom} onChange={e => setCustomFrom(e.target.value)}
              style={{ border: 'none', background: 'transparent', fontFamily: 'inherit', fontSize: 13, fontWeight: 600, color: 'var(--text)', padding: '2px 0' }} />
            <span style={{ color: 'var(--text-3)' }}>→</span>
            <input type="date" value={customTo} onChange={e => setCustomTo(e.target.value)}
              style={{ border: 'none', background: 'transparent', fontFamily: 'inherit', fontSize: 13, fontWeight: 600, color: 'var(--text)', padding: '2px 0' }} />
          </div>
        )}
        <div style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{ fontSize: 12, color: 'var(--text-2)', fontWeight: 600 }}>Garson:</span>
          <select value={waiterFilter} onChange={e => setWaiterFilter(e.target.value)} className="input"
            style={{ width: 'auto', padding: '7px 28px 7px 12px', fontSize: 13, fontWeight: 600 }}>
            <option value="all">Tümü</option>
            {allWaiters.map(w => <option key={w} value={w}>{w}</option>)}
          </select>
        </div>
      </div>

      {/* KPIs */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(170px, 1fr))', gap: 12 }}>
        <StatCard icon="💰" label="Toplam Ciro" accent="var(--accent)" value={fmt(a.revenue)} trend={pctChange(a.revenue, pA.revenue)} sub="önceki dönemden" />
        <StatCard icon="🧾" label="Sipariş" accent="var(--green)" value={a.count} trend={pctChange(a.count, pA.count)} sub="önceki dönemden" />
        <StatCard icon="📊" label="Ort. Hesap" accent="#7C3AED" value={fmt(Math.round(a.avg))} trend={pctChange(a.avg, pA.avg)} sub="önceki dönemden" />
        <StatCard icon="🍽" label="Toplam Ürün" accent="#0EA5E9" value={a.items} trend={pctChange(a.items, pA.items)} sub="önceki dönemden" />
      </div>

      {/* Daily trend (only if range > 1 day) */}
      {range.days > 1 && (
        <Section title="Günlük Trend" subtitle={`${range.days} gün`}>
          {a.count > 0
            ? <BarChart
                data={byDay.map(d => ({
                  label: dayLabel(d.date),
                  value: d.revenue,
                  tooltip: `${dayTooltip(d.date)} · ${d.count} sipariş`,
                }))}
                format={fmt} height={220}
              />
            : <EmptyState message="Bu dönemde satış yok" />}
        </Section>
      )}

      {/* Hourly */}
      <Section
        title={range.days === 1 ? 'Saatlik Satış' : 'Ortalama Saatlik Dağılım'}
        subtitle={range.days > 1 ? `${range.days} günün ortalaması` : null}
      >
        {a.count > 0
          ? <BarChart
              color="#7C3AED"
              data={hourly.filter(h => h.h >= 7 && h.h <= 23).map(h => ({
                label: String(h.h).padStart(2, '0'),
                value: range.days > 1 ? h.revenue / range.days : h.revenue,
                tooltip: `${String(h.h).padStart(2, '0')}:00 – ${String((h.h + 1) % 24).padStart(2, '0')}:00`,
              }))}
              format={fmt} height={180}
            />
          : <EmptyState message="Saatlik veri yok" />}
      </Section>

      {/* Per-waiter table */}
      <Section
        title="Garson Performansı"
        subtitle={`${byWaiter.length} garson · seçmek için satıra tıkla`}
        action={waiterFilter !== 'all' && (
          <button className="btn btn-ghost" style={{ fontSize: 12 }} onClick={() => setWaiterFilter('all')}>
            ← Tüm garsonlar
          </button>
        )}
        padded={false}
      >
        {byWaiter.length === 0 ? (
          <div style={{ padding: 20 }}>
            <EmptyState icon="👥" message="Bu dönemde garson satışı yok" />
          </div>
        ) : (
          <div className="waiter-perf-table">
            <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr 1fr 2fr', gap: 12, padding: '10px 18px', fontSize: 10, color: 'var(--text-3)', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.05em', borderBottom: '1px solid var(--border)', background: 'var(--bg)' }}>
              <span>Garson</span>
              <span style={{ textAlign: 'right' }}>Ciro</span>
              <span style={{ textAlign: 'right' }}>Sipariş</span>
              <span style={{ textAlign: 'right' }}>Ort.</span>
              <span>En Çok Sattığı</span>
            </div>
            {byWaiter.map((w, i) => (
              <button key={w.name}
                onClick={() => setWaiterFilter(waiterFilter === w.name ? 'all' : w.name)}
                style={{
                  display: 'grid', gridTemplateColumns: '2fr 1fr 1fr 1fr 2fr', gap: 12,
                  padding: '14px 18px',
                  border: 'none', borderBottom: '1px solid var(--border)',
                  background: waiterFilter === w.name ? 'var(--accent-light)' : 'white',
                  cursor: 'pointer', width: '100%',
                  fontFamily: 'inherit', textAlign: 'left',
                  alignItems: 'center',
                  transition: 'background 0.12s',
                }}>
                <span style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 0 }}>
                  <span style={{
                    width: 30, height: 30, borderRadius: '50%',
                    background: PALETTE[i % PALETTE.length] + '22',
                    color: PALETTE[i % PALETTE.length],
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    fontWeight: 800, fontSize: 13, flexShrink: 0,
                  }}>{w.name[0]}</span>
                  <span style={{ fontWeight: 700, fontSize: 14, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{w.name}</span>
                </span>
                <span style={{ textAlign: 'right', fontWeight: 700, color: 'var(--accent)', fontSize: 14 }}>{fmt(w.revenue)}</span>
                <span style={{ textAlign: 'right', fontSize: 14, color: 'var(--text-2)', fontWeight: 600 }}>{w.count}</span>
                <span style={{ textAlign: 'right', fontSize: 14, color: 'var(--text-2)' }}>{fmt(Math.round(w.avg))}</span>
                <span style={{ fontSize: 12, color: 'var(--text-2)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                  {w.topItem ? <>{w.topItem.name} <span style={{ color: 'var(--text-3)' }}>×{w.topItem.qty}</span></> : '—'}
                </span>
              </button>
            ))}
          </div>
        )}
      </Section>

      {/* Two-col bottom */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 14 }}>
        <Section title="Ödeme Yöntemleri">
          {a.revenue > 0 ? (
            <div style={{ display: 'flex', alignItems: 'center', gap: 18, flexWrap: 'wrap' }}>
              <DonutChart
                data={[
                  { value: a.cash, color: 'var(--green)' },
                  { value: a.card, color: 'var(--accent)' },
                ]}
                size={130}
                centerLabel="Toplam"
                centerValue={fmt(a.revenue)}
              />
              <div style={{ flex: 1, minWidth: 140, display: 'flex', flexDirection: 'column', gap: 12 }}>
                {[
                  { label: 'Nakit', value: a.cash, color: 'var(--green)' },
                  { label: 'Kart', value: a.card, color: 'var(--accent)' },
                ].map(row => (
                  <div key={row.label}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 4 }}>
                      <span style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, fontWeight: 600 }}>
                        <span style={{ width: 10, height: 10, background: row.color, borderRadius: 2 }} />
                        {row.label}
                      </span>
                      <span style={{ fontSize: 13, fontWeight: 700 }}>{fmt(row.value)}</span>
                    </div>
                    <div style={{ fontSize: 11, color: 'var(--text-3)' }}>
                      %{Math.round((row.value / a.revenue) * 100)}
                    </div>
                  </div>
                ))}
              </div>
            </div>
          ) : <EmptyState message="Veri yok" />}
        </Section>

        <Section title="En Çok Satanlar" subtitle="Adet bazlı">
          <HBarList
            items={items.map((it, i) => ({ label: it.name, value: it.qty, color: PALETTE[i % PALETTE.length] }))}
            format={(v) => `${v} adet`}
            emptyMessage="Veri yok"
          />
        </Section>
      </div>

      <Section title="Kategori Dağılımı" subtitle="Ciro bazlı">
        <HBarList
          items={cats.map((c, i) => ({ label: `${c.name} · ${c.qty} adet`, value: c.revenue, color: PALETTE[i % PALETTE.length] }))}
          format={fmt}
          emptyMessage="Veri yok"
        />
      </Section>
    </div>
  );
}

// ----- Tables -----
function TablesTab() {
  const [tables, setTables] = useState(Store.getTables());
  const [confirmRemove, setConfirmRemove] = useState(null);
  const [_, setTick] = useState(0);

  useEffect(() => {
    const onUpdate = () => setTables(Store.getTables());
    window.addEventListener('store-updated', onUpdate);
    // tick once a minute so elapsed times refresh
    const id = setInterval(() => setTick(t => t + 1), 30000);
    return () => { window.removeEventListener('store-updated', onUpdate); clearInterval(id); };
  }, []);

  const handleAdd = async () => setTables(await Store.addTable());
  const handleRemove = async (id) => {
    setTables(await Store.removeTable(id));
    setConfirmRemove(null);
  };

  const occupied = tables.filter(t => t.occupied).length;
  const empty = tables.length - occupied;
  const totalOpen = tables.reduce(
    (s, t) => s + (t.orders || []).reduce((ss, o) => ss + o.price * o.qty, 0),
    0
  );

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap' }}>
        <div>
          <div style={{ fontSize: 22, fontWeight: 800, letterSpacing: '-0.02em' }}>Masalar</div>
          <div style={{ fontSize: 13, color: 'var(--text-2)', marginTop: 2 }}>
            {tables.length} masa · {occupied} dolu · {empty} boş
          </div>
        </div>
        <button className="btn btn-primary" onClick={handleAdd}>+ Masa Ekle</button>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(150px, 1fr))', gap: 12 }}>
        <StatCard icon="🪑" label="Toplam" accent="var(--text)" value={tables.length} />
        <StatCard icon="🟠" label="Dolu" accent="var(--accent)" value={occupied} sub={`%${Math.round(occupied / Math.max(tables.length, 1) * 100)}`} />
        <StatCard icon="🟢" label="Boş" accent="var(--green)" value={empty} sub={`%${Math.round(empty / Math.max(tables.length, 1) * 100)}`} />
        <StatCard icon="💰" label="Açık Hesap" accent="#7C3AED" value={fmt(totalOpen)} sub="şu anda" />
      </div>

      <Section title="Tüm Masalar" subtitle="Boş masaları silebilirsin · dolu masalar korumalı" padded={false}>
        <div style={{ padding: 16, display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(180px, 1fr))', gap: 12 }}>
          {tables.map(t => {
            const total = (t.orders || []).reduce((s, o) => s + o.price * o.qty, 0);
            const itemCount = (t.orders || []).reduce((s, o) => s + o.qty, 0);
            return (
              <div key={t.id} style={{
                background: t.occupied ? 'white' : 'var(--green-bg)',
                border: '2px solid', borderColor: t.occupied ? 'var(--accent)' : 'var(--green-border)',
                borderRadius: 14, padding: 14,
                display: 'flex', flexDirection: 'column',
                minHeight: 130,
                boxShadow: t.occupied ? '0 2px 8px rgba(232,89,12,0.08)' : 'var(--shadow)',
                position: 'relative',
              }}>
                <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 4 }}>
                  <div>
                    <div style={{ fontWeight: 800, fontSize: 17 }}>{t.name}</div>
                    <div style={{ fontSize: 10, fontWeight: 800, color: t.occupied ? 'var(--accent)' : 'var(--green)', marginTop: 2, letterSpacing: '0.05em' }}>
                      {t.occupied ? 'DOLU' : 'BOŞ'}
                    </div>
                  </div>
                  {!t.occupied && (
                    <button onClick={() => setConfirmRemove(t)}
                      title="Sil"
                      style={{
                        width: 26, height: 26, borderRadius: 6,
                        border: '1px solid var(--border)', background: 'white', color: 'var(--text-3)',
                        cursor: 'pointer', fontSize: 13, display: 'flex',
                        alignItems: 'center', justifyContent: 'center',
                      }}>✕</button>
                  )}
                </div>
                {t.occupied && (
                  <div style={{ marginTop: 'auto', paddingTop: 8, borderTop: '1px solid var(--border)' }}>
                    <div style={{ fontSize: 12, color: 'var(--text-2)', fontWeight: 600, display: 'flex', alignItems: 'center', gap: 4 }}>
                      <span>👤</span> {t.waiter}
                    </div>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginTop: 6 }}>
                      <div style={{ fontSize: 11, color: 'var(--text-3)' }}>
                        ⏱ {t.openedAt ? elapsed(t.openedAt) : '—'} · {itemCount} ürün
                      </div>
                    </div>
                    {total > 0 && (
                      <div style={{ fontSize: 16, fontWeight: 800, color: 'var(--accent)', marginTop: 4, textAlign: 'right' }}>
                        {fmt(total)}
                      </div>
                    )}
                  </div>
                )}
              </div>
            );
          })}
        </div>
      </Section>

      {confirmRemove && (
        <ConfirmDialog
          title={`${confirmRemove.name} silinsin mi?`}
          message="Bu masa kalıcı olarak silinecek. İstersen daha sonra yenisini ekleyebilirsin."
          confirmLabel="Sil" danger
          onConfirm={() => handleRemove(confirmRemove.id)}
          onCancel={() => setConfirmRemove(null)}
        />
      )}
    </div>
  );
}

// ----- Menu -----
function MenuTab() {
  const [menu, setMenu] = useState(Store.getMenu());
  const [cats, setCats] = useState(Store.getCategories());
  const [activeCat, setActiveCat] = useState(null);
  const [editId, setEditId] = useState(null);
  const [editName, setEditName] = useState('');
  const [editPrice, setEditPrice] = useState('');
  const [newName, setNewName] = useState('');
  const [newPrice, setNewPrice] = useState('');
  const [addingCat, setAddingCat] = useState(false);
  const [catInput, setCatInput] = useState('');

  useEffect(() => {
    const onUpdate = () => { setMenu(Store.getMenu()); setCats(Store.getCategories()); };
    window.addEventListener('store-updated', onUpdate);
    return () => window.removeEventListener('store-updated', onUpdate);
  }, []);

  useEffect(() => { if (!activeCat && cats.length) setActiveCat(cats[0]); }, [cats]);

  const catItems = menu.filter(m => m.cat === activeCat);

  const startEdit = (item) => { setEditId(item.id); setEditName(item.name); setEditPrice(String(item.price)); };
  const saveEdit = async () => {
    setMenu(await Store.updateMenuItem(editId, { name: editName, price: parseFloat(editPrice) || 0 }));
    setEditId(null);
  };
  const handleDelete = async (id) => { setMenu(await Store.deleteMenuItem(id)); };
  const handleAdd = async () => {
    if (!newName.trim() || !newPrice || !activeCat) return;
    setMenu(await Store.addMenuItem(activeCat, newName.trim(), newPrice));
    setNewName(''); setNewPrice('');
  };
  const handleAddCat = async () => {
    if (!catInput.trim()) return;
    await Store.addCategory(catInput.trim());
    setCats(Store.getCategories());
    setActiveCat(catInput.trim());
    setCatInput(''); setAddingCat(false);
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16, height: '100%' }}>
      <div>
        <div style={{ fontSize: 22, fontWeight: 800, letterSpacing: '-0.02em' }}>Menü</div>
        <div style={{ fontSize: 13, color: 'var(--text-2)', marginTop: 2 }}>
          {menu.length} ürün · {cats.length} kategori
        </div>
      </div>

      <div style={{
        background: 'white', borderRadius: 14, border: '1px solid var(--border)',
        boxShadow: 'var(--shadow)', display: 'flex', flexDirection: 'column',
        overflow: 'hidden', flex: 1, minHeight: 420,
      }}>
        <div className="menu-tab-inner" style={{ display: 'flex', flex: 1, overflow: 'hidden' }}>
          <div className="menu-cats-side" style={{
            width: 220, borderRight: '1px solid var(--border)',
            padding: 14, overflowY: 'auto', flexShrink: 0, background: 'var(--bg)',
          }}>
            <div className="menu-cats-label" style={{ fontSize: 11, fontWeight: 700, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 10 }}>Kategoriler</div>
            {cats.map(c => {
              const count = menu.filter(m => m.cat === c).length;
              return (
                <button key={c} onClick={() => setActiveCat(c)}
                  className="menu-cat-btn"
                  style={{
                    display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                    width: '100%', padding: '10px 12px', borderRadius: 8, border: 'none', cursor: 'pointer',
                    fontFamily: 'inherit', fontSize: 13, fontWeight: 600, marginBottom: 3,
                    background: activeCat === c ? 'white' : 'transparent',
                    color: activeCat === c ? 'var(--accent)' : 'var(--text)',
                    boxShadow: activeCat === c ? '0 1px 3px rgba(0,0,0,0.06)' : 'none',
                  }}>
                  <span>{c}</span>
                  <span style={{ fontSize: 11, color: 'var(--text-3)', fontWeight: 600 }}>{count}</span>
                </button>
              );
            })}
            <div className="menu-add-cat" style={{ marginTop: 10 }}>
              {addingCat ? (
                <div>
                  <input className="input" value={catInput} onChange={e => setCatInput(e.target.value)}
                    placeholder="Kategori adı" style={{ marginBottom: 6, fontSize: 13 }} autoFocus
                    onKeyDown={e => e.key === 'Enter' && handleAddCat()} />
                  <div style={{ display: 'flex', gap: 6 }}>
                    <button className="btn btn-primary" style={{ flex: 1, fontSize: 12, padding: '6px 0' }} onClick={handleAddCat}>Ekle</button>
                    <button className="btn btn-ghost" style={{ fontSize: 12, padding: '6px 8px' }} onClick={() => setAddingCat(false)}>✕</button>
                  </div>
                </div>
              ) : (
                <button className="btn btn-ghost" style={{ width: '100%', fontSize: 12, padding: '8px 0' }} onClick={() => setAddingCat(true)}>+ Kategori</button>
              )}
            </div>
          </div>

          <div className="menu-items-side" style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
            <div style={{ padding: '14px 18px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <div style={{ fontWeight: 700, fontSize: 15 }}>{activeCat || 'Kategori seçin'}</div>
              <div style={{ fontSize: 12, color: 'var(--text-3)' }}>{catItems.length} ürün</div>
            </div>
            <div style={{ flex: 1, overflowY: 'auto', padding: 14 }}>
              {catItems.length === 0 ? (
                <EmptyState icon="🍽" message="Bu kategoride ürün yok" sub="Aşağıdan yeni ekleyebilirsin" />
              ) : catItems.map(item => (
                <div key={item.id} className="menu-item-row" style={{
                  display: 'flex', alignItems: 'center', gap: 10, padding: '10px 14px',
                  background: 'white', borderRadius: 10, marginBottom: 6,
                  border: '1px solid var(--border)',
                }}>
                  {editId === item.id ? (
                    <>
                      <input className="input" value={editName} onChange={e => setEditName(e.target.value)} style={{ flex: 2 }} />
                      <input className="input" value={editPrice} onChange={e => setEditPrice(e.target.value)} type="number" style={{ width: 90 }} />
                      <button className="btn btn-primary" style={{ fontSize: 13, padding: '8px 14px' }} onClick={saveEdit}>Kaydet</button>
                      <button className="btn btn-ghost" style={{ fontSize: 13, padding: '8px 10px' }} onClick={() => setEditId(null)}>İptal</button>
                    </>
                  ) : (
                    <>
                      <div className="menu-item-name" style={{ flex: 1, fontWeight: 600, fontSize: 14 }}>{item.name}</div>
                      <div style={{ fontWeight: 700, color: 'var(--accent)', fontSize: 14, minWidth: 70, textAlign: 'right' }}>{fmt(item.price)}</div>
                      <button className="btn btn-ghost" style={{ fontSize: 13, padding: '6px 12px' }} onClick={() => startEdit(item)}>Düzenle</button>
                      <button className="btn btn-danger" style={{ fontSize: 13, padding: '6px 12px' }} onClick={() => handleDelete(item.id)}>Sil</button>
                    </>
                  )}
                </div>
              ))}
            </div>
            {activeCat && (
              <div className="menu-add-row" style={{ padding: '12px 18px', borderTop: '1px solid var(--border)', background: 'var(--bg)', display: 'flex', gap: 8, alignItems: 'center' }}>
                <input className="input" value={newName} onChange={e => setNewName(e.target.value)} placeholder="Yeni ürün adı" style={{ flex: 2 }} onKeyDown={e => e.key === 'Enter' && handleAdd()} />
                <input className="input" value={newPrice} onChange={e => setNewPrice(e.target.value)} placeholder="₺" type="number" style={{ width: 100 }} onKeyDown={e => e.key === 'Enter' && handleAdd()} />
                <button className="btn btn-primary" style={{ whiteSpace: 'nowrap' }} onClick={handleAdd}>+ Ekle</button>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

// ----- Users -----
function maskPhone(phone) {
  if (!phone) return '';
  const m = phone.match(/^\+90(\d{3})(\d{3})(\d{2})(\d{2})$/);
  if (!m) return phone;
  return `+90 ${m[1][0]}•• ••• ${m[3]} ${m[4]}`;
}

function UsersTab({ currentUser }) {
  const [users, setUsers] = useState(Store.getUsers());
  const [showAdd, setShowAdd] = useState(false);
  const [editingPinId, setEditingPinId] = useState(null);
  const [editPin, setEditPin] = useState('');
  const [confirmDelete, setConfirmDelete] = useState(null);
  const [filter, setFilter] = useState('all');

  useEffect(() => {
    const onUpdate = () => setUsers(Store.getUsers());
    window.addEventListener('store-updated', onUpdate);
    return () => window.removeEventListener('store-updated', onUpdate);
  }, []);

  const counts = {
    all: users.length,
    admin: users.filter(u => u.role === 'admin').length,
    waiter: users.filter(u => u.role === 'waiter').length,
    inactive: users.filter(u => !u.active).length,
  };

  const filtered = users.filter(u => {
    if (filter === 'admin') return u.role === 'admin';
    if (filter === 'waiter') return u.role === 'waiter';
    if (filter === 'inactive') return !u.active;
    return true;
  });

  const handleToggle = async (id) => { await Store.toggleUser(id); setUsers(Store.getUsers()); };
  const handleDelete = async (id) => {
    try {
      await Store.deleteUser(id);
      setUsers(Store.getUsers());
      setConfirmDelete(null);
    } catch (e) { alert(e.message || 'Silinemedi'); }
  };
  const handleSavePin = async (id) => {
    if (!/^\d{6}$/.test(editPin)) return;
    await Store.setUserPin(id, editPin);
    setEditingPinId(null); setEditPin('');
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap' }}>
        <div>
          <div style={{ fontSize: 22, fontWeight: 800, letterSpacing: '-0.02em' }}>Kullanıcılar</div>
          <div style={{ fontSize: 13, color: 'var(--text-2)', marginTop: 2 }}>
            {counts.all} toplam · {counts.admin} yönetici · {counts.waiter} garson
          </div>
        </div>
        <button className="btn btn-primary" onClick={() => setShowAdd(true)}>+ Kullanıcı Ekle</button>
      </div>

      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
        <FilterPill active={filter === 'all'} onClick={() => setFilter('all')}>Tümü ({counts.all})</FilterPill>
        <FilterPill active={filter === 'admin'} onClick={() => setFilter('admin')}>Yönetici ({counts.admin})</FilterPill>
        <FilterPill active={filter === 'waiter'} onClick={() => setFilter('waiter')}>Garson ({counts.waiter})</FilterPill>
        {counts.inactive > 0 && <FilterPill active={filter === 'inactive'} onClick={() => setFilter('inactive')}>Pasif ({counts.inactive})</FilterPill>}
      </div>

      {filtered.length === 0 ? (
        <Section title="Hiç kullanıcı yok"><EmptyState icon="👥" message="Bu filtrede kullanıcı yok" /></Section>
      ) : (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 12 }}>
          {filtered.map(u => {
            const isSelf = currentUser && currentUser.id === u.id;
            const isAdminUser = u.role === 'admin';
            return (
              <div key={u.id} style={{
                background: 'white', borderRadius: 12, padding: 16,
                border: '1px solid var(--border)', boxShadow: 'var(--shadow)',
                opacity: u.active ? 1 : 0.65,
                display: 'flex', flexDirection: 'column', gap: 12,
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                  <div style={{
                    width: 44, height: 44, borderRadius: '50%',
                    background: u.active ? (isAdminUser ? 'var(--accent-light)' : 'var(--green-bg)') : 'var(--border)',
                    color: u.active ? (isAdminUser ? 'var(--accent)' : 'var(--green)') : 'var(--text-2)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    fontWeight: 800, fontSize: 17, flexShrink: 0,
                  }}>{u.name[0]}</div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontWeight: 700, fontSize: 15, display: 'flex', alignItems: 'center', gap: 6 }}>
                      <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{u.name}</span>
                      {isSelf && <span style={{ fontSize: 9, fontWeight: 700, padding: '2px 5px', borderRadius: 3, background: 'var(--bg)', color: 'var(--text-3)', flexShrink: 0 }}>SEN</span>}
                    </div>
                    <div style={{ fontSize: 12, color: 'var(--text-2)', fontFamily: 'monospace', marginTop: 2 }}>{maskPhone(u.phone)}</div>
                  </div>
                </div>
                <div style={{ display: 'flex', gap: 6 }}>
                  <span style={{
                    fontSize: 10, fontWeight: 700, padding: '3px 8px', borderRadius: 4,
                    background: isAdminUser ? 'var(--accent-light)' : 'var(--green-bg)',
                    color: isAdminUser ? 'var(--accent)' : 'var(--green)',
                  }}>{isAdminUser ? 'YÖNETİCİ' : 'GARSON'}</span>
                  <span style={{
                    fontSize: 10, fontWeight: 700, padding: '3px 8px', borderRadius: 4,
                    background: u.active ? '#F0FDF4' : '#F5F5F4',
                    color: u.active ? 'var(--green)' : 'var(--text-3)',
                  }}>{u.active ? 'AKTİF' : 'PASİF'}</span>
                </div>
                {editingPinId === u.id ? (
                  <div style={{ display: 'flex', gap: 6 }}>
                    <input className="input" value={editPin} placeholder="Yeni 6 haneli PIN" inputMode="numeric"
                      onChange={e => setEditPin(e.target.value.replace(/\D/g, '').slice(0, 6))}
                      style={{ letterSpacing: '0.2em', textAlign: 'center', fontSize: 14 }} autoFocus
                      onKeyDown={e => e.key === 'Enter' && handleSavePin(u.id)} />
                    <button className="btn btn-primary" style={{ fontSize: 12, padding: '8px 12px' }} onClick={() => handleSavePin(u.id)}>Kaydet</button>
                    <button className="btn btn-ghost" style={{ fontSize: 12, padding: '8px 8px' }} onClick={() => { setEditingPinId(null); setEditPin(''); }}>✕</button>
                  </div>
                ) : (
                  <div style={{ display: 'flex', gap: 6 }}>
                    <button className="btn btn-ghost" style={{ flex: 1, fontSize: 12, padding: '7px 0', justifyContent: 'center' }}
                      onClick={() => { setEditingPinId(u.id); setEditPin(''); }}>🔑 PIN Sıfırla</button>
                    <button className="btn btn-ghost" style={{ fontSize: 12, padding: '7px 10px' }} disabled={isSelf}
                      title={isSelf ? 'Kendinizi pasifleştiremezsiniz' : (u.active ? 'Pasifleştir' : 'Aktifleştir')}
                      onClick={() => handleToggle(u.id)}>{u.active ? '⏸' : '▶'}</button>
                    <button className="btn btn-danger" style={{ fontSize: 12, padding: '7px 10px' }} disabled={isSelf}
                      title={isSelf ? 'Kendinizi silemezsiniz' : 'Sil'}
                      onClick={() => setConfirmDelete(u)}>✕</button>
                  </div>
                )}
              </div>
            );
          })}
        </div>
      )}

      {showAdd && <AddUserModal onClose={() => setShowAdd(false)} onAdded={() => { setUsers(Store.getUsers()); setShowAdd(false); }} />}
      {confirmDelete && (
        <ConfirmDialog
          title="Kullanıcıyı sil?"
          message={<><strong>{confirmDelete.name}</strong> kalıcı olarak silinecek. Geçmiş satışlar etkilenmez.</>}
          confirmLabel="Sil" danger
          onConfirm={() => handleDelete(confirmDelete.id)}
          onCancel={() => setConfirmDelete(null)}
        />
      )}
    </div>
  );
}

function AddUserModal({ onClose, onAdded }) {
  const [name, setName] = useState('');
  const [phoneDigits, setPhoneDigits] = useState('');
  const [pin, setPin] = useState('');
  const [role, setRole] = useState('waiter');
  const [error, setError] = useState(null);
  const [submitting, setSubmitting] = useState(false);

  const phoneOk = phoneDigits.length === 10;
  const pinOk = /^\d{6}$/.test(pin);
  const canSubmit = name.trim() && phoneOk && pinOk && !submitting;

  const submit = async () => {
    if (!canSubmit) return;
    setSubmitting(true);
    try {
      await Store.addUser(name.trim(), '+90' + phoneDigits, pin, role);
      onAdded();
    } catch (e) {
      setError(e.message || 'Eklenemedi');
      setSubmitting(false);
    }
  };

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal-box" style={{ width: 380, padding: 24 }} onClick={e => e.stopPropagation()}>
        <div style={{ fontWeight: 700, fontSize: 18, marginBottom: 14 }}>Yeni Kullanıcı</div>

        <label style={{ display: 'block', fontSize: 12, fontWeight: 600, color: 'var(--text-2)', marginBottom: 6 }}>Ad Soyad</label>
        <input className="input" value={name} onChange={(e) => { setName(e.target.value); setError(null); }} autoFocus style={{ marginBottom: 12 }} />

        <label style={{ display: 'block', fontSize: 12, fontWeight: 600, color: 'var(--text-2)', marginBottom: 6 }}>Telefon</label>
        <div style={{ display: 'flex', alignItems: 'stretch', border: '1.5px solid var(--border)', borderRadius: 10, overflow: 'hidden', marginBottom: 12 }}>
          <div style={{ display: 'flex', alignItems: 'center', padding: '0 12px', background: 'var(--bg)', fontSize: 16, fontWeight: 600, color: 'var(--text-2)' }}>+90</div>
          <input type="tel" inputMode="numeric" placeholder="5XX XXX XX XX"
            value={window.formatPhoneInput ? window.formatPhoneInput(phoneDigits) : phoneDigits}
            onChange={(e) => { const d = e.target.value.replace(/\D/g, '').slice(0, 10); setPhoneDigits(d); setError(null); }}
            style={{ flex: 1, padding: '12px 14px', border: 'none', outline: 'none', fontFamily: 'inherit', fontSize: 16, letterSpacing: '0.04em' }} />
        </div>

        <label style={{ display: 'block', fontSize: 12, fontWeight: 600, color: 'var(--text-2)', marginBottom: 6 }}>İlk PIN (6 haneli)</label>
        <input className="input" value={pin} inputMode="numeric" maxLength={6}
          onChange={(e) => { setPin(e.target.value.replace(/\D/g, '').slice(0, 6)); setError(null); }}
          style={{ letterSpacing: '0.2em', textAlign: 'center', marginBottom: 12 }} />

        <label style={{ display: 'block', fontSize: 12, fontWeight: 600, color: 'var(--text-2)', marginBottom: 6 }}>Rol</label>
        <div style={{ display: 'flex', gap: 8, marginBottom: 16 }}>
          {[
            { id: 'waiter', label: '👤 Garson' },
            { id: 'admin', label: '🔒 Yönetici' },
          ].map(r => (
            <button key={r.id} type="button" onClick={() => setRole(r.id)}
              style={{
                flex: 1, padding: '12px 0', borderRadius: 8, border: '1.5px solid',
                borderColor: role === r.id ? 'var(--accent)' : 'var(--border)',
                background: role === r.id ? 'var(--accent-light)' : 'white',
                color: role === r.id ? 'var(--accent)' : 'var(--text-2)',
                fontFamily: 'inherit', fontSize: 14, fontWeight: 700, cursor: 'pointer',
              }}>{r.label}</button>
          ))}
        </div>

        {error && <div style={{ color: 'var(--red)', fontSize: 13, fontWeight: 600, marginBottom: 12 }}>{error}</div>}

        <div style={{ display: 'flex', gap: 10 }}>
          <button className="btn btn-ghost" style={{ flex: 1 }} onClick={onClose}>İptal</button>
          <button className="btn btn-primary" style={{ flex: 1 }} disabled={!canSubmit} onClick={submit}>Ekle</button>
        </div>
      </div>
    </div>
  );
}

// ----- System -----
function SystemTab({ lang, onLangChange }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <div>
        <div style={{ fontSize: 22, fontWeight: 800, letterSpacing: '-0.02em' }}>Sistem</div>
        <div style={{ fontSize: 13, color: 'var(--text-2)', marginTop: 2 }}>Cihaz oturumları ve uygulama ayarları</div>
      </div>

      <Section title="Aktif Oturumlar" subtitle="Şu anda giriş yapmış cihazlar"><SessionsList /></Section>

      <Section title="Dil / Language">
        <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
          {[{ id: 'tr', label: '🇹🇷 Türkçe' }, { id: 'en', label: '🇬🇧 English' }].map(l => (
            <button key={l.id} onClick={() => onLangChange(l.id)}
              style={{
                padding: '12px 24px', borderRadius: 8, border: '1.5px solid',
                borderColor: lang === l.id ? 'var(--accent)' : 'var(--border)',
                background: lang === l.id ? 'var(--accent-light)' : 'white',
                color: lang === l.id ? 'var(--accent)' : 'var(--text)',
                fontFamily: 'inherit', fontSize: 14, fontWeight: 700, cursor: 'pointer',
              }}>{l.label}</button>
          ))}
        </div>
      </Section>
    </div>
  );
}

function SessionsList() {
  const [sessions, setSessions] = useState([]);
  const [loading, setLoading] = useState(true);

  const refresh = async () => {
    setLoading(true);
    try { setSessions(await Store.listSessions()); }
    catch { setSessions([]); }
    finally { setLoading(false); }
  };
  useEffect(() => { refresh(); }, []);

  const handleRevoke = async (token, isCurrent) => {
    if (isCurrent && !confirm('Bu mevcut oturumu kapatırsan çıkış yapacaksın. Devam?')) return;
    try { await Store.revokeSession(token); await refresh(); }
    catch (e) { alert(e.message || 'Hata'); }
  };

  const fmtAgo = (iso) => {
    const m = Math.floor((Date.now() - new Date(iso).getTime()) / 60000);
    if (m < 1) return 'şimdi';
    if (m < 60) return `${m} dk önce`;
    const h = Math.floor(m / 60);
    if (h < 24) return `${h} saat önce`;
    return `${Math.floor(h / 24)} gün önce`;
  };

  if (loading) return <div style={{ color: 'var(--text-3)', fontSize: 13 }}>Yükleniyor…</div>;
  if (sessions.length === 0) return <EmptyState icon="🔌" message="Aktif oturum yok" />;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
      {sessions.map(s => (
        <div key={s.token} style={{
          display: 'flex', alignItems: 'center', gap: 10, padding: 12,
          background: 'var(--bg)', borderRadius: 10,
          border: s.isCurrent ? '1.5px solid var(--accent)' : '1px solid var(--border)',
        }}>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontWeight: 700, fontSize: 14, display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
              <span>{s.userName}</span>
              <span style={{ fontSize: 10, fontWeight: 700, padding: '2px 6px', borderRadius: 3, background: s.role === 'admin' ? 'var(--accent-light)' : 'var(--green-bg)', color: s.role === 'admin' ? 'var(--accent)' : 'var(--green)' }}>{s.role === 'admin' ? 'ADMİN' : 'GARSON'}</span>
              {s.isCurrent && <span style={{ fontSize: 10, fontWeight: 700, padding: '2px 6px', borderRadius: 3, background: 'var(--accent)', color: 'white' }}>BU CİHAZ</span>}
            </div>
            <div style={{ fontSize: 11, color: 'var(--text-2)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', marginTop: 2 }}>
              {fmtAgo(s.lastSeen)} · {(s.userAgent || 'bilinmiyor').slice(0, 60)}
            </div>
          </div>
          <button className="btn btn-danger" style={{ fontSize: 12, padding: '6px 10px' }} onClick={() => handleRevoke(s.token, s.isCurrent)}>✕</button>
        </div>
      ))}
    </div>
  );
}

// ============================================================================
// AdminPanel shell
// ============================================================================

function AdminPanel({ lang, onClose, onLangChange, currentUser }) {
  const [tab, setTab] = useState('dashboard');
  const tabs = [
    { id: 'dashboard', label: 'Genel', icon: '📊' },
    { id: 'analytics', label: 'Analitik', icon: '📈' },
    { id: 'tables', label: 'Masalar', icon: '🪑' },
    { id: 'menu', label: 'Menü', icon: '🍽' },
    { id: 'users', label: 'Kullanıcılar', icon: '👥' },
    { id: 'system', label: 'Sistem', icon: '⚙️' },
  ];

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal-box admin-fullscreen admin-shell"
        style={{ width: '95vw', maxWidth: 1200, height: '92vh', display: 'flex', flexDirection: 'column' }}
        onClick={e => e.stopPropagation()}>

        {/* Top bar */}
        <div className="admin-topbar" style={{
          display: 'flex', alignItems: 'center',
          borderBottom: '1px solid var(--border)',
          padding: '0 18px', flexShrink: 0, height: 56,
        }}>
          <div style={{ fontWeight: 800, fontSize: 16, letterSpacing: '-0.01em', display: 'flex', alignItems: 'center', gap: 10 }}>
            <span style={{
              width: 28, height: 28, background: 'var(--accent)', borderRadius: 7,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 14, color: 'white',
            }}>⚙</span>
            Yönetim
          </div>
          <button className="btn btn-ghost" style={{ marginLeft: 'auto', fontSize: 18, padding: '8px 12px' }} onClick={onClose}>✕</button>
        </div>

        {/* Mobile-only horizontal tab bar */}
        <div className="admin-tabs-mobile" style={{
          display: 'none', borderBottom: '1px solid var(--border)',
          overflowX: 'auto', flexShrink: 0, background: 'white',
        }}>
          {tabs.map(t => (
            <button key={t.id} onClick={() => setTab(t.id)} title={t.label}
              style={{
                padding: '14px 16px', border: 'none', background: 'transparent', cursor: 'pointer',
                fontFamily: 'inherit', fontSize: 13, fontWeight: 700, flexShrink: 0,
                borderBottom: '2px solid', borderBottomColor: tab === t.id ? 'var(--accent)' : 'transparent',
                color: tab === t.id ? 'var(--accent)' : 'var(--text-2)',
                display: 'flex', alignItems: 'center', gap: 6,
              }}>
              <span style={{ fontSize: 16 }}>{t.icon}</span>
              <span className="admin-tab-label-mobile">{t.label}</span>
            </button>
          ))}
        </div>

        {/* Body */}
        <div className="admin-body" style={{ display: 'flex', flex: 1, overflow: 'hidden' }}>
          <div className="admin-sidebar" style={{
            width: 200, flexShrink: 0,
            borderRight: '1px solid var(--border)',
            background: 'var(--bg)',
            padding: '14px 10px',
            overflowY: 'auto',
            display: 'flex', flexDirection: 'column', gap: 2,
          }}>
            {tabs.map(t => (
              <button key={t.id} onClick={() => setTab(t.id)}
                style={{
                  display: 'flex', alignItems: 'center', gap: 12,
                  padding: '11px 14px', borderRadius: 8, border: 'none', cursor: 'pointer',
                  fontFamily: 'inherit', fontSize: 14, fontWeight: 700,
                  background: tab === t.id ? 'white' : 'transparent',
                  color: tab === t.id ? 'var(--accent)' : 'var(--text-2)',
                  boxShadow: tab === t.id ? '0 1px 3px rgba(0,0,0,0.06)' : 'none',
                  transition: 'all 0.12s',
                  textAlign: 'left',
                }}>
                <span style={{ fontSize: 17 }}>{t.icon}</span>
                <span>{t.label}</span>
              </button>
            ))}
            <div style={{ marginTop: 'auto', paddingTop: 14, fontSize: 11, color: 'var(--text-3)', textAlign: 'center', fontWeight: 500 }}>
              {currentUser ? `👤 ${currentUser.name}` : ''}
            </div>
          </div>

          <div className="admin-main" style={{
            flex: 1, overflowY: 'auto',
            padding: '24px 28px', background: 'var(--bg)',
          }}>
            {tab === 'dashboard' && <DashboardTab onJumpToAnalytics={() => setTab('analytics')} />}
            {tab === 'analytics' && <AnalyticsTab />}
            {tab === 'tables' && <TablesTab />}
            {tab === 'menu' && <MenuTab />}
            {tab === 'users' && <UsersTab currentUser={currentUser} />}
            {tab === 'system' && <SystemTab lang={lang} onLangChange={onLangChange} />}
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { AdminPanel });
