// -- تحويل للنشر بدون أدوات بناء (Vite/Webpack): بنستخدم المتغيرات العامة يلي محمّلة من CDN بملف index.html --
const { useState, useMemo, useEffect, useRef } = React;

const TABLES = Array.from({ length: 10 }, (_, i) => i + 1);
const LOW_STOCK_THRESHOLD = 5;

const PERM_LIST = [
  { id: "editMenu", label: "تعديل القائمة (إضافة/تعديل/حذف صنف)" },
  { id: "deleteOrder", label: "حذف أو إلغاء طلب" },
  { id: "applyDiscount", label: "تطبيق خصم على الفاتورة" },
  { id: "viewReports", label: "عرض التقارير" },
  { id: "manageInventory", label: "إدارة المخزون" },
  { id: "addToOpenOrder", label: "إضافة أصناف لطلب طاولة مفتوح" },
  { id: "removeFromOpenOrder", label: "حذف/إنقاص أصناف من طلب طاولة مفتوح" },
];

const DEFAULT_STAFF = [
  { id: "s1", name: "أحمد", type: "نادل", assignedZone: "ground", username: "ahmad", password: "1111", permissions: { editMenu: false, deleteOrder: false, applyDiscount: false, viewReports: false, manageInventory: false, addToOpenOrder: true, removeFromOpenOrder: true } },
  { id: "s2", name: "ليلى", type: "نادل", assignedZone: "roof", username: "laila", password: "1111", permissions: { editMenu: false, deleteOrder: false, applyDiscount: true, viewReports: false, manageInventory: false, addToOpenOrder: false, removeFromOpenOrder: false } },
  { id: "s3", name: "سارة", type: "كاشير", assignedZone: "roof", username: "sara", password: "2222", permissions: { editMenu: true, deleteOrder: true, applyDiscount: true, viewReports: false, manageInventory: true, addToOpenOrder: true, removeFromOpenOrder: true } },
  { id: "s4", name: "خالد", type: "كاشير", assignedZone: "ground", username: "khaled", password: "2222", permissions: { editMenu: false, deleteOrder: true, applyDiscount: false, viewReports: false, manageInventory: false, addToOpenOrder: false, removeFromOpenOrder: false } },
];

const DEFAULT_ZONES = [
  { id: "ground", name: "الطابق الأرضي", tables: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"] },
  { id: "roof", name: "الروف", tables: ["1", "2", "3", "4", "5", "6"] },
];

const CATEGORY_STYLE = {
  hot: { icon: "☕", grad: "linear-gradient(135deg,#fff4e8,#ffe7cc)" },
  cold: { icon: "🧊", grad: "linear-gradient(135deg,#e8f7fb,#d4eef6)" },
  hot_drinks: { icon: "🍵", grad: "linear-gradient(135deg,#eef8ea,#dcf0d1)" },
  cold_drinks: { icon: "🥤", grad: "linear-gradient(135deg,#e6f2ff,#d2e6ff)" },
  juices: { icon: "🧃", grad: "linear-gradient(135deg,#fff8e0,#ffedb0)" },
  mojito: { icon: "🍹", grad: "linear-gradient(135deg,#f6edff,#ecdcff)" },
  hookah: { icon: "💨", grad: "linear-gradient(135deg,#eef1f6,#dde2ec)" },
  snacks: { icon: "🍿", grad: "linear-gradient(135deg,#fff1e0,#ffe1bd)" },
  addons: { icon: "➕", grad: "linear-gradient(135deg,#fdeaf1,#fbd7e5)" },
};

const CATEGORY_STATION = {
  hot: "bar", cold: "bar", hot_drinks: "bar", cold_drinks: "bar",
  juices: "bar", mojito: "bar", addons: "bar",
  hookah: "hookah",
  snacks: "kitchen",
};
const STATION_LABEL = { bar: "☕ الباريستا", kitchen: "🍽️ المطبخ", cashier: "💰 الكاشير", hookah: "💨 الأراجيل" };

const DEFAULT_PRINTERS = [
  { id: "p1", name: "طابعة الكاشير - الأرضي", role: "cashier", zoneId: "ground", ip: "192.168.1.50" },
  { id: "p2", name: "طابعة الباريستا - الأرضي", role: "bar", zoneId: "ground", ip: "192.168.1.51" },
  { id: "p3", name: "طابعة المطبخ", role: "kitchen", zoneId: "all", ip: "192.168.1.52" },
  { id: "p4", name: "طابعة الأراجيل - الروف", role: "hookah", zoneId: "roof", ip: "192.168.1.53" },
];
const ICE_GROUP = { id: "ice", name: "الثلج", type: "single", options: ["عادي", "قليل", "بدون ثلج"] };
const SUGAR_GROUP = { id: "sugar", name: "درجة السكر", type: "single", options: ["سادة", "وسط", "حلوة"] };

const MOD_PRESETS = [
  { key: "sugar", label: "🍬 درجة السكر", group: { name: "درجة السكر", type: "single", options: ["سادة", "وسط", "حلوة"] } },
  { key: "ice", label: "🧊 الثلج", group: { name: "الثلج", type: "single", options: ["عادي", "قليل", "بدون ثلج"] } },
  { key: "size", label: "📏 الحجم", group: { name: "الحجم", type: "single", options: ["صغير", "وسط", "كبير"] } },
  { key: "coffeeFlavor", label: "☕ نكهة قهوة", group: { name: "النكهة", type: "single", options: ["قهوة", "شوكولاتة", "كراميل"] } },
  { key: "juiceFlavor", label: "🍓 نكهة عصير", group: { name: "النكهة", type: "single", options: ["توت", "عنب", "برتقال", "مانجا", "فراولة"] } },
  { key: "milk", label: "🥛 نوع الحليب", group: { name: "نوع الحليب", type: "single", options: ["عادي", "لايت", "بدون حليب"] } },
  { key: "addons", label: "➕ إضافات", group: { name: "إضافات", type: "multi", options: ["زيتون", "جبنة إضافية", "بدون بندورة"] } },
  { key: "nosugar", label: "🚫 بدون سكر", group: { name: "إضافات", type: "multi", options: ["بدون سكر"] } },
];

const DEFAULT_MENU = [
  { catId: "hot", catName: "قهوة ساخنة", items: [
    { id: "esp_double", name: "إسبريسو دبل", price: 1.0, stock: 40, icon: "☕", modifierGroups: [SUGAR_GROUP] },
    { id: "amc", name: "أمريكانو", price: 1.0, stock: 40, icon: "☕", modifierGroups: [SUGAR_GROUP] },
    { id: "flat_white", name: "فلات وايت", price: 1.5, stock: 30, icon: "☕", modifierGroups: [SUGAR_GROUP] },
    { id: "cap", name: "كابتشينو", price: 1.75, stock: 30, icon: "☕", modifierGroups: [SUGAR_GROUP] },
    { id: "lat", name: "لاتيه", price: 1.75, stock: 30, icon: "☕", modifierGroups: [SUGAR_GROUP] },
    { id: "mocha_hot", name: "موكا شوكلت", price: 1.75, stock: 25, icon: "☕", modifierGroups: [SUGAR_GROUP] },
    { id: "spanish_lat", name: "سبانش لاتيه", price: 1.75, stock: 25, icon: "☕", modifierGroups: [SUGAR_GROUP] },
    { id: "trk", name: "قهوة تركية (العميد)", price: 1.5, stock: 25, icon: "☕", modifierGroups: [SUGAR_GROUP] },
  ]},
  { catId: "cold", catName: "قهوة باردة", items: [
    { id: "esp_freddo", name: "إسبريسو الفريدو", price: 1.0, stock: 20, icon: "🧊", modifierGroups: [SUGAR_GROUP] },
    { id: "iced_lat", name: "لاتيه مثلج", price: 1.75, stock: 20, icon: "🧊", modifierGroups: [SUGAR_GROUP, ICE_GROUP] },
    { id: "frap", name: "فرابتشينو", price: 2.0, stock: 15, icon: "🥤", modifierGroups: [SUGAR_GROUP, ICE_GROUP] },
    { id: "caramel_mac", name: "كراميل مكياتو", price: 1.75, stock: 15, icon: "🧊", modifierGroups: [SUGAR_GROUP, ICE_GROUP] },
    { id: "amc_cold", name: "أمريكانو بارد", price: 1.0, stock: 20, icon: "🧊", modifierGroups: [SUGAR_GROUP, ICE_GROUP] },
    { id: "mocha_cold", name: "موكا مثلجة", price: 1.75, stock: 20, icon: "🧊", modifierGroups: [SUGAR_GROUP, ICE_GROUP] },
  ]},
  { catId: "hot_drinks", catName: "مشاريب ساخنة", items: [
    { id: "hcho", name: "هوت شوكلت", price: 1.5, stock: 15, icon: "🍫", modifierGroups: [] },
    { id: "tea", name: "شاي", price: 1.0, stock: 50, icon: "🍵", modifierGroups: [SUGAR_GROUP] },
    { id: "tea_karak", name: "شاي كرك", price: 1.5, stock: 30, icon: "🍵", modifierGroups: [SUGAR_GROUP] },
    { id: "nescafe", name: "نسكافيه", price: 1.0, stock: 25, icon: "☕", modifierGroups: [SUGAR_GROUP] },
    { id: "herbs", name: "أعشاب", price: 1.0, stock: 20, icon: "🌿", modifierGroups: [] },
  ]},
  { catId: "cold_drinks", catName: "مشاريب باردة", items: [
    { id: "milkshake", name: "ميلك شيك", price: 2.5, stock: 20, icon: "🥤", modifierGroups: [{ id: "flavor", name: "النكهة", type: "single", options: ["سنكرز", "فانيلا", "شوكلت", "أوريو", "مانجو", "فراولة", "كروكان", "تشيز كيك", "لوتس"] }] },
    { id: "iced_tea", name: "شاي مثلج", price: 2.0, stock: 20, icon: "🧊", modifierGroups: [] },
    { id: "soda", name: "مشاريب غازية", price: 1.0, stock: 40, icon: "🥤", modifierGroups: [{ id: "flavor", name: "النوع", type: "single", options: ["سڤن", "بيبسي", "مرندا"] }] },
    { id: "smoothie", name: "سموذي", price: 2.0, stock: 15, icon: "🥤", modifierGroups: [] },
    { id: "cocktail", name: "كوكتيلات", price: 2.5, stock: 15, icon: "🍹", modifierGroups: [] },
    { id: "berrican", name: "ببريكان", price: 1.5, stock: 15, icon: "🥤", modifierGroups: [] },
  ]},
  { catId: "juices", catName: "العصائر الطبيعية", items: [
    { id: "juice_mango", name: "عصير مانجو", price: 2.0, stock: 15, icon: "🧃", modifierGroups: [] },
    { id: "juice_lemon_mint", name: "عصير ليمون ونعنع", price: 2.0, stock: 15, icon: "🧃", modifierGroups: [] },
    { id: "juice_lemon", name: "عصير ليمون", price: 2.0, stock: 15, icon: "🧃", modifierGroups: [] },
    { id: "juice_strawberry", name: "عصير فراولة", price: 2.0, stock: 15, icon: "🧃", modifierGroups: [] },
    { id: "juice_guava", name: "عصير جوافة", price: 2.0, stock: 15, icon: "🧃", modifierGroups: [] },
  ]},
  { catId: "mojito", catName: "موهيتو", items: [
    { id: "mojito_7up", name: "موهيتو سڤن", price: 1.75, stock: 20, icon: "🍹", modifierGroups: [{ id: "flavor", name: "النكهة", type: "single", options: ["كيوي", "بلوبيري", "بطيخ", "مكس بيري", "أناناس", "ستروبيري", "مانجو", "خوخ"] }] },
    { id: "mojito_bm", name: "موهيتو BM", price: 2.0, stock: 20, icon: "🍹", modifierGroups: [{ id: "flavor", name: "النكهة", type: "single", options: ["كيوي", "بلوبيري", "بطيخ", "مكس بيري", "أناناس", "ستروبيري", "مانجو", "خوخ"] }] },
    { id: "mojito_boom", name: "موهيتو بوم بوم", price: 2.25, stock: 20, icon: "🍹", modifierGroups: [{ id: "flavor", name: "النكهة", type: "single", options: ["كيوي", "بلوبيري", "بطيخ", "مكس بيري", "أناناس", "ستروبيري", "مانجو", "خوخ"] }] },
    { id: "mojito_redbull", name: "موهيتو ريد بول", price: 2.75, stock: 20, icon: "🍹", modifierGroups: [{ id: "flavor", name: "النكهة", type: "single", options: ["كيوي", "بلوبيري", "بطيخ", "مكس بيري", "أناناس", "ستروبيري", "مانجو", "خوخ"] }] },
  ]},
  { catId: "hookah", catName: "الأراجيل", items: [
    { id: "hookah_mazaya", name: "مزايا", price: 3.0, stock: 100, icon: "💨", modifierGroups: [{ id: "flavor", name: "النكهة", type: "single", options: ["تفاحتين", "ليمون ونعنع", "بطيخ ونعنع", "علكة ونعنع", "علكة وقرفة", "علكة", "علكة ومستكة", "عنب توت", "بلوبيري", "love", "كاندي"] }] },
    { id: "hookah_nakhla", name: "نخلة", price: 4.0, stock: 100, icon: "💨", modifierGroups: [{ id: "flavor", name: "النكهة", type: "single", options: ["تفاحتين", "ليمون ونعنع", "بطيخ ونعنع", "علكة ونعنع", "علكة وقرفة", "علكة", "علكة ومستكة", "عنب توت", "بلوبيري", "love", "كاندي"] }] },
    { id: "hookah_fakher", name: "فاخر", price: 4.0, stock: 100, icon: "🌬️", modifierGroups: [{ id: "flavor", name: "النكهة", type: "single", options: ["تفاحتين", "ليمون ونعنع", "بطيخ ونعنع", "علكة ونعنع", "علكة وقرفة", "علكة", "علكة ومستكة", "عنب توت", "بلوبيري", "love", "كاندي"] }] },
    { id: "hookah_zaghloul", name: "زغلول", price: 3.0, stock: 100, icon: "💨", modifierGroups: [{ id: "flavor", name: "النكهة", type: "single", options: ["تفاحتين", "ليمون ونعنع", "بطيخ ونعنع", "علكة ونعنع", "علكة وقرفة", "علكة", "علكة ومستكة", "عنب توت", "بلوبيري", "love", "كاندي"] }] },
    { id: "hookah_zaghloul_nakhla", name: "زغلول (نخلة)", price: 4.0, stock: 100, icon: "💨", modifierGroups: [{ id: "flavor", name: "النكهة", type: "single", options: ["تفاحتين", "ليمون ونعنع", "بطيخ ونعنع", "علكة ونعنع", "علكة وقرفة", "علكة", "علكة ومستكة", "عنب توت", "بلوبيري", "love", "كاندي"] }] },
    { id: "hookah_lamma", name: "خلطة اللمة", price: 3.5, stock: 100, icon: "💨", modifierGroups: [{ id: "flavor", name: "النكهة", type: "single", options: ["تفاحتين", "ليمون ونعنع", "بطيخ ونعنع", "علكة ونعنع", "علكة وقرفة", "علكة", "علكة ومستكة", "عنب توت", "بلوبيري", "love", "كاندي"] }] },
    { id: "hookah_service", name: "خدمة الأراجيل", price: 2.0, stock: 200, icon: "🧰", modifierGroups: [] },
    { id: "hookah_head", name: "تجديد رأس الأرجيلة", price: 1.5, stock: 200, icon: "🔄", modifierGroups: [] },
  ]},
  { catId: "snacks", catName: "تسالي", items: [
    { id: "popcorn", name: "بوشار", price: 1.0, stock: 20, icon: "🍿", modifierGroups: [] },
    { id: "nuts", name: "مكسرات", price: 1.0, stock: 20, icon: "🥜", modifierGroups: [] },
    { id: "waffle", name: "وافل", price: 1.5, stock: 15, icon: "🧇", modifierGroups: [] },
    { id: "waffle_fruit", name: "وافل مع فواكه", price: 2.0, stock: 15, icon: "🧇", modifierGroups: [] },
    { id: "fruit_plate", name: "صحن فواكه", price: 5.0, stock: 10, icon: "🍓", modifierGroups: [] },
  ]},
  { catId: "addons", catName: "إضافات", items: [
    { id: "addon_flifer", name: "فليفر", price: 0.25, stock: 100, icon: "➕", modifierGroups: [] },
    { id: "addon_sauce", name: "صوص", price: 0.5, stock: 100, icon: "➕", modifierGroups: [] },
    { id: "addon_may", name: "مي", price: 0.35, stock: 100, icon: "➕", modifierGroups: [] },
    { id: "addon_espresso_shot", name: "شوت إسبريسو", price: 0.75, stock: 100, icon: "➕", modifierGroups: [] },
  ]},
];

const CONFIG_VERSION = 6; // bump this any time DEFAULT_MENU / DEFAULT_STAFF / DEFAULT_ZONES change, so saved shared data doesn't shadow the update
const money = (n) => `${n.toFixed(2)} د.أ`;
const uid = () => Math.random().toString(36).slice(2, 9);

function timeAgo(ts, now) {
  const mins = Math.max(0, Math.round((now - ts) / 60000));
  if (mins < 1) return "الآن";
  if (mins === 1) return "قبل دقيقة";
  if (mins === 2) return "قبل دقيقتين";
  if (mins < 11) return `قبل ${mins} دقائق`;
  return `قبل ${mins} دقيقة`;
}

function computeTotals(items, discountPct, vatPct) {
  const subtotal = items.reduce((s, i) => s + i.price * i.qty, 0);
  const net = subtotal * (1 - discountPct / 100);
  const vatAmount = net * (vatPct / 100);
  const total = net + vatAmount;
  return { subtotal, net, vatAmount, total };
}

function orderLabel(o) {
  return o.orderType === "dine-in" ? `${o.zoneName ? o.zoneName + " · " : ""}طاولة ${o.table}` : "Take Away";
}

function getPeriodRange(period, ref = new Date(), customRange = null) {
  if (period === "all") return null;
  if (period === "custom") {
    if (!customRange || !customRange.start || !customRange.end) return null;
    const start = new Date(customRange.start);
    start.setHours(0, 0, 0, 0);
    const end = new Date(customRange.end);
    end.setHours(23, 59, 59, 999);
    return { start: start.getTime(), end: end.getTime() };
  }
  const start = new Date(ref);
  start.setHours(0, 0, 0, 0);
  if (period === "daily") {
    return { start: start.getTime(), end: ref.getTime() };
  }
  if (period === "weekly") {
    // custom work-week starting Saturday (JS getDay: Sun=0 ... Sat=6)
    const day = start.getDay();
    const daysSinceSaturday = (day + 1) % 7;
    start.setDate(start.getDate() - daysSinceSaturday);
    return { start: start.getTime(), end: ref.getTime() };
  }
  if (period === "monthly") {
    start.setDate(1);
    return { start: start.getTime(), end: ref.getTime() };
  }
  return null;
}

function PeriodTabs({ period, setPeriod, customRange, setCustomRange }) {
  return (
    <div>
      <div className="subtab-row" style={{ flexWrap: "wrap" }}>
        <button className={`subtab-btn ${period === "daily" ? "active" : ""}`} onClick={() => setPeriod("daily")}>📅 اليوم</button>
        <button className={`subtab-btn ${period === "weekly" ? "active" : ""}`} onClick={() => setPeriod("weekly")}>🗓️ الأسبوع (من السبت)</button>
        <button className={`subtab-btn ${period === "monthly" ? "active" : ""}`} onClick={() => setPeriod("monthly")}>📆 الشهر</button>
        <button className={`subtab-btn ${period === "all" ? "active" : ""}`} onClick={() => setPeriod("all")}>الكل</button>
        {setCustomRange && (
          <button className={`subtab-btn ${period === "custom" ? "active" : ""}`} onClick={() => setPeriod("custom")}>🗓️ تاريخ مخصّص</button>
        )}
      </div>
      {period === "custom" && setCustomRange && (
        <div className="row-wrap" style={{ marginTop: 10, alignItems: "center" }}>
          <span style={{ fontSize: 12.5, color: "var(--muted)" }}>من</span>
          <input
            type="date"
            className="login-input"
            style={{ width: 160, marginBottom: 0 }}
            value={customRange.start || ""}
            onChange={(e) => setCustomRange((prev) => ({ ...prev, start: e.target.value }))}
          />
          <span style={{ fontSize: 12.5, color: "var(--muted)" }}>إلى</span>
          <input
            type="date"
            className="login-input"
            style={{ width: 160, marginBottom: 0 }}
            value={customRange.end || ""}
            onChange={(e) => setCustomRange((prev) => ({ ...prev, end: e.target.value }))}
          />
        </div>
      )}
    </div>
  );
}

function CafePOS() {
  const [view, setView] = useState("owner"); // owner | waiter | cashier
  const [staff, setStaff] = useState(DEFAULT_STAFF);
  const [menu, setMenu] = useState(DEFAULT_MENU);
  const [vatPct, setVatPct] = useState(16);
  const [ownerEmail, setOwnerEmail] = useState("owner@cafe.com");
  const [ownerPassword, setOwnerPassword] = useState("change-me-123");
  const [ownerLoggedIn, setOwnerLoggedIn] = useState(false);
  const [ownerLoginEmail, setOwnerLoginEmail] = useState("");
  const [ownerLoginPassword, setOwnerLoginPassword] = useState("");
  const [ownerLoginError, setOwnerLoginError] = useState("");
  const [zones, setZones] = useState(DEFAULT_ZONES);
  const [printers, setPrinters] = useState(DEFAULT_PRINTERS);
  const [expenses, setExpenses] = useState([]);
  const [cashClosings, setCashClosings] = useState([]);
  const [reportsPeriod, setReportsPeriod] = useState("daily");
  const [reportsCustomRange, setReportsCustomRange] = useState({ start: "", end: "" });
  const [expensesPeriod, setExpensesPeriod] = useState("daily");
  const [expensesCustomRange, setExpensesCustomRange] = useState({ start: "", end: "" });
  const [showClosingModal, setShowClosingModal] = useState(false);
  const [actualCashInput, setActualCashInput] = useState("");
  const [actualCardInput, setActualCardInput] = useState("");
  const [actualClickInput, setActualClickInput] = useState("");

  const [waiterStaffId, setWaiterStaffId] = useState(null);
  const [cashierStaffId, setCashierStaffId] = useState(null);
  const [loginUsername, setLoginUsername] = useState("");
  const [loginPassword, setLoginPassword] = useState("");
  const [loginError, setLoginError] = useState("");
  const [orderType, setOrderType] = useState("dine-in"); // dine-in | takeaway
  const [selectedZone, setSelectedZone] = useState(DEFAULT_ZONES[0].id);
  const [selectedTable, setSelectedTable] = useState(null);
  const [newZoneName, setNewZoneName] = useState("");
  const [newTableLabel, setNewTableLabel] = useState({});
  const [activeCategory, setActiveCategory] = useState(DEFAULT_MENU[0].catId);
  const [cart, setCart] = useState([]);
  const [note, setNote] = useState("");
  const [discountPct, setDiscountPct] = useState(0);

  const [orders, setOrders] = useState([]);
  const [orderCounter, setOrderCounter] = useState(3025);
  const [selectedOrderId, setSelectedOrderId] = useState(null);

  const [toast, setToast] = useState(null);
  const [now, setNow] = useState(Date.now());
  const [ownerTab, setOwnerTab] = useState("staff");
  const [newStaffName, setNewStaffName] = useState("");
  const [newStaffType, setNewStaffType] = useState("نادل");
  const [newStaffAssignedZone, setNewStaffAssignedZone] = useState("all");
  const [newStaffUsername, setNewStaffUsername] = useState("");
  const [newStaffPassword, setNewStaffPassword] = useState("");
  const [menuEditItem, setMenuEditItem] = useState(null);
  const [restockAmount, setRestockAmount] = useState({});
  const [preBillData, setPreBillData] = useState(null);
  const [printData, setPrintData] = useState(null);
  const [splitOrderId, setSplitOrderId] = useState(null);
  const [splitCash, setSplitCash] = useState("");
  const [splitCard, setSplitCard] = useState("");
  const [cashierSubTab, setCashierSubTab] = useState("active"); // active | all
  const [cashierZoneFilter, setCashierZoneFilter] = useState("all"); // all | <zoneId> | takeaway
  const [allOrdersFilter, setAllOrdersFilter] = useState("all"); // all | dine-in | takeaway
  const [pendingModItem, setPendingModItem] = useState(null); // item awaiting modifier selection
  const [modTargetOrderId, setModTargetOrderId] = useState(null); // if set, modifier confirm adds to this existing order instead of the draft cart
  const [cashierAddItemOrderId, setCashierAddItemOrderId] = useState(null);
  const [cashierPickerCategory, setCashierPickerCategory] = useState(null);
  const [modSelections, setModSelections] = useState({});
  const [configLoaded, setConfigLoaded] = useState(false);
  const [ordersLoaded, setOrdersLoaded] = useState(false);
  const [lastSync, setLastSync] = useState(null);
  const [syncError, setSyncError] = useState(false);
  const configVersionRef = useRef(0);
  const ordersVersionRef = useRef(0);
  const savingRef = useRef(false);
  const sessionIdRef = useRef(uid());
  const [activeSessions, setActiveSessions] = useState({}); // sessionId -> { staffId, staffName, role, zoneId, zoneName, lastSeen }
  const booksVersionRef = useRef(0);
  const [booksLoaded, setBooksLoaded] = useState(false);

  // ---- Shared sync: load config (staff/menu/vat/printers) + orders from shared storage, then keep polling ----
  useEffect(() => {
    let cancelled = false;

    async function loadConfig() {
      try {
        const res = await window.storage.get("pos-config", true);
        if (res && !cancelled) {
          const data = JSON.parse(res.value);
          const incomingTs = data.updatedAt || 0;
          // only accept this data if it's actually newer than what we already have locally —
          // otherwise a slow/stale poll from another device could silently wipe out a fresh edit (e.g. new staff login)
          if (data.version === CONFIG_VERSION && incomingTs >= configVersionRef.current) {
            configVersionRef.current = incomingTs;
            if (data.staff) setStaff(data.staff);
            if (data.menu) setMenu(data.menu);
            if (typeof data.vatPct === "number") setVatPct(data.vatPct);
            if (data.zones) setZones(data.zones);
            if (data.printers) setPrinters(data.printers);
            if (data.ownerEmail) setOwnerEmail(data.ownerEmail);
            if (data.ownerPassword) setOwnerPassword(data.ownerPassword);
          }
        }
        if (!cancelled) setSyncError(false);
      } catch (e) {
        // key not created yet on first-ever run — that's fine, defaults will be saved
      } finally {
        if (!cancelled) { setConfigLoaded(true); setLastSync(Date.now()); }
      }
    }

    async function loadOrders() {
      try {
        const res = await window.storage.get("pos-orders", true);
        if (res && !cancelled) {
          const data = JSON.parse(res.value);
          const incomingTs = data.updatedAt || 0;
          if (incomingTs >= ordersVersionRef.current) {
            ordersVersionRef.current = incomingTs;
            if (data.orders) setOrders(data.orders);
            if (typeof data.orderCounter === "number") setOrderCounter(data.orderCounter);
          }
        }
        if (!cancelled) setSyncError(false);
      } catch (e) {
        // no shared orders yet
      } finally {
        if (!cancelled) { setOrdersLoaded(true); setLastSync(Date.now()); }
      }
    }

    async function loadBooks() {
      try {
        const res = await window.storage.get("pos-books", true);
        if (res && !cancelled) {
          const data = JSON.parse(res.value);
          const incomingTs = data.updatedAt || 0;
          if (incomingTs >= booksVersionRef.current) {
            booksVersionRef.current = incomingTs;
            if (data.expenses) setExpenses(data.expenses);
            if (data.cashClosings) setCashClosings(data.cashClosings);
          }
        }
      } catch (e) {
        // no shared books yet
      } finally {
        if (!cancelled) setBooksLoaded(true);
      }
    }

    loadConfig();
    loadOrders();
    loadBooks();
    const ordersPoll = setInterval(loadOrders, 4000);
    const configPoll = setInterval(loadConfig, 8000);
    const booksPoll = setInterval(loadBooks, 8000);
    return () => { cancelled = true; clearInterval(ordersPoll); clearInterval(configPoll); clearInterval(booksPoll); };
  }, []);

  // save config (staff/menu/vat/printers) to shared storage whenever it changes locally — only after initial load completes
  useEffect(() => {
    if (!configLoaded) return;
    const ts = Date.now();
    configVersionRef.current = ts; // this device's own edit is now the newest known version — polls older than this are ignored
    window.storage.set("pos-config", JSON.stringify({ version: CONFIG_VERSION, updatedAt: ts, staff, menu, vatPct, zones, printers, ownerEmail, ownerPassword }), true).catch(() => setSyncError(true));
  }, [staff, menu, vatPct, zones, printers, ownerEmail, ownerPassword, configLoaded]);

  // save orders to shared storage whenever they change locally
  useEffect(() => {
    if (!ordersLoaded) return;
    const ts = Date.now();
    ordersVersionRef.current = ts;
    window.storage.set("pos-orders", JSON.stringify({ updatedAt: ts, orders, orderCounter }), true).catch(() => setSyncError(true));
  }, [orders, orderCounter, ordersLoaded]);

  // save expenses/cash-closings ("the books") to shared storage whenever they change locally
  useEffect(() => {
    if (!booksLoaded) return;
    const ts = Date.now();
    booksVersionRef.current = ts;
    window.storage.set("pos-books", JSON.stringify({ updatedAt: ts, expenses, cashClosings }), true).catch(() => setSyncError(true));
  }, [expenses, cashClosings, booksLoaded]);

  useEffect(() => {
    const t = setInterval(() => setNow(Date.now()), 15000);
    return () => clearInterval(t);
  }, []);

  useEffect(() => {
    if (!toast) return;
    const t = setTimeout(() => setToast(null), 3000);
    return () => clearTimeout(t);
  }, [toast]);

  const waiterStaff = staff.find((s) => s.id === waiterStaffId) || null;
  const cashierStaff = staff.find((s) => s.id === cashierStaffId) || null;
  function hasPermission(staffObj, permId) {
    return !!staffObj?.permissions?.[permId];
  }

  useEffect(() => {
    if (waiterStaff && waiterStaff.assignedZone && waiterStaff.assignedZone !== "all") {
      setSelectedZone(waiterStaff.assignedZone);
    }
  }, [waiterStaff]);

  // ---- Presence heartbeat: let the owner see who is actually logged in right now, on any device ----
  useEffect(() => {
    let cancelled = false;
    async function publishPresence() {
      try {
        const mySessionId = sessionIdRef.current;
        const res = await window.storage.get("pos-presence", true).catch(() => null);
        const all = res ? JSON.parse(res.value) : {};
        const now = Date.now();
        // drop sessions that haven't reported in over 25s (device closed / logged out)
        Object.keys(all).forEach((sid) => { if (now - all[sid].lastSeen > 25000) delete all[sid]; });

        if (waiterStaff) {
          all[mySessionId + "-w"] = {
            staffId: waiterStaff.id, staffName: waiterStaff.name, role: "نادل",
            zoneId: waiterStaff.assignedZone !== "all" ? waiterStaff.assignedZone : selectedZone,
            zoneName: waiterStaff.assignedZone !== "all" ? zones.find((z) => z.id === waiterStaff.assignedZone)?.name : "كل المناطق",
            lastSeen: now,
          };
        } else delete all[mySessionId + "-w"];

        if (cashierStaff) {
          all[mySessionId + "-c"] = {
            staffId: cashierStaff.id, staffName: cashierStaff.name, role: "كاشير",
            zoneId: cashierStaff.assignedZone !== "all" ? cashierStaff.assignedZone : null,
            zoneName: cashierStaff.assignedZone !== "all" ? zones.find((z) => z.id === cashierStaff.assignedZone)?.name : "كل المناطق",
            lastSeen: now,
          };
        } else delete all[mySessionId + "-c"];

        if (!cancelled) {
          setActiveSessions(all);
          await window.storage.set("pos-presence", JSON.stringify(all), true);
        }
      } catch (e) {
        // presence is best-effort, ignore failures
      }
    }
    publishPresence();
    const t = setInterval(publishPresence, 6000);
    return () => { cancelled = true; clearInterval(t); };
  }, [waiterStaff, cashierStaff, selectedZone, zones]);

  function attemptLogin(allowedTypes, setter) {
    const uname = loginUsername.trim().toLowerCase();
    const match = staff.find((s) => (s.username || "").toLowerCase() === uname && s.password === loginPassword);
    if (!uname || !loginPassword) { setLoginError("لازم تدخل اسم المستخدم وكلمة السر"); return; }
    if (!match) { setLoginError("اسم المستخدم أو كلمة السر غير صحيحة"); return; }
    if (!allowedTypes.includes(match.type)) { setLoginError(`حساب "${match.name}" نوعه "${match.type}" وما إله صلاحية دخول هون`); return; }
    setter(match.id);
    setLoginUsername("");
    setLoginPassword("");
    setLoginError("");
  }
  function logoutWaiter() {
    setWaiterStaffId(null);
    setLoginError("");
  }
  function logoutCashier() {
    setCashierStaffId(null);
    setLoginError("");
  }

  function attemptOwnerLogin() {
    const email = ownerLoginEmail.trim().toLowerCase();
    if (!email || !ownerLoginPassword) { setOwnerLoginError("لازم تدخل الإيميل وكلمة السر"); return; }
    if (email !== ownerEmail.trim().toLowerCase() || ownerLoginPassword !== ownerPassword) {
      setOwnerLoginError("الإيميل أو كلمة السر غير صحيحة");
      return;
    }
    setOwnerLoggedIn(true);
    setOwnerLoginEmail("");
    setOwnerLoginPassword("");
    setOwnerLoginError("");
  }
  function logoutOwner() {
    setOwnerLoggedIn(false);
    setOwnerLoginError("");
  }

  function addZone() {
    if (!newZoneName.trim()) return;
    setZones((prev) => [...prev, { id: uid(), name: newZoneName.trim(), tables: [] }]);
    setNewZoneName("");
    setToast("تمت إضافة المنطقة");
  }
  function removeZone(zoneId) {
    setZones((prev) => prev.filter((z) => z.id !== zoneId));
    setToast("تم حذف المنطقة");
  }
  function addTableToZone(zoneId) {
    const label = (newTableLabel[zoneId] || "").trim();
    if (!label) return;
    setZones((prev) => prev.map((z) => (z.id === zoneId ? { ...z, tables: [...z.tables, label] } : z)));
    setNewTableLabel((prev) => ({ ...prev, [zoneId]: "" }));
  }
  function removeTableFromZone(zoneId, label) {
    setZones((prev) => prev.map((z) => (z.id === zoneId ? { ...z, tables: z.tables.filter((t) => t !== label) } : z)));
  }

  // ---- Printers ----
  function addPrinter(name, ip, role, zoneId) {
    if (!name.trim() || !ip.trim()) return;
    setPrinters((prev) => [...prev, { id: uid(), name: name.trim(), ip: ip.trim(), role, zoneId: zoneId || "all" }]);
    setToast("تمت إضافة الطابعة");
  }
  function updatePrinter(id, field, value) {
    setPrinters((prev) => prev.map((p) => (p.id === id ? { ...p, [field]: value } : p)));
  }
  function removePrinter(id) {
    setPrinters((prev) => prev.filter((p) => p.id !== id));
    setToast("تم حذف الطابعة");
  }

  // ---- Expenses / withdrawals (owner only) ----
  function addExpense(type, description, amount) {
    if (!description.trim() || !amount || Number(amount) <= 0) return;
    setExpenses((prev) => [...prev, { id: uid(), type, description: description.trim(), amount: Number(amount), createdAt: Date.now() }]);
    setToast(`تمت إضافة ${type === "purchase" ? "المشترى" : "السحب"}`);
  }
  function removeExpense(id) {
    setExpenses((prev) => prev.filter((e) => e.id !== id));
    setToast("تم حذف السجل");
  }

  // ---- Daily cashier closing ----
  function closeCashierShift(cashierName, zoneName, expectedCash, expectedCard, actualCash, actualCard, clickCount, clickAmount) {
    const variance = Number(actualCash) - expectedCash;
    const cardVariance = Number(actualCard) - expectedCard;
    setCashClosings((prev) => [
      ...prev,
      { id: uid(), cashierName, zoneName, expectedCash, expectedCard, actualCash: Number(actualCash), actualCard: Number(actualCard), variance, cardVariance, clickCount: clickCount || 0, clickAmount: Number(clickAmount) || 0, closedAt: Date.now() },
    ]);
    const grandTotal = Number(actualCash) + Number(actualCard) + (Number(clickAmount) || 0);
    setToast(`تم إغلاق الشفت — الإجمالي ${money(grandTotal)} 💰`);
  }

  const totals = computeTotals(cart, discountPct, vatPct);

  function qtyInCartForId(itemId) {
    return cart.filter((c) => c.id === itemId).reduce((s, c) => s + c.qty, 0);
  }

  function addToCart(item) {
    const usedQty = qtyInCartForId(item.id);
    if (item.stock - usedQty <= 0) {
      setToast(`عذراً، "${item.name}" خلص من المخزون`);
      return;
    }
    if (item.modifierGroups && item.modifierGroups.length > 0) {
      const defaults = {};
      item.modifierGroups.forEach((g) => { defaults[g.id] = g.type === "multi" ? [] : g.options[0]; });
      setModSelections(defaults);
      setPendingModItem(item);
      return;
    }
    addLineToCart(item, {}, "");
  }

  function addLineToCart(item, mods, modsLabel) {
    const cartKey = `${item.id}::${JSON.stringify(mods)}`;
    const station = item.station || CATEGORY_STATION[item.catId] || "bar";
    setCart((prev) => {
      const existing = prev.find((i) => i.cartKey === cartKey);
      if (existing) return prev.map((i) => (i.cartKey === cartKey ? { ...i, qty: i.qty + 1 } : i));
      return [...prev, { id: item.id, name: item.name, price: item.price, icon: item.icon, qty: 1, cartKey, mods, modsLabel, station }];
    });
  }

  function confirmModifierSelection() {
    const item = pendingModItem;
    if (!item) return;
    const labelParts = [];
    item.modifierGroups.forEach((g) => {
      const val = modSelections[g.id];
      if (g.type === "multi") {
        if (val && val.length) labelParts.push(val.join("، "));
      } else if (val) {
        labelParts.push(val);
      }
    });
    const label = labelParts.join(" · ");
    if (modTargetOrderId) {
      const targetOrder = orders.find((o) => o.id === modTargetOrderId);
      if (targetOrder) addNewItemToExistingOrder(targetOrder, item, modSelections, label, cashierStaff?.name || "الكاشير");
      setModTargetOrderId(null);
    } else {
      addLineToCart(item, modSelections, label);
    }
    setPendingModItem(null);
    setModSelections({});
  }

  function toggleModOption(group, option) {
    setModSelections((prev) => {
      if (group.type === "single") return { ...prev, [group.id]: option };
      const current = prev[group.id] || [];
      const next = current.includes(option) ? current.filter((o) => o !== option) : [...current, option];
      return { ...prev, [group.id]: next };
    });
  }

  function changeQty(cartKey, delta) {
    setCart((prev) => prev.map((i) => (i.cartKey === cartKey ? { ...i, qty: i.qty + delta } : i)).filter((i) => i.qty > 0));
  }

  function deductStockForCart(cartItems) {
    const qtyById = {};
    cartItems.forEach((c) => { qtyById[c.id] = (qtyById[c.id] || 0) + c.qty; });
    setMenu((prev) => prev.map((cat) => ({ ...cat, items: cat.items.map((it) => (qtyById[it.id] ? { ...it, stock: Math.max(0, it.stock - qtyById[it.id]) } : it)) })));
  }

  function startOverDraft() {
    setCart([]);
    setNote("");
    setDiscountPct(0);
    setSelectedTable(null);
    setOrderType("dine-in");
    setToast("تم البدء من جديد");
  }
  function voidAllDraft() {
    if (cart.length === 0) return;
    setCart([]);
    setToast("تم إلغاء كل الأصناف من الطلب الحالي");
  }
  function preBillDraft() {
    if (cart.length === 0) {
      setToast("الطلب فارغ، ضيف أصناف أول");
      return;
    }
    const zoneName = zones.find((z) => z.id === selectedZone)?.name || "";
    setPreBillData({ label: orderType === "dine-in" ? (selectedTable ? `${zoneName} · طاولة ${selectedTable}` : "بدون طاولة") : "Take Away", items: cart, ...totals });
  }

  function getOpenOrderForTable(zoneId, tableLabel) {
    return orders.find((o) => o.orderType === "dine-in" && o.zoneId === zoneId && o.table === tableLabel && o.status === "pending");
  }

  function routingToastFor(items) {
    const hasBar = items.some((i) => i.station === "bar");
    const hasKitchen = items.some((i) => i.station === "kitchen");
    const hasHookah = items.some((i) => i.station === "hookah");
    const parts = [];
    if (hasBar) parts.push("☕ الباريستا");
    if (hasKitchen) parts.push("🍽️ المطبخ");
    if (hasHookah) parts.push("💨 الأراجيل");
    return parts.length ? ` — رايح لـ ${parts.join(" و ")}` : "";
  }

  function submitOrder() {
    if ((orderType === "dine-in" && !selectedTable) || cart.length === 0) return;

    const existing = orderType === "dine-in" ? getOpenOrderForTable(selectedZone, selectedTable) : null;

    if (existing) {
      const mergedItems = [...existing.items];
      cart.forEach((c) => {
        const found = mergedItems.find((i) => i.cartKey === c.cartKey);
        if (found) found.qty += c.qty;
        else mergedItems.push({ ...c });
      });
      const mergedTotals = computeTotals(mergedItems, discountPct || existing.discountPct, vatPct);
      const mergedWaiters = Array.from(new Set([...(existing.waiters || [existing.staffName]), waiterStaff.name]));
      setOrders((prev) =>
        prev.map((o) =>
          o.id === existing.id
            ? { ...o, items: mergedItems, waiters: mergedWaiters, note: [o.note, note].filter(Boolean).join(" · "), discountPct: discountPct || o.discountPct, vatPct, ...mergedTotals, printed: false, barPrinted: false, kitchenPrinted: false, hookahPrinted: false, updatedAt: Date.now() }
            : o
        )
      );
      deductStockForCart(cart);
      startOverDraft();
      setToast(`تمت إضافة الأصناف لطلب طاولة ${selectedTable} (#${existing.id})${routingToastFor(cart)} ✅`);
      return;
    }

    const newOrder = {
      id: orderCounter,
      orderType,
      zoneId: orderType === "dine-in" ? selectedZone : null,
      zoneName: orderType === "dine-in" ? zones.find((z) => z.id === selectedZone)?.name : null,
      table: orderType === "dine-in" ? selectedTable : null,
      staffName: waiterStaff.name,
      waiters: [waiterStaff.name],
      items: cart,
      note,
      discountPct,
      vatPct,
      ...totals,
      status: "pending",
      printed: false,
      barPrinted: false,
      hookahPrinted: false,
      kitchenPrinted: false,
      createdAt: Date.now(),
      updatedAt: Date.now(),
    };
    setOrders((prev) => [...prev, newOrder]);
    setOrderCounter((c) => c + 1);
    deductStockForCart(cart);
    startOverDraft();
    setToast(`تم إرسال الطلب #${newOrder.id} إلى الكاشير${routingToastFor(cart)} ✅`);
  }

  function adjustStock(itemId, delta) {
    setMenu((prev) => prev.map((cat) => ({ ...cat, items: cat.items.map((it) => (it.id === itemId ? { ...it, stock: Math.max(0, it.stock + delta) } : it)) })));
  }

  function editExistingOrderItemQty(order, cartKey, delta, actorName) {
    const target = order.items.find((i) => i.cartKey === cartKey);
    const updatedItems = order.items.map((i) => (i.cartKey === cartKey ? { ...i, qty: i.qty + delta } : i)).filter((i) => i.qty > 0);
    const updatedTotals = computeTotals(updatedItems, order.discountPct, order.vatPct);
    const waiters = Array.from(new Set([...(order.waiters || [order.staffName]), actorName]));
    setOrders((prev) => prev.map((o) => (o.id === order.id ? { ...o, items: updatedItems, waiters, ...updatedTotals, printed: false, updatedAt: Date.now() } : o)));
    if (target) adjustStock(target.id, -delta);
  }
  function removeExistingOrderItem(order, cartKey, actorName) {
    const target = order.items.find((i) => i.cartKey === cartKey);
    const updatedItems = order.items.filter((i) => i.cartKey !== cartKey);
    const updatedTotals = computeTotals(updatedItems, order.discountPct, order.vatPct);
    const waiters = Array.from(new Set([...(order.waiters || [order.staffName]), actorName]));
    setOrders((prev) => prev.map((o) => (o.id === order.id ? { ...o, items: updatedItems, waiters, ...updatedTotals, printed: false, updatedAt: Date.now() } : o)));
    if (target) adjustStock(target.id, target.qty);
  }
  function addNewItemToExistingOrder(order, item, mods, modsLabel, actorName) {
    const station = item.station || CATEGORY_STATION[item.catId] || "bar";
    const cartKey = `${item.id}::${JSON.stringify(mods)}`;
    const existingLine = order.items.find((i) => i.cartKey === cartKey);
    const updatedItems = existingLine
      ? order.items.map((i) => (i.cartKey === cartKey ? { ...i, qty: i.qty + 1 } : i))
      : [...order.items, { id: item.id, name: item.name, price: item.price, icon: item.icon, qty: 1, cartKey, mods, modsLabel, station }];
    const updatedTotals = computeTotals(updatedItems, order.discountPct, order.vatPct);
    const waiters = Array.from(new Set([...(order.waiters || [order.staffName]), actorName]));
    setOrders((prev) => prev.map((o) => (o.id === order.id ? { ...o, items: updatedItems, waiters, ...updatedTotals, printed: false, barPrinted: false, kitchenPrinted: false, hookahPrinted: false, updatedAt: Date.now() } : o)));
    adjustStock(item.id, -1);
    setToast(`تمت إضافة ${item.name} للطلب #${order.id}`);
  }
  function markPaid(orderId, method) {
    setOrders((prev) => prev.map((o) => (o.id === orderId ? { ...o, status: "paid", paymentMethod: method, cashierName: cashierStaff?.name, paidAt: Date.now(), printed: true } : o)));
    setSelectedOrderId(null);
    setToast(`تم تحصيل الطلب #${orderId} (${method}) 💰`);
  }
  function markPaidSplit(orderId, cashAmount, cardAmount) {
    setOrders((prev) =>
      prev.map((o) =>
        o.id === orderId
          ? { ...o, status: "paid", paymentMethod: "مقسّم", cashAmount, cardAmount, cashierName: cashierStaff?.name, paidAt: Date.now(), printed: true }
          : o
      )
    );
    setSelectedOrderId(null);
    setSplitOrderId(null);
    setToast(`تم تحصيل الطلب #${orderId} (نقدي ${money(cashAmount)} + بطاقة ${money(cardAmount)}) 💰`);
  }
  function deleteOrder(orderId) {
    setOrders((prev) => prev.filter((o) => o.id !== orderId));
    setSelectedOrderId(null);
    setToast(`تم إلغاء الطلب #${orderId}`);
  }
  function holdOrder(orderId) {
    setOrders((prev) => prev.map((o) => (o.id === orderId ? { ...o, status: "held", heldAt: Date.now() } : o)));
    setSelectedOrderId(null);
    setToast(`تم تعليق الفاتورة #${orderId}`);
  }
  function reopenOrder(orderId) {
    setOrders((prev) => prev.map((o) => (o.id === orderId ? { ...o, status: "pending" } : o)));
    setToast(`تم إعادة فتح الفاتورة #${orderId}`);
  }
  function preBillOrder(order) {
    setOrders((prev) => prev.map((o) => (o.id === order.id ? { ...o, printed: true } : o)));
    setPreBillData({ label: `#${order.id} · ${orderLabel(order)}`, items: order.items, subtotal: order.subtotal, net: order.net, vatAmount: order.vatAmount, total: order.total });
  }
  function openDrawer() {
    setToast("🔓 تم فتح درج الكاش");
  }
  const STATION_FLAG_FIELD = { bar: "barPrinted", kitchen: "kitchenPrinted", hookah: "hookahPrinted" };

  function printStationTicket(order, station) {
    const items = order.items.filter((i) => i.station === station);
    if (items.length === 0) return;
    setOrders((prev) => prev.map((o) => (o.id === order.id ? { ...o, [STATION_FLAG_FIELD[station]]: true } : o)));
    setPrintData({
      orderId: order.id,
      label: `${STATION_LABEL[station]} · ${orderLabel(order)}`,
      staffName: order.staffName,
      items,
      subtotal: items.reduce((s, i) => s + i.price * i.qty, 0),
      net: null,
      vatAmount: null,
      total: null,
      stationTicket: true,
      date: new Date().toLocaleString("ar"),
    });
    setTimeout(() => {
      window.print();
      setPrintData(null);
    }, 150);
  }

  function printReceipt(order) {
    setOrders((prev) => prev.map((o) => (o.id === order.id ? { ...o, printed: true } : o)));
    setPrintData({
      orderId: order.id,
      label: orderLabel(order),
      staffName: order.staffName,
      paymentMethod: order.paymentMethod,
      cashAmount: order.cashAmount,
      cardAmount: order.cardAmount,
      items: order.items,
      subtotal: order.subtotal,
      net: order.net,
      vatAmount: order.vatAmount,
      vatPct: order.vatPct,
      total: order.total,
      date: new Date(order.paidAt || order.createdAt).toLocaleString("ar"),
    });
    setTimeout(() => {
      window.print();
      setPrintData(null);
    }, 150);
  }

  function resetAll() {
    setOrders([]);
    setCart([]);
    setSelectedTable(null);
    setSelectedOrderId(null);
    setOrderCounter(3025);
    setMenu(DEFAULT_MENU);
    setVatPct(16);
    setZones(DEFAULT_ZONES);
    setStaff(DEFAULT_STAFF);
    setCurrentStaffId(null);
    setToast("تم تصفير كل البيانات");
  }

  // ---- Owner: staff management ----
  function addStaff() {
    if (!newStaffName.trim() || !newStaffUsername.trim() || !newStaffPassword.trim()) {
      setToast("لازم تعبي الاسم واسم المستخدم وكلمة السر");
      return;
    }
    if (staff.some((s) => (s.username || "").toLowerCase() === newStaffUsername.trim().toLowerCase())) {
      setToast("اسم المستخدم هذا مستخدم لموظف تاني، اختار اسم مختلف");
      return;
    }
    const basePerms = { editMenu: false, deleteOrder: false, applyDiscount: false, viewReports: false, manageInventory: false, addToOpenOrder: false, removeFromOpenOrder: false };
    setStaff((prev) => [...prev, { id: uid(), name: newStaffName.trim(), type: newStaffType, assignedZone: newStaffAssignedZone, username: newStaffUsername.trim(), password: newStaffPassword.trim(), permissions: basePerms }]);
    setNewStaffName("");
    setNewStaffUsername("");
    setNewStaffPassword("");
    setToast(`تمت إضافة الموظف ${newStaffName.trim()}`);
  }
  function removeStaff(id) {
    setStaff((prev) => prev.filter((s) => s.id !== id));
    if (waiterStaffId === id) setWaiterStaffId(null);
    if (cashierStaffId === id) setCashierStaffId(null);
    setToast("تم حذف الموظف");
  }
  function toggleStaffPerm(id, permId) {
    setStaff((prev) => prev.map((s) => (s.id === id ? { ...s, permissions: { ...s.permissions, [permId]: !s.permissions[permId] } } : s)));
  }
  function setStaffType(id, type) {
    setStaff((prev) => prev.map((s) => (s.id === id ? { ...s, type } : s)));
  }
  function setStaffZone(id, assignedZone) {
    setStaff((prev) => prev.map((s) => (s.id === id ? { ...s, assignedZone } : s)));
  }
  function updateStaffCredential(id, field, value) {
    setStaff((prev) => prev.map((s) => (s.id === id ? { ...s, [field]: value } : s)));
  }

  // ---- Menu management ----
  function saveMenuItem(catId, itemDraft) {
    setMenu((prev) =>
      prev.map((cat) => {
        if (cat.catId !== catId) return cat;
        const exists = cat.items.some((i) => i.id === itemDraft.id);
        return { ...cat, items: exists ? cat.items.map((i) => (i.id === itemDraft.id ? itemDraft : i)) : [...cat.items, itemDraft] };
      })
    );
    setMenuEditItem(null);
    setToast("تم حفظ الصنف");
  }
  function deleteMenuItem(catId, itemId) {
    setMenu((prev) => prev.map((cat) => (cat.catId === catId ? { ...cat, items: cat.items.filter((i) => i.id !== itemId) } : cat)));
    setToast("تم حذف الصنف");
  }
  function applyGroupsToCategory(catId, modifierGroups) {
    setMenu((prev) => prev.map((cat) => (cat.catId === catId ? { ...cat, items: cat.items.map((i) => ({ ...i, modifierGroups: modifierGroups.map((g) => ({ ...g, id: `${g.id}_${i.id}` })) })) } : cat)));
    setToast("تم تطبيق نفس الخيارات على كل أصناف هذا القسم ✅");
  }
  function restock(catId, itemId) {
    const amount = Number(restockAmount[itemId] || 0);
    if (!amount) return;
    setMenu((prev) => prev.map((cat) => (cat.catId === catId ? { ...cat, items: cat.items.map((i) => (i.id === itemId ? { ...i, stock: i.stock + amount } : i)) } : cat)));
    setRestockAmount((prev) => ({ ...prev, [itemId]: "" }));
    setToast("تم تحديث المخزون");
  }

  const allItems = menu.flatMap((c) => c.items.map((i) => ({ ...i, catId: c.catId, catName: c.catName })));
  const lowStockItems = allItems.filter((i) => i.stock <= LOW_STOCK_THRESHOLD);

  const pendingOrders = orders.filter((o) => o.status === "pending").sort((a, b) => a.createdAt - b.createdAt);
  const heldOrders = orders.filter((o) => o.status === "held").sort((a, b) => b.heldAt - a.heldAt);
  const paidOrders = orders.filter((o) => o.status === "paid").sort((a, b) => b.paidAt - a.paidAt);
  const selectedOrder = orders.find((o) => o.id === selectedOrderId);

  const filteredAllOrders = orders
    .filter((o) => allOrdersFilter === "all" || o.orderType === allOrdersFilter)
    .sort((a, b) => b.createdAt - a.createdAt);

  const reports = useMemo(() => {
    const range = getPeriodRange(reportsPeriod, new Date(), reportsCustomRange);
    const scopedPaidOrders = range ? paidOrders.filter((o) => (o.paidAt || o.createdAt) >= range.start && (o.paidAt || o.createdAt) <= range.end) : paidOrders;
    const scopedOrders = range ? orders.filter((o) => o.createdAt >= range.start && o.createdAt <= range.end) : orders;

    const totalRevenue = scopedPaidOrders.reduce((s, o) => s + o.total, 0);
    const ordersCount = scopedPaidOrders.length;
    const avgTicket = ordersCount ? totalRevenue / ordersCount : 0;

    const itemTally = {};
    scopedPaidOrders.forEach((o) => o.items.forEach((i) => {
      if (!itemTally[i.name]) itemTally[i.name] = { qty: 0, revenue: 0 };
      itemTally[i.name].qty += i.qty;
      itemTally[i.name].revenue += i.qty * i.price;
    }));
    const topItems = Object.entries(itemTally).map(([name, v]) => ({ name, ...v })).sort((a, b) => b.revenue - a.revenue).slice(0, 5);
    const maxItemRevenue = topItems.length ? topItems[0].revenue : 1;

    const byMethod = { نقدي: 0, بطاقة: 0, كليك: 0 };
    let clickCount = 0;
    scopedPaidOrders.forEach((o) => {
      if (o.paymentMethod === "مقسّم") {
        byMethod["نقدي"] += o.cashAmount || 0;
        byMethod["بطاقة"] += o.cardAmount || 0;
      } else if (o.paymentMethod) {
        byMethod[o.paymentMethod] += o.total;
        if (o.paymentMethod === "كليك") clickCount++;
      }
    });

    const byType = { "dine-in": 0, takeaway: 0 };
    scopedPaidOrders.forEach((o) => { byType[o.orderType] += o.total; });

    const byStaff = staff.map((s) => ({ name: s.name, revenue: scopedPaidOrders.filter((o) => o.staffName === s.name).reduce((sum, o) => sum + o.total, 0) }));

    const waiterActivity = staff
      .filter((s) => s.type === "نادل")
      .map((s) => ({
        name: s.name,
        count: scopedOrders.filter((o) => o.orderType === "dine-in" || o.orderType === "takeaway" ? (o.waiters || [o.staffName]).includes(s.name) : false).length,
      }))
      .sort((a, b) => b.count - a.count);
    const maxActivity = waiterActivity.length ? waiterActivity[0].count : 1;

    return { totalRevenue, ordersCount, avgTicket, topItems, maxItemRevenue, byMethod, clickCount, byType, byStaff, waiterActivity, maxActivity };
  }, [paidOrders, orders, staff, reportsPeriod, reportsCustomRange]);

  return (
    <div dir="rtl" className="app">
      <style>{`
        @import url('https://fonts.googleapis.com/css2?family=Cairo:wght@400;500;600;700;800;900&family=IBM+Plex+Mono:wght@500;600;700&display=swap');
        :root {
          --bg:#eef0f5; --surface:#ffffff; --surface-2:#f5f6fa; --border:#e3e6ee;
          --ink:#1c2033; --muted:#767b8c;
          --primary:#4f46e5; --primary-dark:#3c34b8; --primary-soft:#eeecfd;
          --success:#16a34a; --success-soft:#e6f7ec;
          --danger:#e11d48; --danger-soft:#fde8ec;
          --warning:#d97a06; --warning-soft:#fff3e2; --warning-ink:#8a5300;
          --shadow:0 2px 14px rgba(20,20,50,.07);
          --r-lg:18px; --r-md:12px; --r-sm:8px;
        }
        * { box-sizing:border-box; }
        .app { font-family:'Cairo',sans-serif; background:var(--bg); color:var(--ink); min-height:100%; padding:20px; border-radius:var(--r-lg); }
        .mono { font-family:'IBM Plex Mono',monospace; }
        .header { display:flex; flex-wrap:wrap; align-items:center; justify-content:space-between; gap:14px; background:var(--surface); border-radius:var(--r-lg); box-shadow:var(--shadow); padding:16px 22px; margin-bottom:20px; }
        .logo { font-family:'Cairo',sans-serif; font-weight:800; font-size:21px; display:flex; align-items:center; gap:10px; color:var(--ink); }
        .logo span { font-family:'IBM Plex Mono',monospace; font-size:10.5px; color:var(--muted); letter-spacing:1.5px; background:var(--surface-2); padding:3px 8px; border-radius:6px; font-weight:600; }
        .sync-badge { font-family:'Cairo',sans-serif !important; font-size:11px !important; letter-spacing:0 !important; background:var(--success-soft) !important; color:var(--success) !important; padding:4px 10px !important; border-radius:999px !important; font-weight:700 !important; }
        .sync-badge.err { background:var(--danger-soft) !important; color:var(--danger) !important; }
        .tabs { display:flex; gap:4px; background:var(--surface-2); padding:4px; border-radius:999px; }
        .tab-btn { border:none; background:transparent; color:var(--muted); font-weight:700; font-size:13.5px; padding:9px 18px; border-radius:999px; cursor:pointer; transition:all .15s; font-family:'Cairo',sans-serif; }
        .tab-btn:hover { color:var(--ink); }
        .tab-btn.active { background:var(--primary); color:#fff; box-shadow:0 3px 10px rgba(79,70,229,.35); }
        .reset-btn { border:1px solid var(--border); background:var(--surface); color:var(--muted); font-size:12px; padding:8px 14px; border-radius:var(--r-sm); cursor:pointer; font-weight:600; font-family:'Cairo',sans-serif; }
        .reset-btn:hover { color:var(--danger); border-color:var(--danger); }
        .grid-2 { display:grid; grid-template-columns:1.4fr 1fr; gap:18px; }
        @media (max-width:900px) { .grid-2 { grid-template-columns:1fr; } }
        .panel { background:var(--surface); border-radius:var(--r-lg); padding:18px; box-shadow:var(--shadow); border:1px solid var(--border); }
        .panel h3 { margin:0 0 14px; font-size:14.5px; color:var(--ink); font-weight:800; }
        .row-wrap { display:flex; flex-wrap:wrap; gap:8px; }
        .pill-btn { border:1.5px solid var(--border); background:var(--surface); color:var(--ink); padding:8px 16px; border-radius:999px; font-size:13px; font-weight:600; cursor:pointer; font-family:'Cairo',sans-serif; transition:all .15s; }
        .pill-btn.selected { background:var(--primary); border-color:var(--primary); color:#fff; font-weight:700; }
        .table-grid { display:grid; grid-template-columns:repeat(5,1fr); gap:8px; }
        .table-btn { aspect-ratio:1; border-radius:var(--r-md); border:1.5px solid var(--border); background:var(--surface-2); color:var(--ink); font-family:'IBM Plex Mono',monospace; font-weight:700; font-size:15px; cursor:pointer; transition:all .15s; }
        .table-btn.selected { background:var(--primary); border-color:var(--primary); color:#fff; }
        .table-btn.occupied { background:var(--danger-soft); border-color:var(--danger); color:var(--danger); display:flex; flex-direction:column; align-items:center; justify-content:center; gap:2px; }
        .table-btn .table-total { font-size:8.5px; font-weight:600; }
        .legend-dot { display:inline-block; width:10px; height:10px; border-radius:3px; margin:0 4px 0 10px; vertical-align:middle; }
        .legend-dot.free { background:var(--surface-2); border:1.5px solid var(--border); }
        .legend-dot.occ { background:var(--danger); }
        .reorder-banner { background:var(--warning-soft); color:var(--warning-ink); font-size:12px; font-weight:700; padding:10px 14px; border-radius:var(--r-sm); margin-bottom:10px; border:1px solid #f3d9ab; }

        .action-bar { display:flex; gap:8px; flex-wrap:wrap; margin-bottom:16px; }
        .action-btn { background:var(--surface-2); color:var(--ink); border:1px solid var(--border); padding:9px 15px; border-radius:var(--r-sm); font-size:12.5px; font-weight:700; cursor:pointer; display:flex; align-items:center; gap:6px; font-family:'Cairo',sans-serif; transition:all .15s; }
        .action-btn:hover { background:var(--border); }
        .action-btn.start { background:var(--primary-soft); color:var(--primary-dark); }
        .action-btn.warn { background:var(--danger-soft); color:var(--danger); }
        .action-btn.neutral { background:var(--surface-2); color:var(--muted); }

        .cat-rail { display:flex; flex-direction:column; gap:8px; }
        .cat-tile { border:1.5px solid transparent; border-radius:var(--r-md); padding:13px 12px; display:flex; align-items:center; gap:10px; cursor:pointer; color:var(--muted); font-weight:700; font-size:13px; text-align:right; background:var(--surface-2); font-family:'Cairo',sans-serif; transition:all .15s; }
        .cat-tile.active { background:var(--primary-soft); color:var(--primary-dark); border-color:var(--primary); }
        .cat-tile .icon-box { width:36px; height:36px; border-radius:10px; background:var(--surface); display:flex; align-items:center; justify-content:center; font-size:18px; flex-shrink:0; box-shadow:0 1px 4px rgba(0,0,0,.08); }

        .item-grid { display:grid; grid-template-columns:repeat(2,1fr); gap:10px; }
        @media (min-width:1100px) { .item-grid { grid-template-columns:repeat(3,1fr); } }
        .item-tile { border:1.5px solid var(--border); border-radius:var(--r-md); padding:14px; cursor:pointer; color:var(--ink); text-align:right; position:relative; overflow:hidden; min-height:96px; display:flex; flex-direction:column; justify-content:flex-end; background:var(--surface); transition:all .15s; }
        .item-tile:hover { border-color:var(--primary); box-shadow:var(--shadow); transform:translateY(-1px); }
        .item-tile.out { opacity:.45; cursor:not-allowed; }
        .item-tile .icon-big { position:absolute; top:10px; left:10px; font-size:19px; width:36px; height:36px; border-radius:10px; background:var(--surface-2); display:flex; align-items:center; justify-content:center; }
        .item-tile .name { font-weight:800; font-size:13.5px; margin-top:8px; }
        .item-tile .price { font-family:'IBM Plex Mono',monospace; font-size:12px; margin-top:3px; color:var(--muted); font-weight:600; }
        .item-tile .stock-tag { font-size:9.5px; margin-top:6px; background:var(--danger-soft); color:var(--danger); display:inline-block; padding:2px 7px; border-radius:5px; font-weight:700; width:fit-content; }

        .grid-layout { display:grid; grid-template-columns:150px 1fr 320px; gap:16px; }
        @media (max-width:1100px) { .grid-layout { grid-template-columns:1fr; } }

        .receipt { background:var(--surface); color:var(--ink); border-radius:var(--r-lg); padding:18px; position:relative; border:1px solid var(--border); }
        .receipt-title { font-family:'Cairo',sans-serif; font-size:13.5px; font-weight:800; color:var(--ink); text-align:center; margin-bottom:12px; padding-bottom:10px; border-bottom:1px dashed var(--border); }
        .receipt-line { display:flex; justify-content:space-between; padding:8px 0; border-bottom:1px solid var(--surface-2); font-size:13.5px; gap:8px; }
        .receipt-line .qty-ctrl { display:flex; align-items:center; gap:6px; }
        .qty-btn { width:22px; height:22px; border-radius:6px; border:1px solid var(--border); background:var(--surface-2); cursor:pointer; font-size:13px; line-height:1; color:var(--ink); }
        .receipt-empty { text-align:center; color:var(--muted); font-size:13px; padding:24px 0; }
        .receipt-sub { display:flex; justify-content:space-between; font-size:12.5px; color:var(--muted); padding:3px 0; }
        .receipt-total { display:flex; justify-content:space-between; font-weight:800; font-size:16px; padding-top:12px; margin-top:8px; border-top:2px solid var(--ink); font-family:'IBM Plex Mono',monospace; color:var(--ink); }
        .receipt-zigzag { display:none; }
        .note-input { width:100%; margin-top:10px; border:1px solid var(--border); background:var(--surface-2); border-radius:var(--r-sm); padding:9px; font-size:12.5px; color:var(--ink); resize:none; font-family:'Cairo',sans-serif; }
        .discount-row { display:flex; align-items:center; gap:8px; margin-top:10px; font-size:12.5px; color:var(--muted); }
        .discount-row input { width:60px; border:1px solid var(--border); border-radius:6px; padding:5px 7px; background:var(--surface); color:var(--ink); }
        .submit-btn { width:100%; margin-top:14px; background:var(--success); color:#fff; border:none; padding:13px; border-radius:var(--r-md); font-weight:800; font-size:14.5px; cursor:pointer; box-shadow:0 3px 10px rgba(22,163,74,.3); font-family:'Cairo',sans-serif; transition:all .15s; }
        .submit-btn:hover:not(:disabled) { background:#128a3e; }
        .submit-btn:disabled { background:var(--border); color:var(--muted); cursor:not-allowed; box-shadow:none; }

        .tickets-rail { display:flex; flex-direction:column; gap:12px; }
        .ticket-card { background:var(--surface); color:var(--ink); border-radius:var(--r-md); padding:14px 16px; cursor:pointer; border:1.5px solid var(--border); position:relative; overflow:hidden; transition:all .15s; }
        .ticket-card:hover { box-shadow:var(--shadow); }
        .ticket-card.active { border-color:var(--primary); box-shadow:0 0 0 3px var(--primary-soft); }
        .ticket-top { display:flex; justify-content:space-between; align-items:flex-start; }
        .ticket-num { font-family:'IBM Plex Mono',monospace; font-weight:700; font-size:12.5px; color:var(--muted); }
        .ticket-table { font-family:'Cairo',sans-serif; font-weight:800; font-size:17px; color:var(--ink); }
        .ticket-meta { font-size:11.5px; color:var(--muted); margin-top:6px; display:flex; gap:6px; flex-wrap:wrap; align-items:center; }
        .ticket-total { font-family:'IBM Plex Mono',monospace; font-weight:800; font-size:15px; margin-top:8px; color:var(--ink); }
        .ticket-zigzag { display:none; }
        .stamp { position:absolute; top:12px; left:12px; transform:rotate(-8deg); border:2px solid var(--success); color:var(--success); background:var(--success-soft); font-weight:800; font-size:11px; padding:3px 10px; border-radius:6px; }
        .empty-msg { text-align:center; color:var(--muted); padding:30px 10px; font-size:13.5px; }
        .detail-item-line { display:flex; justify-content:space-between; font-size:13.5px; padding:7px 0; border-bottom:1px solid var(--surface-2); }
        .pay-buttons { display:flex; gap:10px; margin-top:14px; flex-wrap:wrap; }
        .pay-btn { flex:1; border:none; border-radius:var(--r-md); padding:13px; font-weight:800; font-size:13.5px; cursor:pointer; color:#fff; min-width:120px; font-family:'Cairo',sans-serif; transition:all .15s; }
        .pay-btn:hover { filter:brightness(1.08); }
        .pay-cash { background:var(--success); }
        .pay-card { background:var(--primary); }
        .pay-split { background:var(--warning); color:var(--ink); }
        .pay-click { background:#7c3aed; }

        .print-badge { font-size:9.5px; font-weight:700; padding:2px 8px; border-radius:999px; }
        .print-badge.not-printed { background:var(--danger-soft); color:var(--danger); }
        .print-badge.printed { background:var(--success-soft); color:var(--success); }
        .type-badge { font-size:9.5px; font-weight:700; padding:2px 8px; border-radius:999px; background:var(--surface-2); color:var(--muted); }

        .kpi-grid { display:grid; grid-template-columns:repeat(4,1fr); gap:12px; margin-bottom:20px; }
        @media (max-width:900px) { .kpi-grid { grid-template-columns:repeat(2,1fr); } }
        .kpi-card { background:var(--surface); color:var(--ink); border-radius:var(--r-lg); padding:16px; border:1px solid var(--border); box-shadow:var(--shadow); }
        .kpi-label { font-size:11.5px; color:var(--muted); font-weight:700; }
        .kpi-value { font-family:'IBM Plex Mono',monospace; font-size:23px; font-weight:800; margin-top:6px; color:var(--ink); }
        .tally-row { margin-bottom:12px; }
        .tally-head { display:flex; justify-content:space-between; font-size:12.5px; margin-bottom:5px; color:var(--ink); }
        .bar-track { background:var(--surface-2); border-radius:6px; height:8px; overflow:hidden; }
        .bar-fill { height:100%; background:var(--primary); border-radius:6px; }
        table.log { width:100%; border-collapse:collapse; font-size:12.5px; }
        table.log th { text-align:right; color:var(--muted); font-size:11px; padding:8px; border-bottom:2px solid var(--border); font-weight:700; }
        table.log td { padding:9px 8px; border-bottom:1px solid var(--surface-2); color:var(--ink); }
        .badge { padding:3px 10px; border-radius:999px; font-size:11px; font-weight:700; }
        .badge.paid { background:var(--success-soft); color:var(--success); }
        .badge.pending { background:var(--danger-soft); color:var(--danger); }
        .badge.held { background:var(--warning-soft); color:var(--warning-ink); }
        .badge.role { background:var(--surface-2); color:var(--muted); }
        .toast { position:fixed; bottom:20px; left:50%; transform:translateX(-50%); background:var(--ink); color:#fff; padding:11px 20px; border-radius:999px; font-size:13px; font-weight:700; box-shadow:0 8px 24px rgba(0,0,0,.25); z-index:50; }

        .owner-subtabs { display:flex; gap:6px; margin-bottom:16px; flex-wrap:wrap; }
        .owner-subtab { background:var(--surface); color:var(--muted); border:1.5px solid var(--border); padding:9px 16px; border-radius:999px; font-weight:700; font-size:13px; cursor:pointer; font-family:'Cairo',sans-serif; }
        .owner-subtab.active { background:var(--primary); color:#fff; border-color:var(--primary); }

        .staff-card { background:var(--surface-2); color:var(--ink); border-radius:var(--r-md); padding:16px; margin-bottom:12px; border:1px solid var(--border); }
        .staff-top { display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:8px; }
        .staff-name { font-weight:800; font-size:15px; color:var(--ink); }
        .staff-type-select { border:1px solid var(--border); border-radius:8px; padding:6px 10px; background:var(--surface); font-family:'Cairo',sans-serif; font-size:12.5px; font-weight:700; color:var(--ink); }
        .perm-grid { margin-top:12px; display:grid; grid-template-columns:repeat(2,1fr); gap:8px; }
        @media (max-width:700px) { .perm-grid { grid-template-columns:1fr; } }
        .perm-toggle { display:flex; align-items:center; gap:8px; font-size:12.5px; background:var(--surface); border-radius:9px; padding:8px 12px; cursor:pointer; border:1px solid var(--border); color:var(--ink); }
        .perm-toggle input { accent-color:var(--primary); width:16px; height:16px; }
        .staff-remove { background:none; border:none; color:var(--danger); cursor:pointer; font-size:12px; font-weight:700; font-family:'Cairo',sans-serif; }
        .cred-row { display:flex; gap:10px; margin-top:10px; flex-wrap:wrap; }
        .cred-field { display:flex; flex-direction:column; gap:3px; flex:1; min-width:120px; }
        .cred-field label { font-size:10.5px; color:var(--muted); font-weight:700; }
        .cred-field input { border:1px solid var(--border); border-radius:8px; padding:6px 10px; font-size:12.5px; font-family:'IBM Plex Mono',monospace; background:var(--surface); color:var(--ink); }
        .table-chip { display:inline-flex; align-items:center; gap:6px; background:var(--surface); border:1px solid var(--border); border-radius:999px; padding:6px 12px; font-size:12.5px; font-weight:600; color:var(--ink); }
        .table-chip button { background:none; border:none; color:var(--danger); cursor:pointer; font-size:11px; padding:0; }
        .zone-lock-badge { display:inline-block; background:var(--primary-soft); color:var(--primary-dark); font-weight:800; font-size:13px; padding:9px 16px; border-radius:999px; margin-top:12px; }
        .login-wrap { display:flex; justify-content:center; padding:30px 10px; }
        .login-card { width:100%; max-width:360px; text-align:center; }
        .login-icon { font-size:34px; margin-bottom:6px; }
        .login-hint { font-size:12.5px; color:var(--muted); margin:0 0 16px; line-height:1.6; }
        .login-input { width:100%; border:1px solid var(--border); border-radius:var(--r-sm); padding:11px 14px; font-size:14px; font-family:'Cairo',sans-serif; background:var(--surface-2); color:var(--ink); margin-bottom:10px; text-align:center; }
        .login-error { background:var(--danger-soft); color:var(--danger); font-size:12.5px; font-weight:700; padding:8px 12px; border-radius:var(--r-sm); margin-bottom:10px; }

        #print-area { display: none; }
        @media print {
          body * { visibility: hidden; }
          #print-area, #print-area * { visibility: visible; }
          #print-area {
            display: block;
            position: absolute;
            top: 0; left: 0;
            width: 76mm;
            padding: 4mm;
            font-family: 'IBM Plex Mono', monospace;
            font-size: 11px;
            color: #000;
            background: #fff;
          }
          .print-title { text-align: center; font-weight: 800; font-size: 14px; margin-bottom: 6px; }
          .print-line { margin-bottom: 3px; }
          .print-sep { border-top: 1px dashed #000; margin: 6px 0; }
          .print-row { display: flex; justify-content: space-between; margin-bottom: 3px; }
          .print-total { font-weight: 800; font-size: 13px; border-top: 1px solid #000; padding-top: 4px; margin-top: 4px; }
          .print-footer { text-align: center; margin-top: 8px; }
        }
        .add-staff-row { display:flex; gap:8px; flex-wrap:wrap; margin-top:8px; }
        .add-staff-row input, .add-staff-row select { border:1px solid var(--border); background:var(--surface); color:var(--ink); border-radius:8px; padding:9px 12px; font-size:13px; font-family:'Cairo',sans-serif; }
        .add-staff-row button { background:var(--primary); color:#fff; border:none; border-radius:8px; padding:9px 18px; font-weight:700; cursor:pointer; font-family:'Cairo',sans-serif; }

        .menu-manage-card { background:var(--surface-2); color:var(--ink); border-radius:var(--r-md); padding:12px 14px; margin-bottom:8px; display:flex; justify-content:space-between; align-items:center; gap:8px; flex-wrap:wrap; border:1px solid var(--border); }
        .menu-manage-info .name { font-weight:700; font-size:13.5px; }
        .menu-manage-info .meta { font-size:11px; color:var(--muted); font-family:'IBM Plex Mono',monospace; }
        .icon-btn { background:var(--surface); color:var(--ink); border:1px solid var(--border); border-radius:8px; padding:7px 12px; font-size:12px; cursor:pointer; font-weight:600; font-family:'Cairo',sans-serif; }
        .icon-btn.danger { background:var(--danger-soft); color:var(--danger); border-color:transparent; }
        .item-form { background:var(--surface); color:var(--ink); border-radius:var(--r-md); padding:16px; margin-bottom:14px; border:1px solid var(--border); }
        .item-form-row { display:flex; gap:8px; flex-wrap:wrap; margin-bottom:8px; }
        .item-form input, .item-form select { border:1px solid var(--border); border-radius:8px; padding:8px 10px; font-size:13px; font-family:'Cairo',sans-serif; flex:1; min-width:90px; color:var(--ink); background:var(--surface); }
        .item-form button { border:none; border-radius:8px; padding:9px 18px; font-weight:700; cursor:pointer; font-family:'Cairo',sans-serif; }
        .no-access-inline { font-size:12px; color:var(--muted); background:var(--surface-2); padding:9px 14px; border-radius:8px; margin-bottom:10px; border:1px dashed var(--border); }
        .mod-editor-title { font-size:11.5px; font-weight:700; color:var(--muted); margin:12px 0 8px; }
        .mod-editor-row { display:flex; gap:6px; margin-bottom:6px; align-items:center; }
        .mod-editor-row select { border:1px solid var(--border); border-radius:8px; padding:8px 6px; font-size:12px; font-family:'Cairo',sans-serif; background:var(--surface); color:var(--ink); }
        .low-stock-banner { background:var(--warning-soft); color:var(--warning-ink); padding:11px 15px; border-radius:var(--r-sm); font-size:12.5px; font-weight:700; margin-bottom:14px; border:1px solid #f3d9ab; }
        .restock-row { display:flex; gap:6px; align-items:center; }
        .restock-row input { width:55px; border:1px solid var(--border); border-radius:8px; padding:5px 7px; font-size:12px; background:var(--surface); color:var(--ink); }

        .modal-overlay { position:fixed; inset:0; background:rgba(15,17,30,.55); backdrop-filter:blur(2px); display:flex; align-items:center; justify-content:center; z-index:100; padding:20px; }
        .modal-receipt { background:var(--surface); color:var(--ink); width:100%; max-width:380px; border-radius:var(--r-lg); padding:22px; max-height:82vh; overflow-y:auto; box-shadow:0 20px 50px rgba(0,0,0,.25); }
        .modal-receipt-header { text-align:center; font-weight:800; font-size:15px; color:var(--ink); border-bottom:1px solid var(--border); padding-bottom:12px; margin-bottom:14px; }
        .modal-close-btn { width:100%; margin-top:12px; background:var(--surface-2); color:var(--ink); border:1px solid var(--border); padding:11px; border-radius:var(--r-sm); font-weight:700; cursor:pointer; font-family:'Cairo',sans-serif; }
        .mod-label { font-size:11px; color:var(--muted); margin-right:5px; font-weight:500; }
        .mod-group { margin-bottom:18px; }
        .mod-group-title { font-size:12.5px; font-weight:700; color:var(--ink); margin-bottom:9px; }
        .mod-options { display:flex; flex-wrap:wrap; gap:8px; }
        .mod-chip { border:1.5px solid var(--border); background:var(--surface-2); color:var(--ink); padding:8px 15px; border-radius:999px; font-size:12.5px; font-weight:600; cursor:pointer; font-family:'Cairo',sans-serif; transition:all .15s; }
        .mod-chip.selected { background:var(--primary); border-color:var(--primary); color:#fff; font-weight:700; }

        .subtab-row { display:flex; gap:6px; margin-bottom:14px; }
        .subtab-btn { background:var(--surface); color:var(--muted); border:1.5px solid var(--border); padding:8px 16px; border-radius:999px; font-size:12.5px; font-weight:700; cursor:pointer; font-family:'Cairo',sans-serif; }
        .subtab-btn.active { background:var(--ink); color:#fff; border-color:var(--ink); }
        .settings-row { display:flex; align-items:center; gap:10px; margin-bottom:10px; }
        .settings-row input { width:80px; border:1px solid var(--border); border-radius:8px; padding:7px 10px; background:var(--surface); color:var(--ink); font-family:'IBM Plex Mono',monospace; }
      `}</style>

      <div className="header">
        <div className="logo">
          دفتر القهوجي <span>CAFE POS · DEMO</span>
          <span className={`sync-badge ${syncError ? "err" : ""}`}>{syncError ? "⚠️ انقطع الاتصال" : configLoaded && ordersLoaded ? "🟢 متزامن" : "⏳ يتزامن..."}</span>
        </div>
        <div className="tabs">
          <button className={`tab-btn ${view === "owner" ? "active" : ""}`} onClick={() => setView("owner")}>👑 صاحب الكافيه</button>
          <button className={`tab-btn ${view === "waiter" ? "active" : ""}`} onClick={() => setView("waiter")}>🧾 النادل</button>
          <button className={`tab-btn ${view === "cashier" ? "active" : ""}`} onClick={() => setView("cashier")}>💰 الكاشير</button>
        </div>
        <button className="reset-btn" onClick={resetAll}>🔄 تصفير البيانات</button>
      </div>

      {/* ---------------- OWNER ---------------- */}
      {view === "owner" && (
        <div>
          {!ownerLoggedIn ? (
            <LoginPanel
              title="تسجيل دخول صاحب الكافيه"
              hint="هاي الشاشة محمية — سجل دخول بالإيميل وكلمة السر يلي حددتها لنفسك"
              username={ownerLoginEmail}
              setUsername={setOwnerLoginEmail}
              password={ownerLoginPassword}
              setPassword={setOwnerLoginPassword}
              error={ownerLoginError}
              onSubmit={attemptOwnerLogin}
            />
          ) : (
          <>
          <div className="panel" style={{ marginBottom: 14, display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 8 }}>
            <span>مسجل دخول: <strong>{ownerEmail}</strong> <span className="badge role">👑 صاحب الكافيه</span></span>
            <button className="reset-btn" onClick={logoutOwner}>🚪 تسجيل خروج</button>
          </div>
          <div className="owner-subtabs">
            <button className={`owner-subtab ${ownerTab === "staff" ? "active" : ""}`} onClick={() => setOwnerTab("staff")}>👥 الموظفين والصلاحيات</button>
            <button className={`owner-subtab ${ownerTab === "menu" ? "active" : ""}`} onClick={() => setOwnerTab("menu")}>📋 إدارة القائمة</button>
            <button className={`owner-subtab ${ownerTab === "inventory" ? "active" : ""}`} onClick={() => setOwnerTab("inventory")}>📦 المخزون</button>
            <button className={`owner-subtab ${ownerTab === "zones" ? "active" : ""}`} onClick={() => setOwnerTab("zones")}>🪑 المناطق والطاولات</button>
            <button className={`owner-subtab ${ownerTab === "live" ? "active" : ""}`} onClick={() => setOwnerTab("live")}>🟢 الحالة الآن</button>
            <button className={`owner-subtab ${ownerTab === "printers" ? "active" : ""}`} onClick={() => setOwnerTab("printers")}>🖨️ الطابعات</button>
            <button className={`owner-subtab ${ownerTab === "expenses" ? "active" : ""}`} onClick={() => setOwnerTab("expenses")}>💸 المشتريات والسحوبات</button>
            <button className={`owner-subtab ${ownerTab === "closings" ? "active" : ""}`} onClick={() => setOwnerTab("closings")}>🔒 إغلاقات الكاشير</button>
            <button className={`owner-subtab ${ownerTab === "reports" ? "active" : ""}`} onClick={() => setOwnerTab("reports")}>📊 التقارير</button>
            <button className={`owner-subtab ${ownerTab === "settings" ? "active" : ""}`} onClick={() => setOwnerTab("settings")}>⚙️ الإعدادات</button>
          </div>

          {ownerTab === "staff" && (
            <div className="panel">
              <h3>الموظفين — نوع الموظف، منطقته، وصلاحياته</h3>
              <div className="no-access-inline">حدد لكل نادل/كاشير المنطقة المسؤول عنها بس (الأرضي أو الروف) — أو "كل المناطق" لو بدك يشوف الكل. الموظف ما رح يقدر يغيّرها من شاشته.</div>
              {staff.map((s) => (
                <div className="staff-card" key={s.id}>
                  <div className="staff-top">
                    <span className="staff-name">{s.name}</span>
                    <select className="staff-type-select" value={s.type} onChange={(e) => setStaffType(s.id, e.target.value)}>
                      <option value="نادل">نادل</option>
                      <option value="كاشير">كاشير</option>
                    </select>
                    <select className="staff-type-select" value={s.assignedZone || "all"} onChange={(e) => setStaffZone(s.id, e.target.value)}>
                      <option value="all">🌐 كل المناطق</option>
                      {zones.map((z) => (
                        <option key={z.id} value={z.id}>🪑 {z.name} بس</option>
                      ))}
                    </select>
                    <button className="staff-remove" onClick={() => removeStaff(s.id)}>حذف الموظف ✕</button>
                  </div>
                  <div className="cred-row">
                    <div className="cred-field">
                      <label>اسم المستخدم</label>
                      <input value={s.username || ""} onChange={(e) => updateStaffCredential(s.id, "username", e.target.value)} />
                    </div>
                    <div className="cred-field">
                      <label>كلمة السر</label>
                      <input value={s.password || ""} onChange={(e) => updateStaffCredential(s.id, "password", e.target.value)} />
                    </div>
                  </div>
                  <div className="perm-grid">
                    {PERM_LIST.map((p) => (
                      <label className="perm-toggle" key={p.id}>
                        <input type="checkbox" checked={!!s.permissions[p.id]} onChange={() => toggleStaffPerm(s.id, p.id)} />
                        {p.label}
                      </label>
                    ))}
                  </div>
                </div>
              ))}
              <h3 style={{ marginTop: 18 }}>إضافة موظف جديد</h3>
              <div className="no-access-inline">أعطي الموظف اسم المستخدم وكلمة السر هاي عشان يسجل دخول من جهازه</div>
              <div className="add-staff-row">
                <input placeholder="اسم الموظف" value={newStaffName} onChange={(e) => setNewStaffName(e.target.value)} />
                <select value={newStaffType} onChange={(e) => setNewStaffType(e.target.value)}>
                  <option value="نادل">نادل</option>
                  <option value="كاشير">كاشير</option>
                </select>
                <select value={newStaffAssignedZone} onChange={(e) => setNewStaffAssignedZone(e.target.value)}>
                  <option value="all">🌐 كل المناطق</option>
                  {zones.map((z) => (
                    <option key={z.id} value={z.id}>🪑 {z.name} بس</option>
                  ))}
                </select>
                <input placeholder="اسم المستخدم" value={newStaffUsername} onChange={(e) => setNewStaffUsername(e.target.value)} />
                <input placeholder="كلمة السر" value={newStaffPassword} onChange={(e) => setNewStaffPassword(e.target.value)} />
                <button onClick={addStaff}>+ إضافة</button>
              </div>
            </div>
          )}

          {ownerTab === "menu" && (
            <OwnerMenuManager menu={menu} menuEditItem={menuEditItem} setMenuEditItem={setMenuEditItem} saveMenuItem={saveMenuItem} deleteMenuItem={deleteMenuItem} applyGroupsToCategory={applyGroupsToCategory} />
          )}

          {ownerTab === "inventory" && (
            <InventoryPanel menu={menu} lowStockItems={lowStockItems} restockAmount={restockAmount} setRestockAmount={setRestockAmount} restock={restock} />
          )}

          {ownerTab === "zones" && (
            <div className="panel">
              <h3>المناطق والطاولات</h3>
              <div className="no-access-inline">مثال: "الطابق الأرضي" و"الروف" منطقتين منفصلتين، كل وحدة إلها طاولاتها الخاصة وطلباتها المفتوحة منفصلة عن التانية.</div>
              {zones.map((z) => (
                <div className="staff-card" key={z.id}>
                  <div className="staff-top">
                    <span className="staff-name">🪑 {z.name}</span>
                    <button className="staff-remove" onClick={() => removeZone(z.id)}>حذف المنطقة ✕</button>
                  </div>
                  <div className="row-wrap" style={{ marginTop: 10 }}>
                    {z.tables.map((t) => (
                      <span key={t} className="table-chip">
                        طاولة {t}
                        <button onClick={() => removeTableFromZone(z.id, t)}>✕</button>
                      </span>
                    ))}
                    {z.tables.length === 0 && <span style={{ fontSize: 12, color: "var(--muted)" }}>ما في طاولات بهاي المنطقة بعد</span>}
                  </div>
                  <div className="restock-row" style={{ marginTop: 10 }}>
                    <input
                      placeholder="اسم/رقم الطاولة الجديدة"
                      value={newTableLabel[z.id] || ""}
                      onChange={(e) => setNewTableLabel((prev) => ({ ...prev, [z.id]: e.target.value }))}
                      style={{ width: 160 }}
                    />
                    <button className="icon-btn" onClick={() => addTableToZone(z.id)}>+ إضافة طاولة</button>
                  </div>
                </div>
              ))}
              <h3 style={{ marginTop: 18 }}>إضافة منطقة جديدة</h3>
              <div className="add-staff-row">
                <input placeholder="اسم المنطقة (مثلاً: الروف)" value={newZoneName} onChange={(e) => setNewZoneName(e.target.value)} />
                <button onClick={addZone}>+ إضافة منطقة</button>
              </div>
            </div>
          )}

          {ownerTab === "live" && (() => {
            const now2 = Date.now();
            const liveSessions = Object.values(activeSessions).filter((s) => now2 - s.lastSeen < 25000);
            const liveWaiters = liveSessions.filter((s) => s.role === "نادل");
            const liveCashiers = liveSessions.filter((s) => s.role === "كاشير");
            const openOrders = orders.filter((o) => o.status === "pending" || o.status === "held");
            const openValue = openOrders.reduce((s, o) => s + o.total, 0);
            return (
              <div>
                <div className="kpi-grid">
                  <div className="kpi-card">
                    <div className="kpi-label">نادلين شغالين هلق</div>
                    <div className="kpi-value">{liveWaiters.length}</div>
                  </div>
                  <div className="kpi-card">
                    <div className="kpi-label">كاشيرية شغالين هلق</div>
                    <div className="kpi-value">{liveCashiers.length}</div>
                  </div>
                  <div className="kpi-card">
                    <div className="kpi-label">طاولات مفتوحة الآن</div>
                    <div className="kpi-value">{openOrders.filter((o) => o.orderType === "dine-in").length}</div>
                  </div>
                  <div className="kpi-card">
                    <div className="kpi-label">قيمة الطلبات المفتوحة</div>
                    <div className="kpi-value">{money(openValue)}</div>
                  </div>
                </div>

                <div className="grid-2">
                  <div className="panel">
                    <h3>👥 مين شغال هلق (كل الأجهزة)</h3>
                    {liveSessions.length === 0 && <div className="empty-msg">ما في حدا مسجل دخول هلق</div>}
                    {liveWaiters.map((s, i) => (
                      <div key={"w" + i} className="menu-manage-card">
                        <div className="menu-manage-info">
                          <div className="name">🧾 {s.staffName} <span className="badge role">نادل</span></div>
                          <div className="meta">منطقته: {s.zoneName || "—"}</div>
                        </div>
                        <span className="print-badge printed">🟢 متصل</span>
                      </div>
                    ))}
                    {liveCashiers.map((s, i) => (
                      <div key={"c" + i} className="menu-manage-card">
                        <div className="menu-manage-info">
                          <div className="name">💰 {s.staffName} <span className="badge role">كاشير</span></div>
                          <div className="meta">منطقته: {s.zoneName || "—"}</div>
                        </div>
                        <span className="print-badge printed">🟢 متصل</span>
                      </div>
                    ))}
                  </div>

                  <div className="panel">
                    <h3>🪑 الطاولات المفتوحة حسب المنطقة</h3>
                    {zones.map((z) => {
                      const zoneOpen = openOrders.filter((o) => o.zoneId === z.id);
                      const zoneValue = zoneOpen.reduce((s, o) => s + o.total, 0);
                      return (
                        <div key={z.id} style={{ marginBottom: 14 }}>
                          <div className="tally-head" style={{ marginBottom: 6 }}>
                            <span>🪑 {z.name} — {zoneOpen.length} طاولة مفتوحة</span>
                            <span className="mono">{money(zoneValue)}</span>
                          </div>
                          {zoneOpen.length === 0 && <div style={{ fontSize: 12, color: "var(--muted)" }}>ما في طاولات مفتوحة هون</div>}
                          {zoneOpen.map((o) => (
                            <div key={o.id} className="receipt-line" style={{ background: "var(--surface-2)", borderRadius: 8, padding: "7px 10px", border: "none", marginBottom: 4 }}>
                              <span>طاولة {o.table} · {(o.waiters || [o.staffName]).join("، ")}</span>
                              <span className="mono">{money(o.total)}</span>
                            </div>
                          ))}
                        </div>
                      );
                    })}
                    {(() => {
                      const takeawayOpen = openOrders.filter((o) => o.orderType === "takeaway");
                      if (takeawayOpen.length === 0) return null;
                      return (
                        <div>
                          <div className="tally-head" style={{ marginBottom: 6 }}>
                            <span>🥡 Take Away — {takeawayOpen.length} طلب</span>
                            <span className="mono">{money(takeawayOpen.reduce((s, o) => s + o.total, 0))}</span>
                          </div>
                          {takeawayOpen.map((o) => (
                            <div key={o.id} className="receipt-line" style={{ background: "var(--surface-2)", borderRadius: 8, padding: "7px 10px", border: "none", marginBottom: 4 }}>
                              <span>#{o.id} · {(o.waiters || [o.staffName]).join("، ")}</span>
                              <span className="mono">{money(o.total)}</span>
                            </div>
                          ))}
                        </div>
                      );
                    })()}
                  </div>
                </div>
              </div>
            );
          })()}

          {ownerTab === "printers" && (
            <PrintersPanel printers={printers} addPrinter={addPrinter} updatePrinter={updatePrinter} removePrinter={removePrinter} zones={zones} />
          )}

          {ownerTab === "expenses" && (
            <ExpensesPanel expenses={expenses} addExpense={addExpense} removeExpense={removeExpense} period={expensesPeriod} setPeriod={setExpensesPeriod} customRange={expensesCustomRange} setCustomRange={setExpensesCustomRange} />
          )}

          {ownerTab === "closings" && <ClosingsPanel cashClosings={cashClosings} />}

          {ownerTab === "reports" && (
            <ReportsPanel reports={reports} pendingCount={pendingOrders.length} orders={orders} now={now} period={reportsPeriod} setPeriod={setReportsPeriod} customRange={reportsCustomRange} setCustomRange={setReportsCustomRange} />
          )}

          {ownerTab === "settings" && (
            <div className="panel">
              <h3>إعدادات عامة</h3>
              <div className="settings-row">
                <span>نسبة الضريبة VAT %</span>
                <input type="number" min="0" max="100" value={vatPct} onChange={(e) => setVatPct(Number(e.target.value))} />
              </div>
              <div style={{ fontSize: 12, color: "var(--muted)" }}>بتنطبق هاي النسبة تلقائياً على كل الفواتير الجديدة (Net + Vat = Total).</div>

              <h3 style={{ marginTop: 22 }}>🔐 بيانات دخول صاحب الكافيه</h3>
              <div className="no-access-inline">هاي بيانات الدخول الخاصة فيك لهاي الشاشة — لا تشاركها مع الموظفين.</div>
              <div className="cred-row">
                <div className="cred-field">
                  <label>الإيميل</label>
                  <input value={ownerEmail} onChange={(e) => setOwnerEmail(e.target.value)} />
                </div>
                <div className="cred-field">
                  <label>كلمة السر</label>
                  <input value={ownerPassword} onChange={(e) => setOwnerPassword(e.target.value)} />
                </div>
              </div>
            </div>
          )}
          </>
          )}
        </div>
      )}

      {/* ---------------- WAITER ---------------- */}
      {view === "waiter" && (
        <div>
          {!waiterStaff || !["نادل"].includes(waiterStaff.type) ? (
            <LoginPanel
              title="تسجيل دخول النادل"
              hint="استخدم اسم المستخدم وكلمة السر يلي أعطاك ياها صاحب الكافيه"
              username={loginUsername}
              setUsername={setLoginUsername}
              password={loginPassword}
              setPassword={setLoginPassword}
              error={loginError}
              onSubmit={() => attemptLogin(["نادل"], setWaiterStaffId)}
            />
          ) : (
          <>
          <div className="panel" style={{ marginBottom: 14, display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 8 }}>
            <span>مسجل دخول: <strong>{waiterStaff.name}</strong> <span className="badge role">{waiterStaff.type}</span></span>
            <button className="reset-btn" onClick={logoutWaiter}>🚪 تسجيل خروج</button>
          </div>

          <div className="action-bar">
            <button className="action-btn start" onClick={startOverDraft}>↺ Start Over</button>
            <button className="action-btn" onClick={preBillDraft}>🧾 Pre-Bill</button>
            <button className="action-btn warn" onClick={voidAllDraft}>🗑 Void All</button>
            <button className="action-btn neutral" onClick={startOverDraft}>⏏ Exit</button>
          </div>

          <div className="panel" style={{ marginBottom: 14 }}>
            <div className="row-wrap">
              <button className={`pill-btn ${orderType === "dine-in" ? "selected" : ""}`} onClick={() => setOrderType("dine-in")}>🍽 Dine-in</button>
              <button className={`pill-btn ${orderType === "takeaway" ? "selected" : ""}`} onClick={() => { setOrderType("takeaway"); setSelectedTable(null); }}>🥡 Take Away</button>
            </div>
            {orderType === "dine-in" && (
              <>
                {waiterStaff && waiterStaff.assignedZone && waiterStaff.assignedZone !== "all" ? (
                  <div className="zone-lock-badge">🪑 منطقتك: {zones.find((z) => z.id === waiterStaff.assignedZone)?.name || "—"}</div>
                ) : (
                  <div className="row-wrap" style={{ marginTop: 12 }}>
                    {zones.map((z) => (
                      <button key={z.id} className={`pill-btn ${selectedZone === z.id ? "selected" : ""}`} onClick={() => { setSelectedZone(z.id); setSelectedTable(null); }}>
                        🪑 {z.name}
                      </button>
                    ))}
                  </div>
                )}
                <div className="table-grid" style={{ marginTop: 12 }}>
                  {(zones.find((z) => z.id === selectedZone)?.tables || []).map((t) => {
                    const occupied = getOpenOrderForTable(selectedZone, t);
                    return (
                      <button
                        key={t}
                        className={`table-btn ${selectedTable === t ? "selected" : ""} ${occupied && selectedTable !== t ? "occupied" : ""}`}
                        onClick={() => setSelectedTable(t)}
                      >
                        {t}
                        {occupied && <span className="table-total">{money(occupied.total)}</span>}
                      </button>
                    );
                  })}
                  {(zones.find((z) => z.id === selectedZone)?.tables || []).length === 0 && (
                    <div style={{ fontSize: 12.5, color: "var(--muted)" }}>ما في طاولات بهاي المنطقة، ضيفها من شاشة صاحب الكافيه</div>
                  )}
                </div>
                <div className="row-wrap" style={{ marginTop: 10, fontSize: 11 }}>
                  <span className="legend-dot free" /> فاضية
                  <span className="legend-dot occ" /> فيها طلب مفتوح
                </div>
              </>
            )}
          </div>

          <div className="grid-layout">
            <div className="panel cat-rail">
              {menu.map((c) => {
                const style = CATEGORY_STYLE[c.catId] || { icon: "🍽", grad: "linear-gradient(135deg,#555,#222)" };
                return (
                  <button key={c.catId} className={`cat-tile ${activeCategory === c.catId ? "active" : ""}`} style={{ background: style.grad }} onClick={() => setActiveCategory(c.catId)}>
                    <span className="icon-box">{style.icon}</span>
                    {c.catName}
                  </button>
                );
              })}
            </div>

            <div className="panel">
              <div className="item-grid">
                {(menu.find((c) => c.catId === activeCategory)?.items || []).map((item) => {
                  const style = CATEGORY_STYLE[activeCategory] || { grad: "linear-gradient(135deg,#555,#222)" };
                  const inCartQty = qtyInCartForId(item.id);
                  const isOut = item.stock - inCartQty <= 0;
                  return (
                    <div key={item.id} className={`item-tile ${isOut ? "out" : ""}`} style={{ background: style.grad }} onClick={() => !isOut && addToCart({ ...item, catId: activeCategory })}>
                      <span className="icon-big">{item.icon}</span>
                      <div className="name">{item.name}</div>
                      <div className="price">{money(item.price)}</div>
                      {item.stock <= LOW_STOCK_THRESHOLD && (
                        <span className="stock-tag">{isOut ? "خلص" : `متبقي ${item.stock - inCartQty}`}</span>
                      )}
                    </div>
                  );
                })}
              </div>
            </div>

            <div>
              {orderType === "dine-in" && selectedTable && getOpenOrderForTable(selectedZone, selectedTable) && (
                <div className="reorder-banner">
                  🔔 طاولة {selectedTable} عندها طلب مفتوح #{getOpenOrderForTable(selectedZone, selectedTable).id} بقيمة {money(getOpenOrderForTable(selectedZone, selectedTable).total)} — أي صنف تضيفه هلق رح ينضاف عليه.
                </div>
              )}
              {orderType === "dine-in" && selectedTable && getOpenOrderForTable(selectedZone, selectedTable) && (hasPermission(waiterStaff, "addToOpenOrder") || hasPermission(waiterStaff, "removeFromOpenOrder")) && (
                <div className="receipt" style={{ marginBottom: 12 }}>
                  <div className="receipt-title">تعديل الأصناف المرسلة سابقاً</div>
                  {getOpenOrderForTable(selectedZone, selectedTable).items.map((i) => (
                    <div className="receipt-line" key={i.cartKey}>
                      <span>
                        {i.name}
                        {i.modsLabel && <span className="mod-label">({i.modsLabel})</span>}
                      </span>
                      <div className="qty-ctrl">
                        {hasPermission(waiterStaff, "removeFromOpenOrder") && (
                          <button className="qty-btn" onClick={() => editExistingOrderItemQty(getOpenOrderForTable(selectedZone, selectedTable), i.cartKey, -1, waiterStaff.name)}>−</button>
                        )}
                        <span className="mono">{i.qty}</span>
                        {hasPermission(waiterStaff, "addToOpenOrder") && (
                          <button className="qty-btn" onClick={() => editExistingOrderItemQty(getOpenOrderForTable(selectedZone, selectedTable), i.cartKey, 1, waiterStaff.name)}>+</button>
                        )}
                        {hasPermission(waiterStaff, "removeFromOpenOrder") && (
                          <button className="icon-btn danger" onClick={() => removeExistingOrderItem(getOpenOrderForTable(selectedZone, selectedTable), i.cartKey, waiterStaff.name)}>حذف</button>
                        )}
                      </div>
                    </div>
                  ))}
                  {getOpenOrderForTable(selectedZone, selectedTable).items.length === 0 && (
                    <div className="receipt-empty">ما بقي أصناف بهاي الفاتورة</div>
                  )}
                </div>
              )}
              <div className="receipt">
                <div className="receipt-title">
                  {orderType === "dine-in" && selectedTable && getOpenOrderForTable(selectedZone, selectedTable)
                    ? `إضافة لطلب #${getOpenOrderForTable(selectedZone, selectedTable).id} · طاولة ${selectedTable}`
                    : `طلب #${orderCounter} · ${orderType === "dine-in" ? (selectedTable ? `طاولة ${selectedTable}` : "— اختر طاولة —") : "Take Away"}`}
                </div>
                {cart.length === 0 && <div className="receipt-empty">لسا ما ضفت أصناف للطلب</div>}
                {cart.map((i) => (
                  <div className="receipt-line" key={i.cartKey}>
                    <span>
                      {i.name}
                      {i.modsLabel && <span className="mod-label">({i.modsLabel})</span>}
                    </span>
                    <div className="qty-ctrl">
                      <button className="qty-btn" onClick={() => changeQty(i.cartKey, -1)}>−</button>
                      <span className="mono">{i.qty}</span>
                      <button className="qty-btn" onClick={() => changeQty(i.cartKey, 1)}>+</button>
                      <span className="mono">{money(i.price * i.qty)}</span>
                    </div>
                  </div>
                ))}
                {cart.length > 0 && (
                  <>
                    <div className="receipt-sub"><span>المجموع الفرعي</span><span className="mono">{money(totals.subtotal)}</span></div>
                    {hasPermission(waiterStaff, "applyDiscount") && (
                      <div className="discount-row">
                        <span>نسبة الخصم %</span>
                        <input type="number" min="0" max="100" value={discountPct} onChange={(e) => setDiscountPct(Math.min(100, Math.max(0, Number(e.target.value))))} />
                      </div>
                    )}
                    <div className="receipt-sub"><span>Net</span><span className="mono">{money(totals.net)}</span></div>
                    <div className="receipt-sub"><span>Vat ({vatPct}%)</span><span className="mono">{money(totals.vatAmount)}</span></div>
                    <div className="receipt-total"><span>Total</span><span>{money(totals.total)}</span></div>
                    <textarea className="note-input" rows={2} placeholder="ملاحظات على الطلب (اختياري)…" value={note} onChange={(e) => setNote(e.target.value)} />
                  </>
                )}
                <div className="receipt-zigzag" />
              </div>
              <button className="submit-btn" disabled={(orderType === "dine-in" && !selectedTable) || cart.length === 0} onClick={submitOrder}>
                {orderType === "dine-in" && selectedTable && getOpenOrderForTable(selectedZone, selectedTable) ? "➕ إضافة للطلب الحالي" : "إرسال الطلب للكاشير"}
              </button>
            </div>
          </div>
          </>
          )}
        </div>
      )}

      {/* ---------------- CASHIER ---------------- */}
      {view === "cashier" && (
        <div>
          {!cashierStaff || !["كاشير"].includes(cashierStaff.type) ? (
            <LoginPanel
              title="تسجيل دخول الكاشير"
              hint="استخدم اسم المستخدم وكلمة السر يلي أعطاك ياها صاحب الكافيه"
              username={loginUsername}
              setUsername={setLoginUsername}
              password={loginPassword}
              setPassword={setLoginPassword}
              error={loginError}
              onSubmit={() => attemptLogin(["كاشير"], setCashierStaffId)}
            />
          ) : (
          <>
          <div className="panel" style={{ marginBottom: 14, display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 8 }}>
            <span>مسجل دخول: <strong>{cashierStaff.name}</strong> <span className="badge role">{cashierStaff.type}</span></span>
            <div style={{ display: "flex", gap: 8 }}>
              <button className="reset-btn" style={{ color: "var(--warning-ink)", borderColor: "var(--warning)" }} onClick={() => setShowClosingModal(true)}>🔒 إغلاق الشفت اليومي</button>
              <button className="reset-btn" onClick={logoutCashier}>🚪 تسجيل خروج</button>
            </div>
          </div>

          <div className="subtab-row">
            <button className={`subtab-btn ${cashierSubTab === "active" ? "active" : ""}`} onClick={() => setCashierSubTab("active")}>الطلبات النشطة</button>
            <button className={`subtab-btn ${cashierSubTab === "all" ? "active" : ""}`} onClick={() => setCashierSubTab("all")}>كل الطلبات</button>
          </div>

          {cashierSubTab === "active" && (
            <div className="grid-2">
              <div className="panel">
                <h3>الطلبات المعلقة ({pendingOrders.length})</h3>
                {cashierStaff && cashierStaff.assignedZone && cashierStaff.assignedZone !== "all" ? (
                  <div className="zone-lock-badge">🪑 منطقتك: {zones.find((z) => z.id === cashierStaff.assignedZone)?.name || "—"} (+ Take Away)</div>
                ) : (
                  <div className="subtab-row" style={{ flexWrap: "wrap" }}>
                    <button className={`subtab-btn ${cashierZoneFilter === "all" ? "active" : ""}`} onClick={() => setCashierZoneFilter("all")}>
                      الكل ({pendingOrders.length})
                    </button>
                    {zones.map((z) => {
                      const count = pendingOrders.filter((o) => o.zoneId === z.id).length;
                      return (
                        <button key={z.id} className={`subtab-btn ${cashierZoneFilter === z.id ? "active" : ""}`} onClick={() => setCashierZoneFilter(z.id)}>
                          🪑 {z.name} ({count})
                        </button>
                      );
                    })}
                    <button className={`subtab-btn ${cashierZoneFilter === "takeaway" ? "active" : ""}`} onClick={() => setCashierZoneFilter("takeaway")}>
                      🥡 Take Away ({pendingOrders.filter((o) => o.orderType === "takeaway").length})
                    </button>
                  </div>
                )}
                {heldOrders.length > 0 && (
                  <div className="low-stock-banner" style={{ background: "var(--warning)", color: "var(--ink)" }}>
                    ⏸ في {heldOrders.length} فاتورة محتجزة — تقدر تعيد فتحها من تبويب "كل الطلبات"
                  </div>
                )}
                <div className="tickets-rail">
                  {(() => {
                    const lockedZone = cashierStaff && cashierStaff.assignedZone && cashierStaff.assignedZone !== "all" ? cashierStaff.assignedZone : null;
                    const filteredPending = pendingOrders.filter((o) => {
                      if (lockedZone) return o.zoneId === lockedZone || o.orderType === "takeaway";
                      if (cashierZoneFilter === "all") return true;
                      if (cashierZoneFilter === "takeaway") return o.orderType === "takeaway";
                      return o.zoneId === cashierZoneFilter;
                    });
                    if (filteredPending.length === 0) return <div className="empty-msg">ما في طلبات هون حالياً 🎉</div>;
                    return filteredPending.map((o) => (
                    <div key={o.id} className={`ticket-card ${selectedOrderId === o.id ? "active" : ""}`} onClick={() => setSelectedOrderId(o.id)}>
                      <div className="ticket-top">
                        <div>
                          <div className="ticket-num">#{o.id}</div>
                          <div className="ticket-table">{orderLabel(o)}</div>
                        </div>
                        <div style={{ textAlign: "left" }}>
                          <div className="ticket-total">{money(o.total)}</div>
                        </div>
                      </div>
                      <div className="ticket-meta">
                        <span>👤 {(o.waiters || [o.staffName]).join("، ")}</span> · <span>{timeAgo(o.createdAt, now)}</span> · <span>{o.items.length} صنف</span>
                        <span className={`print-badge ${o.printed ? "printed" : "not-printed"}`}>{o.printed ? "Printed" : "Not Printed"}</span>
                        {o.items.some((i) => i.station === "bar") && (
                          <span className={`print-badge ${o.barPrinted ? "printed" : "not-printed"}`}>☕ {o.barPrinted ? "أُرسل" : "بانتظار الباريستا"}</span>
                        )}
                        {o.items.some((i) => i.station === "kitchen") && (
                          <span className={`print-badge ${o.kitchenPrinted ? "printed" : "not-printed"}`}>🍽️ {o.kitchenPrinted ? "أُرسل" : "بانتظار المطبخ"}</span>
                        )}
                        {o.items.some((i) => i.station === "hookah") && (
                          <span className={`print-badge ${o.hookahPrinted ? "printed" : "not-printed"}`}>💨 {o.hookahPrinted ? "أُرسل" : "بانتظار الأراجيل"}</span>
                        )}
                      </div>
                      <div className="ticket-zigzag" />
                    </div>
                    ));
                  })()}
                </div>
              </div>

              <div className="panel">
                <h3>تفاصيل الطلب</h3>
                {!selectedOrder && <div className="empty-msg">اختر طلب من القائمة لعرض التفاصيل وتحصيل الدفع</div>}
                {selectedOrder && (
                  <>
                    <div className="action-bar">
                      <button className="action-btn" onClick={() => preBillOrder(selectedOrder)}>🧾 Pre-Bill</button>
                      <button className="action-btn" style={{ background: "var(--primary-soft)", color: "var(--primary-dark)" }} onClick={() => printReceipt(selectedOrder)}>🖨 طباعة الفاتورة</button>
                      {selectedOrder.items.some((i) => i.station === "bar") && (
                        <button
                          className="action-btn"
                          style={{ background: selectedOrder.barPrinted ? "var(--success-soft)" : "var(--warning-soft)", color: selectedOrder.barPrinted ? "var(--success)" : "var(--warning-ink)" }}
                          onClick={() => printStationTicket(selectedOrder, "bar")}
                        >
                          ☕ تذكرة الباريستا {selectedOrder.barPrinted ? "✓" : ""}
                        </button>
                      )}
                      {selectedOrder.items.some((i) => i.station === "kitchen") && (
                        <button
                          className="action-btn"
                          style={{ background: selectedOrder.kitchenPrinted ? "var(--success-soft)" : "var(--warning-soft)", color: selectedOrder.kitchenPrinted ? "var(--success)" : "var(--warning-ink)" }}
                          onClick={() => printStationTicket(selectedOrder, "kitchen")}
                        >
                          🍽️ تذكرة المطبخ {selectedOrder.kitchenPrinted ? "✓" : ""}
                        </button>
                      )}
                      {selectedOrder.items.some((i) => i.station === "hookah") && (
                        <button
                          className="action-btn"
                          style={{ background: selectedOrder.hookahPrinted ? "var(--success-soft)" : "var(--warning-soft)", color: selectedOrder.hookahPrinted ? "var(--success)" : "var(--warning-ink)" }}
                          onClick={() => printStationTicket(selectedOrder, "hookah")}
                        >
                          💨 تذكرة الأراجيل {selectedOrder.hookahPrinted ? "✓" : ""}
                        </button>
                      )}
                      <button className="action-btn neutral" onClick={openDrawer}>🔓 Open Drawer</button>
                      {selectedOrder.status === "pending" && (
                        <button className="action-btn" style={{ background: "var(--warning)", color: "var(--ink)" }} onClick={() => holdOrder(selectedOrder.id)}>⏸ Close Bill</button>
                      )}
                      {hasPermission(cashierStaff, "deleteOrder") && (
                        <button className="action-btn warn" onClick={() => deleteOrder(selectedOrder.id)}>🗑 Void All</button>
                      )}
                      <button className="action-btn neutral" onClick={() => setSelectedOrderId(null)}>⏏ Exit</button>
                    </div>
                    <div className="receipt" style={{ position: "relative" }}>
                      {selectedOrder.status === "paid" && <div className="stamp">مدفوع ✓</div>}
                      <div className="receipt-title">طلب #{selectedOrder.id} · {orderLabel(selectedOrder)}</div>
                      {selectedOrder.items.map((i) => (
                        <div className="detail-item-line" key={i.cartKey || i.id}>
                          <span>{i.name}{i.modsLabel && <span className="mod-label">({i.modsLabel})</span>}</span>
                          {selectedOrder.status === "pending" && (hasPermission(cashierStaff, "addToOpenOrder") || hasPermission(cashierStaff, "removeFromOpenOrder")) ? (
                            <div className="qty-ctrl">
                              {hasPermission(cashierStaff, "removeFromOpenOrder") && (
                                <button className="qty-btn" onClick={() => editExistingOrderItemQty(selectedOrder, i.cartKey, -1, cashierStaff.name)}>−</button>
                              )}
                              <span className="mono">{i.qty}</span>
                              {hasPermission(cashierStaff, "addToOpenOrder") && (
                                <button className="qty-btn" onClick={() => editExistingOrderItemQty(selectedOrder, i.cartKey, 1, cashierStaff.name)}>+</button>
                              )}
                              <span className="mono">{money(i.price * i.qty)}</span>
                              {hasPermission(cashierStaff, "removeFromOpenOrder") && (
                                <button className="icon-btn danger" onClick={() => removeExistingOrderItem(selectedOrder, i.cartKey, cashierStaff.name)}>حذف</button>
                              )}
                            </div>
                          ) : (
                            <span>× {i.qty}</span>
                          )}
                        </div>
                      ))}
                      {selectedOrder.status === "pending" && hasPermission(cashierStaff, "addToOpenOrder") && (
                        <button className="icon-btn" style={{ marginTop: 8 }} onClick={() => { setCashierAddItemOrderId(selectedOrder.id); setCashierPickerCategory(menu[0]?.catId); }}>+ إضافة صنف للطلب</button>
                      )}
                      {selectedOrder.note && <div style={{ fontSize: 12, marginTop: 8, color: "var(--muted)" }}>ملاحظة: {selectedOrder.note}</div>}
                      {selectedOrder.discountPct > 0 && (
                        <div className="receipt-sub"><span>خصم {selectedOrder.discountPct}%</span><span className="mono">- {money(selectedOrder.subtotal - selectedOrder.net)}</span></div>
                      )}
                      <div className="receipt-sub"><span>Net</span><span className="mono">{money(selectedOrder.net)}</span></div>
                      <div className="receipt-sub"><span>Vat ({selectedOrder.vatPct}%)</span><span className="mono">{money(selectedOrder.vatAmount)}</span></div>
                      <div className="receipt-total"><span>Total</span><span>{money(selectedOrder.total)}</span></div>
                      {selectedOrder.status === "pending" ? (
                        <div className="pay-buttons">
                          <button className="pay-btn pay-cash" onClick={() => markPaid(selectedOrder.id, "نقدي")}>💵 دفع نقدي</button>
                          <button className="pay-btn pay-card" onClick={() => markPaid(selectedOrder.id, "بطاقة")}>💳 دفع بطاقة</button>
                          <button className="pay-btn pay-click" onClick={() => markPaid(selectedOrder.id, "كليك")}>📲 دفع كليك</button>
                          <button
                            className="pay-btn pay-split"
                            onClick={() => {
                              setSplitOrderId(selectedOrder.id);
                              setSplitCash(selectedOrder.total.toFixed(2));
                              setSplitCard("0.00");
                            }}
                          >
                            🔀 دفع مقسّم
                          </button>
                        </div>
                      ) : (
                        <div style={{ marginTop: 12, fontSize: 12.5, color: "var(--muted)" }}>
                          تم الدفع {selectedOrder.paymentMethod === "مقسّم" ? `(نقدي ${money(selectedOrder.cashAmount)} + بطاقة ${money(selectedOrder.cardAmount)})` : selectedOrder.paymentMethod} — {timeAgo(selectedOrder.paidAt, now)}
                        </div>
                      )}
                      <div className="receipt-zigzag" />
                    </div>
                  </>
                )}

                {paidOrders.length > 0 && !selectedOrder && (
                  <>
                    <h3 style={{ marginTop: 20 }}>آخر عمليات الدفع</h3>
                    <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                      {paidOrders.slice(0, 4).map((o) => (
                        <div key={o.id} className="receipt-line" style={{ background: "var(--ink)", borderRadius: 8, padding: "8px 10px", border: "none" }}>
                          <span>#{o.id} · {orderLabel(o)} · {o.staffName}</span>
                          <span className="mono">{money(o.total)}</span>
                        </div>
                      ))}
                    </div>
                  </>
                )}
              </div>
            </div>
          )}

          {cashierSubTab === "all" && (
            <div className="panel">
              <div className="subtab-row">
                <button className={`subtab-btn ${allOrdersFilter === "all" ? "active" : ""}`} onClick={() => setAllOrdersFilter("all")}>الكل</button>
                <button className={`subtab-btn ${allOrdersFilter === "dine-in" ? "active" : ""}`} onClick={() => setAllOrdersFilter("dine-in")}>🍽 Dine-in</button>
                <button className={`subtab-btn ${allOrdersFilter === "takeaway" ? "active" : ""}`} onClick={() => setAllOrdersFilter("takeaway")}>🥡 Take Away</button>
              </div>
              <div style={{ maxHeight: 420, overflowY: "auto" }}>
                <table className="log">
                  <thead>
                    <tr>
                      <th>رقم</th><th>النوع</th><th>الموظف</th><th>الوقت</th><th>الحالة</th><th>الطباعة</th><th>الإجمالي</th><th></th>
                    </tr>
                  </thead>
                  <tbody>
                    {filteredAllOrders.map((o) => (
                      <tr key={o.id}>
                        <td className="mono">#{o.id}</td>
                        <td>{orderLabel(o)}</td>
                        <td>{(o.waiters || [o.staffName]).join("، ")}</td>
                        <td>{timeAgo(o.createdAt, now)}</td>
                        <td><span className={`badge ${o.status}`}>{o.status === "paid" ? "مدفوع" : o.status === "held" ? "معلّقة" : "قيد الانتظار"}</span></td>
                        <td><span className={`print-badge ${o.printed ? "printed" : "not-printed"}`}>{o.printed ? "Printed" : "Not Printed"}</span></td>
                        <td className="mono">{money(o.total)}</td>
                        <td>{o.status === "held" && <button className="icon-btn" onClick={() => reopenOrder(o.id)}>إعادة فتح</button>}</td>
                      </tr>
                    ))}
                    {filteredAllOrders.length === 0 && (
                      <tr><td colSpan={8} style={{ textAlign: "center", padding: 20 }}>ما في طلبات مطابقة</td></tr>
                    )}
                  </tbody>
                </table>
              </div>
            </div>
          )}

          {hasPermission(cashierStaff, "editMenu") && (
            <div style={{ marginTop: 18 }}>
              <OwnerMenuManager menu={menu} menuEditItem={menuEditItem} setMenuEditItem={setMenuEditItem} saveMenuItem={saveMenuItem} deleteMenuItem={deleteMenuItem} applyGroupsToCategory={applyGroupsToCategory} titleOverride="إدارة القائمة (صلاحية ممنوحة لك)" />
            </div>
          )}
          {hasPermission(cashierStaff, "manageInventory") && (
            <div style={{ marginTop: 18 }}>
              <InventoryPanel menu={menu} lowStockItems={lowStockItems} restockAmount={restockAmount} setRestockAmount={setRestockAmount} restock={restock} titleOverride="المخزون (صلاحية ممنوحة لك)" />
            </div>
          )}
          {hasPermission(cashierStaff, "viewReports") && (
            <div style={{ marginTop: 18 }}>
              <ReportsPanel reports={reports} pendingCount={pendingOrders.length} orders={orders} now={now} period={reportsPeriod} setPeriod={setReportsPeriod} customRange={reportsCustomRange} setCustomRange={setReportsCustomRange} />
            </div>
          )}
          </>
          )}
        </div>
      )}

      {showClosingModal && cashierStaff && (() => {
        const range = getPeriodRange("daily");
        const myPaidToday = orders.filter((o) => o.status === "paid" && o.cashierName === cashierStaff.name && o.paidAt >= range.start && o.paidAt <= range.end);
        const expectedCash = myPaidToday.reduce((s, o) => s + (o.paymentMethod === "مقسّم" ? o.cashAmount || 0 : o.paymentMethod === "نقدي" ? o.total : 0), 0);
        const expectedCard = myPaidToday.reduce((s, o) => s + (o.paymentMethod === "مقسّم" ? o.cardAmount || 0 : o.paymentMethod === "بطاقة" ? o.total : 0), 0);
        const clickOrders = myPaidToday.filter((o) => o.paymentMethod === "كليك");
        const clickCount = clickOrders.length;
        const expectedClick = clickOrders.reduce((s, o) => s + o.total, 0);
        const actualCashNum = Number(actualCashInput) || 0;
        const actualCardNum = Number(actualCardInput) || 0;
        const actualClickNum = Number(actualClickInput) || 0;
        const cashVariance = actualCashNum - expectedCash;
        const cardVariance = actualCardNum - expectedCard;
        const canConfirm = actualCashInput !== "" && actualCardInput !== "" && (clickCount === 0 || actualClickInput !== "");
        return (
          <div className="modal-overlay" onClick={() => setShowClosingModal(false)}>
            <div className="modal-receipt" onClick={(e) => e.stopPropagation()}>
              <div className="modal-receipt-header">🔒 إغلاق شفت اليوم · {cashierStaff.name}</div>
              <div className="receipt-sub"><span>عدد الفواتير المحصّلة اليوم</span><span className="mono">{myPaidToday.length}</span></div>

              <div className="mod-group" style={{ marginTop: 14 }}>
                <div className="mod-group-title">💵 عد الكاش الفعلي بالدرج وحطه هون</div>
                <input className="login-input" type="number" step="0.01" value={actualCashInput} onChange={(e) => setActualCashInput(e.target.value)} placeholder="0.00" />
              </div>

              <div className="mod-group">
                <div className="mod-group-title">💳 المبلغ الفعلي عالبطاقة (من كشف/دفتر الجهاز)</div>
                <input className="login-input" type="number" step="0.01" value={actualCardInput} onChange={(e) => setActualCardInput(e.target.value)} placeholder="0.00" />
              </div>

              {clickCount > 0 && (
                <div className="mod-group">
                  <div className="mod-group-title">📲 المبلغ الفعلي لعمليات كليك ({clickCount} عملية — النظام حاسبه {money(expectedClick)})</div>
                  <input className="login-input" type="number" step="0.01" value={actualClickInput} onChange={(e) => setActualClickInput(e.target.value)} placeholder="0.00" />
                </div>
              )}

              {canConfirm && (
                <div className="receipt-total">
                  <span>المجموع الكلي (كاش + بطاقة + كليك)</span>
                  <span>{money(actualCashNum + actualCardNum + actualClickNum)}</span>
                </div>
              )}

              <button
                className="submit-btn"
                disabled={!canConfirm}
                onClick={() => {
                  const zoneName = cashierStaff.assignedZone && cashierStaff.assignedZone !== "all" ? zones.find((z) => z.id === cashierStaff.assignedZone)?.name : "كل المناطق";
                  closeCashierShift(cashierStaff.name, zoneName, expectedCash, expectedCard, actualCashInput, actualCardInput, clickCount, actualClickInput || 0);
                  setShowClosingModal(false);
                  setActualCashInput("");
                  setActualCardInput("");
                  setActualClickInput("");
                }}
              >
                ✅ تأكيد الإغلاق
              </button>
              <button className="modal-close-btn" onClick={() => setShowClosingModal(false)}>إلغاء</button>
            </div>
          </div>
        );
      })()}

      {splitOrderId && (() => {
        const splitOrder = orders.find((o) => o.id === splitOrderId);
        if (!splitOrder) return null;
        const cashNum = Number(splitCash) || 0;
        const cardNum = Number(splitCard) || 0;
        const sumMatches = Math.abs(cashNum + cardNum - splitOrder.total) < 0.01;
        return (
          <div className="modal-overlay" onClick={() => setSplitOrderId(null)}>
            <div className="modal-receipt" onClick={(e) => e.stopPropagation()}>
              <div className="modal-receipt-header">دفع مقسّم · طلب #{splitOrder.id}</div>
              <div className="receipt-total" style={{ marginBottom: 14 }}>
                <span>الإجمالي المطلوب</span>
                <span>{money(splitOrder.total)}</span>
              </div>
              <div className="mod-group">
                <div className="mod-group-title">💵 المبلغ نقدي</div>
                <input
                  className="login-input"
                  type="number"
                  step="0.01"
                  value={splitCash}
                  onChange={(e) => {
                    setSplitCash(e.target.value);
                    const remaining = Math.max(0, splitOrder.total - (Number(e.target.value) || 0));
                    setSplitCard(remaining.toFixed(2));
                  }}
                />
              </div>
              <div className="mod-group">
                <div className="mod-group-title">💳 المبلغ بطاقة</div>
                <input
                  className="login-input"
                  type="number"
                  step="0.01"
                  value={splitCard}
                  onChange={(e) => {
                    setSplitCard(e.target.value);
                    const remaining = Math.max(0, splitOrder.total - (Number(e.target.value) || 0));
                    setSplitCash(remaining.toFixed(2));
                  }}
                />
              </div>
              {!sumMatches && (
                <div className="login-error">مجموع النقدي والبطاقة لازم يساوي الإجمالي بالضبط ({money(splitOrder.total)})</div>
              )}
              <button
                className="submit-btn"
                disabled={!sumMatches}
                onClick={() => markPaidSplit(splitOrder.id, cashNum, cardNum)}
              >
                ✅ تأكيد الدفع المقسّم
              </button>
              <button className="modal-close-btn" onClick={() => setSplitOrderId(null)}>إلغاء</button>
            </div>
          </div>
        );
      })()}

      {cashierAddItemOrderId && (() => {
        const targetOrder = orders.find((o) => o.id === cashierAddItemOrderId);
        if (!targetOrder) return null;
        const activeCat = cashierPickerCategory || menu[0]?.catId;
        const catItems = menu.find((c) => c.catId === activeCat)?.items || [];
        return (
          <div className="modal-overlay" onClick={() => setCashierAddItemOrderId(null)}>
            <div className="modal-receipt" style={{ maxWidth: 480 }} onClick={(e) => e.stopPropagation()}>
              <div className="modal-receipt-header">+ إضافة صنف لطلب #{targetOrder.id}</div>
              <div className="category-tabs">
                {menu.map((c) => (
                  <button key={c.catId} className={`category-btn ${activeCat === c.catId ? "active" : ""}`} onClick={() => setCashierPickerCategory(c.catId)}>
                    {c.catName}
                  </button>
                ))}
              </div>
              <div className="item-grid">
                {catItems.map((item) => {
                  const style = CATEGORY_STYLE[activeCat] || { grad: "linear-gradient(135deg,#eee,#ddd)" };
                  const isOut = item.stock <= 0;
                  return (
                    <div
                      key={item.id}
                      className={`item-tile ${isOut ? "out" : ""}`}
                      style={{ background: style.grad }}
                      onClick={() => {
                        if (isOut) return;
                        const itemWithCat = { ...item, catId: activeCat };
                        if (item.modifierGroups && item.modifierGroups.length > 0) {
                          const defaults = {};
                          item.modifierGroups.forEach((g) => { defaults[g.id] = g.type === "multi" ? [] : g.options[0]; });
                          setModSelections(defaults);
                          setPendingModItem(itemWithCat);
                          setModTargetOrderId(targetOrder.id);
                        } else {
                          addNewItemToExistingOrder(targetOrder, itemWithCat, {}, "", cashierStaff?.name || "الكاشير");
                        }
                      }}
                    >
                      <span className="icon-big">{item.icon}</span>
                      <div className="name">{item.name}</div>
                      <div className="price">{money(item.price)}</div>
                      {isOut && <span className="stock-tag">خلص</span>}
                    </div>
                  );
                })}
              </div>
              <button className="modal-close-btn" style={{ marginTop: 14 }} onClick={() => setCashierAddItemOrderId(null)}>تم</button>
            </div>
          </div>
        );
      })()}

      {pendingModItem && (
        <div className="modal-overlay" onClick={() => setPendingModItem(null)}>
          <div className="modal-receipt" onClick={(e) => e.stopPropagation()}>
            <div className="modal-receipt-header" style={{ letterSpacing: 0, textTransform: "none", fontSize: 16 }}>
              {pendingModItem.icon} {pendingModItem.name}
            </div>
            {pendingModItem.modifierGroups.map((g) => (
              <div key={g.id} className="mod-group">
                <div className="mod-group-title">{g.name}{g.type === "multi" ? " (تقدر تختار أكثر من واحد)" : ""}</div>
                <div className="mod-options">
                  {g.options.map((opt) => {
                    const selected = g.type === "multi" ? (modSelections[g.id] || []).includes(opt) : modSelections[g.id] === opt;
                    return (
                      <button key={opt} className={`mod-chip ${selected ? "selected" : ""}`} onClick={() => toggleModOption(g, opt)}>
                        {opt}
                      </button>
                    );
                  })}
                </div>
              </div>
            ))}
            <button className="submit-btn" style={{ marginTop: 16 }} onClick={confirmModifierSelection}>➕ إضافة للطلب</button>
            <button className="modal-close-btn" onClick={() => setPendingModItem(null)}>إلغاء</button>
          </div>
        </div>
      )}

      {preBillData && (
        <div className="modal-overlay" onClick={() => setPreBillData(null)}>
          <div className="modal-receipt mono" onClick={(e) => e.stopPropagation()}>
            <div className="modal-receipt-header">فاتورة مبدئية · PRE-BILL<br />{preBillData.label}</div>
            {preBillData.items.map((i) => (
              <div className="detail-item-line" key={i.cartKey || i.id}><span>{i.name}{i.modsLabel && <span className="mod-label">({i.modsLabel})</span>} × {i.qty}</span><span>{money(i.price * i.qty)}</span></div>
            ))}
            <div className="receipt-sub"><span>Net</span><span>{money(preBillData.net)}</span></div>
            <div className="receipt-sub"><span>Vat</span><span>{money(preBillData.vatAmount)}</span></div>
            <div className="receipt-total"><span>Total</span><span>{money(preBillData.total)}</span></div>
            <button className="modal-close-btn" onClick={() => setPreBillData(null)}>إغلاق المعاينة</button>
          </div>
        </div>
      )}

      {printData && (
        <div id="print-area">
          <div className="print-title">{printData.stationTicket ? "دفتر القهوجي — تذكرة تحضير" : "دفتر القهوجي"}</div>
          <div className="print-line">طلب #{printData.orderId} — {printData.label}</div>
          <div className="print-line">{printData.date}</div>
          <div className="print-line">النادل/الكاشير: {printData.staffName}</div>
          <div className="print-sep" />
          {printData.items.map((i, idx) => (
            <div className="print-row" key={idx}>
              <span>{i.name}{i.modsLabel ? ` (${i.modsLabel})` : ""} × {i.qty}</span>
              {!printData.stationTicket && <span>{money(i.price * i.qty)}</span>}
            </div>
          ))}
          {!printData.stationTicket && (
            <>
              <div className="print-sep" />
              <div className="print-row"><span>Net</span><span>{money(printData.net)}</span></div>
              <div className="print-row"><span>Vat ({printData.vatPct}%)</span><span>{money(printData.vatAmount)}</span></div>
              <div className="print-row print-total"><span>Total</span><span>{money(printData.total)}</span></div>
              {printData.paymentMethod && (
                <div className="print-line">
                  طريقة الدفع: {printData.paymentMethod === "مقسّم" ? `نقدي ${money(printData.cashAmount)} + بطاقة ${money(printData.cardAmount)}` : printData.paymentMethod}
                </div>
              )}
            </>
          )}
          <div className="print-sep" />
          <div className="print-footer">{printData.stationTicket ? "" : "شكراً لزيارتكم ☕"}</div>
        </div>
      )}

      {toast && <div className="toast">{toast}</div>}
    </div>
  );
}

function LoginPanel({ title, hint, username, setUsername, password, setPassword, error, onSubmit }) {
  return (
    <div className="login-wrap">
      <div className="panel login-card">
        <div className="login-icon">🔐</div>
        <h3 style={{ textAlign: "center" }}>{title}</h3>
        <p className="login-hint">{hint}</p>
        <input
          className="login-input"
          placeholder="اسم المستخدم"
          value={username}
          onChange={(e) => setUsername(e.target.value)}
          onKeyDown={(e) => e.key === "Enter" && onSubmit()}
        />
        <input
          className="login-input"
          placeholder="كلمة السر"
          type="password"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          onKeyDown={(e) => e.key === "Enter" && onSubmit()}
        />
        {error && <div className="login-error">{error}</div>}
        <button className="submit-btn" onClick={onSubmit}>دخول</button>
      </div>
    </div>
  );
}

function InventoryPanel({ menu, lowStockItems, restockAmount, setRestockAmount, restock, titleOverride }) {
  return (
    <div className="panel">
      <h3>{titleOverride || "حالة المخزون"}</h3>
      {lowStockItems.length > 0 && (
        <div className="low-stock-banner">⚠️ في {lowStockItems.length} صنف أوشك ينخلص: {lowStockItems.map((i) => i.name).join("، ")}</div>
      )}
      {menu.map((cat) => (
        <div key={cat.catId} style={{ marginBottom: 14 }}>
          <div style={{ color: "var(--muted)", fontSize: 12.5, fontWeight: 700, marginBottom: 6 }}>{cat.catName}</div>
          {cat.items.map((item) => (
            <div className="menu-manage-card" key={item.id}>
              <div className="menu-manage-info">
                <div className="name">{item.icon} {item.name}</div>
                <div className="meta" style={{ color: item.stock <= LOW_STOCK_THRESHOLD ? "var(--danger)" : "var(--muted)" }}>
                  الكمية المتوفرة: {item.stock} {item.stock <= LOW_STOCK_THRESHOLD ? "— وشيك الانتهاء" : ""}
                </div>
              </div>
              <div className="restock-row">
                <input type="number" placeholder="كمية" value={restockAmount[item.id] || ""} onChange={(e) => setRestockAmount((prev) => ({ ...prev, [item.id]: e.target.value }))} />
                <button className="icon-btn" onClick={() => restock(cat.catId, item.id)}>+ توريد</button>
              </div>
            </div>
          ))}
        </div>
      ))}
    </div>
  );
}

function OwnerMenuManager({ menu, menuEditItem, setMenuEditItem, saveMenuItem, deleteMenuItem, applyGroupsToCategory, titleOverride }) {
  const [draft, setDraft] = useState({ id: "", name: "", price: "", stock: "", icon: "", groups: [] });

  useEffect(() => {
    if (menuEditItem) {
      const groups = (menuEditItem.item.modifierGroups || []).map((g) => ({ id: g.id, name: g.name, type: g.type, optionsText: g.options.join("، ") }));
      setDraft({ id: menuEditItem.item.id, name: menuEditItem.item.name, price: menuEditItem.item.price, stock: menuEditItem.item.stock, icon: menuEditItem.item.icon || "", groups });
    } else {
      setDraft({ id: "", name: "", price: "", stock: "", icon: "", groups: [] });
    }
  }, [menuEditItem]);

  function startAdd(catId) {
    setMenuEditItem({ catId, item: { id: uid(), name: "", price: "", stock: "", icon: "", modifierGroups: [] } });
  }
  function addGroup() {
    setDraft((d) => ({ ...d, groups: [...d.groups, { id: uid(), name: "", type: "single", optionsText: "" }] }));
  }
  function addPreset(preset) {
    setDraft((d) => {
      if (d.groups.some((g) => g.name === preset.group.name)) return d; // avoid duplicate group names
      return { ...d, groups: [...d.groups, { id: uid(), name: preset.group.name, type: preset.group.type, optionsText: preset.group.options.join("، ") }] };
    });
  }
  function updateGroup(gid, patch) {
    setDraft((d) => ({ ...d, groups: d.groups.map((g) => (g.id === gid ? { ...g, ...patch } : g)) }));
  }
  function removeGroup(gid) {
    setDraft((d) => ({ ...d, groups: d.groups.filter((g) => g.id !== gid) }));
  }
  function buildModifierGroups() {
    return draft.groups
      .map((g) => ({ id: g.id, name: g.name.trim(), type: g.type, options: g.optionsText.split(/[،,]/).map((o) => o.trim()).filter(Boolean) }))
      .filter((g) => g.name && g.options.length > 0);
  }
  function handleSave() {
    if (!draft.name.trim() || draft.price === "" || draft.stock === "") return;
    saveMenuItem(menuEditItem.catId, { id: draft.id, name: draft.name.trim(), price: Number(draft.price), stock: Number(draft.stock), icon: draft.icon || "🍽", modifierGroups: buildModifierGroups() });
  }
  function handleApplyToCategory() {
    const groups = buildModifierGroups();
    if (groups.length === 0) return;
    applyGroupsToCategory(menuEditItem.catId, groups);
  }

  return (
    <div className="panel">
      <h3>{titleOverride || "إدارة القائمة"}</h3>
      {menu.map((cat) => (
        <div key={cat.catId} style={{ marginBottom: 16 }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 6 }}>
            <span style={{ color: "var(--muted)", fontSize: 12.5, fontWeight: 700 }}>{cat.catName}</span>
            <button className="icon-btn" onClick={() => startAdd(cat.catId)}>+ صنف جديد</button>
          </div>

          {menuEditItem && menuEditItem.catId === cat.catId && (
            <div className="item-form">
              <div className="item-form-row">
                <input placeholder="اسم الصنف" value={draft.name} onChange={(e) => setDraft((d) => ({ ...d, name: e.target.value }))} />
                <input type="number" placeholder="السعر" value={draft.price} onChange={(e) => setDraft((d) => ({ ...d, price: e.target.value }))} />
                <input type="number" placeholder="الكمية بالمخزون" value={draft.stock} onChange={(e) => setDraft((d) => ({ ...d, stock: e.target.value }))} />
                <input placeholder="إيموجي (اختياري)" value={draft.icon} onChange={(e) => setDraft((d) => ({ ...d, icon: e.target.value }))} style={{ maxWidth: 90 }} />
              </div>

              <div className="mod-editor-title">⚡ إضافة سريعة — اضغط بس على اللي بدك ياه</div>
              <div className="mod-options" style={{ marginBottom: 12 }}>
                {MOD_PRESETS.map((p) => (
                  <button key={p.key} className="mod-chip" onClick={() => addPreset(p)}>{p.label}</button>
                ))}
              </div>

              {draft.groups.length > 0 && (
                <>
                  <div className="mod-editor-title">الخيارات المضافة (تقدر تعدلها)</div>
                  {draft.groups.map((g) => (
                    <div className="mod-editor-row" key={g.id}>
                      <input placeholder="اسم المجموعة" value={g.name} onChange={(e) => updateGroup(g.id, { name: e.target.value })} />
                      <select value={g.type} onChange={(e) => updateGroup(g.id, { type: e.target.value })}>
                        <option value="single">اختيار واحد</option>
                        <option value="multi">أكثر من اختيار</option>
                      </select>
                      <input placeholder="الخيارات مفصولة بفاصلة" value={g.optionsText} onChange={(e) => updateGroup(g.id, { optionsText: e.target.value })} style={{ flex: 2 }} />
                      <button className="icon-btn danger" onClick={() => removeGroup(g.id)}>✕</button>
                    </div>
                  ))}
                </>
              )}
              <button className="icon-btn" style={{ marginBottom: 10 }} onClick={addGroup}>+ مجموعة فاضية (يدوي)</button>

              {draft.groups.length > 0 && (
                <div className="no-access-inline" style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 8 }}>
                  <span>وفّر وقتك: طبّق نفس الخيارات فوق على كل أصناف "{cat.catName}" بضغطة وحدة</span>
                  <button className="icon-btn" style={{ background: "var(--primary-soft)", color: "var(--primary-dark)" }} onClick={handleApplyToCategory}>⚡ طبّق على كل القسم</button>
                </div>
              )}

              <div className="item-form-row" style={{ marginTop: 10 }}>
                <button style={{ background: "var(--success)", color: "var(--surface)" }} onClick={handleSave}>💾 حفظ</button>
                <button style={{ background: "var(--muted)", color: "var(--surface)" }} onClick={() => setMenuEditItem(null)}>إلغاء</button>
              </div>
            </div>
          )}

          {cat.items.map((item) => (
            <div className="menu-manage-card" key={item.id}>
              <div className="menu-manage-info">
                <div className="name">{item.icon} {item.name}</div>
                <div className="meta">
                  {item.price.toFixed(2)} د.أ · الكمية: {item.stock}
                  {item.modifierGroups && item.modifierGroups.length > 0 && ` · خيارات: ${item.modifierGroups.map((g) => g.name).join("، ")}`}
                </div>
              </div>
              <div style={{ display: "flex", gap: 6 }}>
                <button className="icon-btn" onClick={() => setMenuEditItem({ catId: cat.catId, item })}>✏️ تعديل</button>
                <button className="icon-btn danger" onClick={() => deleteMenuItem(cat.catId, item.id)}>🗑 حذف</button>
              </div>
            </div>
          ))}
        </div>
      ))}
    </div>
  );
}

function PrintersPanel({ printers, addPrinter, updatePrinter, removePrinter, zones }) {
  const [name, setName] = useState("");
  const [ip, setIp] = useState("");
  const [role, setRole] = useState("bar");
  const [zoneId, setZoneId] = useState("all");

  return (
    <div className="panel">
      <h3>🖨️ طابعات الكافيه — عندك {printers.length} طابعة مسجّلة</h3>
      <div className="no-access-inline">كل طابعة إلها دور (كاشير/باريستا/مطبخ/أراجيل)، منطقة (الأرضي/الروف/كل المناطق)، وعنوان IP. الربط الفعلي بين الطلب والطابعة الصحيحة بيصير تلقائياً حسب نوع الصنف ومنطقة الطاولة.</div>
      {printers.map((p) => (
        <div className="menu-manage-card" key={p.id}>
          <div className="menu-manage-info" style={{ flex: 1 }}>
            <div className="cred-row" style={{ marginTop: 0, flexWrap: "wrap" }}>
              <div className="cred-field">
                <label>اسم الطابعة</label>
                <input value={p.name} onChange={(e) => updatePrinter(p.id, "name", e.target.value)} />
              </div>
              <div className="cred-field">
                <label>عنوان IP</label>
                <input value={p.ip} onChange={(e) => updatePrinter(p.id, "ip", e.target.value)} />
              </div>
              <div className="cred-field">
                <label>الدور</label>
                <select className="staff-type-select" value={p.role} onChange={(e) => updatePrinter(p.id, "role", e.target.value)}>
                  <option value="cashier">💰 الكاشير</option>
                  <option value="bar">☕ الباريستا</option>
                  <option value="kitchen">🍽️ المطبخ</option>
                  <option value="hookah">💨 الأراجيل</option>
                </select>
              </div>
              <div className="cred-field">
                <label>المنطقة</label>
                <select className="staff-type-select" value={p.zoneId || "all"} onChange={(e) => updatePrinter(p.id, "zoneId", e.target.value)}>
                  <option value="all">🌐 كل المناطق</option>
                  {zones.map((z) => (
                    <option key={z.id} value={z.id}>🪑 {z.name}</option>
                  ))}
                </select>
              </div>
            </div>
          </div>
          <button className="icon-btn danger" onClick={() => removePrinter(p.id)}>🗑 حذف</button>
        </div>
      ))}
      <h3 style={{ marginTop: 18 }}>إضافة طابعة جديدة</h3>
      <div className="add-staff-row">
        <input placeholder="اسم الطابعة" value={name} onChange={(e) => setName(e.target.value)} />
        <input placeholder="عنوان IP (مثلاً 192.168.1.55)" value={ip} onChange={(e) => setIp(e.target.value)} />
        <select value={role} onChange={(e) => setRole(e.target.value)}>
          <option value="cashier">💰 الكاشير</option>
          <option value="bar">☕ الباريستا</option>
          <option value="kitchen">🍽️ المطبخ</option>
          <option value="hookah">💨 الأراجيل</option>
        </select>
        <select value={zoneId} onChange={(e) => setZoneId(e.target.value)}>
          <option value="all">🌐 كل المناطق</option>
          {zones.map((z) => (
            <option key={z.id} value={z.id}>🪑 {z.name}</option>
          ))}
        </select>
        <button onClick={() => { addPrinter(name, ip, role, zoneId); setName(""); setIp(""); }}>+ إضافة</button>
      </div>
    </div>
  );
}

function ExpensesPanel({ expenses, addExpense, removeExpense, period, setPeriod, customRange, setCustomRange }) {
  const [type, setType] = useState("purchase");
  const [description, setDescription] = useState("");
  const [amount, setAmount] = useState("");

  const range = getPeriodRange(period, new Date(), customRange);
  const scoped = range ? expenses.filter((e) => e.createdAt >= range.start && e.createdAt <= range.end) : expenses;
  const totalPurchases = scoped.filter((e) => e.type === "purchase").reduce((s, e) => s + e.amount, 0);
  const totalWithdrawals = scoped.filter((e) => e.type === "withdrawal").reduce((s, e) => s + e.amount, 0);

  return (
    <div className="panel">
      <h3>💸 المشتريات والسحوبات</h3>
      <PeriodTabs period={period} setPeriod={setPeriod} customRange={customRange} setCustomRange={setCustomRange} />

      <div className="kpi-grid" style={{ marginTop: 14 }}>
        <div className="kpi-card"><div className="kpi-label">إجمالي المشتريات</div><div className="kpi-value">{money(totalPurchases)}</div></div>
        <div className="kpi-card"><div className="kpi-label">إجمالي السحوبات</div><div className="kpi-value">{money(totalWithdrawals)}</div></div>
      </div>

      <div style={{ maxHeight: 300, overflowY: "auto" }}>
        {scoped.length === 0 && <div className="empty-msg">ما في مشتريات أو سحوبات بهاي الفترة</div>}
        {[...scoped].sort((a, b) => b.createdAt - a.createdAt).map((e) => (
          <div className="menu-manage-card" key={e.id}>
            <div className="menu-manage-info">
              <div className="name">{e.type === "purchase" ? "🛒" : "💵"} {e.description}</div>
              <div className="meta">{new Date(e.createdAt).toLocaleString("ar")}</div>
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <span className="mono" style={{ fontWeight: 800 }}>{money(e.amount)}</span>
              <button className="icon-btn danger" onClick={() => removeExpense(e.id)}>🗑</button>
            </div>
          </div>
        ))}
      </div>

      <h3 style={{ marginTop: 18 }}>إضافة سجل جديد</h3>
      <div className="add-staff-row">
        <select value={type} onChange={(e) => setType(e.target.value)}>
          <option value="purchase">🛒 مشترى</option>
          <option value="withdrawal">💵 سحب</option>
        </select>
        <input placeholder="الوصف (مثلاً: شراء حليب)" value={description} onChange={(e) => setDescription(e.target.value)} style={{ flex: 2 }} />
        <input type="number" placeholder="المبلغ" value={amount} onChange={(e) => setAmount(e.target.value)} />
        <button onClick={() => { addExpense(type, description, amount); setDescription(""); setAmount(""); }}>+ إضافة</button>
      </div>
    </div>
  );
}

function ClosingsPanel({ cashClosings }) {
  const sortedClosings = [...cashClosings].sort((a, b) => b.closedAt - a.closedAt);
  const totalActualCash = cashClosings.reduce((s, c) => s + c.actualCash, 0);
  const totalActualCard = cashClosings.reduce((s, c) => s + (c.actualCard ?? 0), 0);
  const totalClickCount = cashClosings.reduce((s, c) => s + (c.clickCount ?? 0), 0);
  const totalClickAmount = cashClosings.reduce((s, c) => s + (c.clickAmount ?? 0), 0);

  return (
    <div className="panel">
      <h3>🔒 إغلاقات الكاشير اليومية</h3>
      {cashClosings.length === 0 && <div className="empty-msg">ما في إغلاقات مسجّلة بعد</div>}
      {cashClosings.length > 0 && (
        <div className="kpi-grid" style={{ marginBottom: 16 }}>
          <div className="kpi-card"><div className="kpi-label">مجموع النقدي الفعلي</div><div className="kpi-value">{money(totalActualCash)}</div></div>
          <div className="kpi-card"><div className="kpi-label">مجموع البطاقة الفعلي</div><div className="kpi-value">{money(totalActualCard)}</div></div>
          <div className="kpi-card"><div className="kpi-label">📲 عمليات كليك (عدد / مبلغ)</div><div className="kpi-value" style={{ fontSize: 16 }}>{totalClickCount} / {money(totalClickAmount)}</div></div>
          <div className="kpi-card"><div className="kpi-label">المجموع الكلي</div><div className="kpi-value">{money(totalActualCash + totalActualCard + totalClickAmount)}</div></div>
        </div>
      )}
      <div style={{ maxHeight: 420, overflowY: "auto" }}>
        <table className="log">
          <thead>
            <tr>
              <th>الكاشير</th><th>المنطقة</th><th>الوقت</th>
              <th>نقدي فعلي</th><th>بطاقة فعلي</th><th>كليك (عدد/مبلغ)</th><th>المجموع</th>
            </tr>
          </thead>
          <tbody>
            {sortedClosings.map((c) => (
              <tr key={c.id}>
                <td>{c.cashierName}</td>
                <td><span className="type-badge">🪑 {c.zoneName || "—"}</span></td>
                <td>{new Date(c.closedAt).toLocaleString("ar")}</td>
                <td className="mono">{money(c.actualCash)}</td>
                <td className="mono">{money(c.actualCard ?? 0)}</td>
                <td className="mono">{c.clickCount ?? 0} / {money(c.clickAmount ?? 0)}</td>
                <td className="mono" style={{ fontWeight: 800 }}>{money(c.actualCash + (c.actualCard ?? 0) + (c.clickAmount ?? 0))}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function ReportsPanel({ reports, pendingCount, orders, now, period, setPeriod, customRange, setCustomRange }) {
  return (
    <div>
      <div className="panel" style={{ marginBottom: 14 }}>
        <PeriodTabs period={period} setPeriod={setPeriod} customRange={customRange} setCustomRange={setCustomRange} />
      </div>
      <div className="kpi-grid">
        <div className="kpi-card"><div className="kpi-label">إجمالي المبيعات</div><div className="kpi-value">{money(reports.totalRevenue)}</div></div>
        <div className="kpi-card"><div className="kpi-label">عدد الطلبات المدفوعة</div><div className="kpi-value">{reports.ordersCount}</div></div>
        <div className="kpi-card"><div className="kpi-label">متوسط الفاتورة</div><div className="kpi-value">{money(reports.avgTicket)}</div></div>
        <div className="kpi-card"><div className="kpi-label">طلبات قيد الانتظار</div><div className="kpi-value">{pendingCount}</div></div>
      </div>

      <div className="panel" style={{ marginBottom: 18 }}>
        <h3>🏆 الأكثر نشاطاً — عدد الطلبات المأخوذة من العملاء</h3>
        {reports.waiterActivity.length === 0 && <div className="empty-msg">ما في نشاط مسجّل بعد</div>}
        {reports.waiterActivity.map((w, idx) => (
          <div className="tally-row" key={w.name}>
            <div className="tally-head">
              <span>{idx === 0 && w.count > 0 ? "👑 " : `${idx + 1}. `}{w.name}</span>
              <span className="mono">{w.count} طلب</span>
            </div>
            <div className="bar-track">
              <div className="bar-fill" style={{ background: idx === 0 ? "var(--warning)" : "var(--primary)", width: `${reports.maxActivity ? (w.count / reports.maxActivity) * 100 : 0}%` }} />
            </div>
          </div>
        ))}
      </div>

      <div className="grid-2">
        <div className="panel">
          <h3>الأصناف الأكثر مبيعاً</h3>
          {reports.topItems.length === 0 && <div className="empty-msg">ما في مبيعات مسجّلة بعد</div>}
          {reports.topItems.map((i) => (
            <div className="tally-row" key={i.name}>
              <div className="tally-head"><span>{i.name} <span className="mono">× {i.qty}</span></span><span className="mono">{money(i.revenue)}</span></div>
              <div className="bar-track"><div className="bar-fill" style={{ width: `${(i.revenue / reports.maxItemRevenue) * 100}%` }} /></div>
            </div>
          ))}

          <h3 style={{ marginTop: 22 }}>حسب طريقة الدفع</h3>
          <div className="tally-row">
            <div className="tally-head"><span>💵 نقدي</span><span className="mono">{money(reports.byMethod["نقدي"])}</span></div>
            <div className="bar-track"><div className="bar-fill" style={{ background: "var(--success)", width: `${reports.totalRevenue ? (reports.byMethod["نقدي"] / reports.totalRevenue) * 100 : 0}%` }} /></div>
          </div>
          <div className="tally-row">
            <div className="tally-head"><span>💳 بطاقة</span><span className="mono">{money(reports.byMethod["بطاقة"])}</span></div>
            <div className="bar-track"><div className="bar-fill" style={{ width: `${reports.totalRevenue ? (reports.byMethod["بطاقة"] / reports.totalRevenue) * 100 : 0}%` }} /></div>
          </div>
          <div className="tally-row">
            <div className="tally-head"><span>📲 كليك ({reports.clickCount} عملية)</span><span className="mono">{money(reports.byMethod["كليك"])}</span></div>
            <div className="bar-track"><div className="bar-fill" style={{ background: "#7c3aed", width: `${reports.totalRevenue ? (reports.byMethod["كليك"] / reports.totalRevenue) * 100 : 0}%` }} /></div>
          </div>

          <h3 style={{ marginTop: 22 }}>Dine-in مقابل Take Away</h3>
          <div className="tally-row">
            <div className="tally-head"><span>🍽 Dine-in</span><span className="mono">{money(reports.byType["dine-in"])}</span></div>
            <div className="bar-track"><div className="bar-fill" style={{ background: "var(--primary)", width: `${reports.totalRevenue ? (reports.byType["dine-in"] / reports.totalRevenue) * 100 : 0}%` }} /></div>
          </div>
          <div className="tally-row">
            <div className="tally-head"><span>🥡 Take Away</span><span className="mono">{money(reports.byType.takeaway)}</span></div>
            <div className="bar-track"><div className="bar-fill" style={{ background: "#0891b2", width: `${reports.totalRevenue ? (reports.byType.takeaway / reports.totalRevenue) * 100 : 0}%` }} /></div>
          </div>
        </div>

        <div className="panel">
          <h3>المبيعات حسب الموظف</h3>
          {(() => {
            const maxStaffRevenue = Math.max(1, ...reports.byStaff.map((s) => s.revenue));
            return reports.byStaff.map((s) => (
              <div className="tally-row" key={s.name}>
                <div className="tally-head"><span>{s.name}</span><span className="mono">{money(s.revenue)}</span></div>
                <div className="bar-track"><div className="bar-fill" style={{ width: `${(s.revenue / maxStaffRevenue) * 100}%` }} /></div>
              </div>
            ));
          })()}
        </div>
      </div>

      <div className="panel" style={{ marginTop: 18 }}>
        <h3>سجل كل الطلبات</h3>
        <div style={{ maxHeight: 260, overflowY: "auto" }}>
          <table className="log">
            <thead><tr><th>رقم</th><th>النوع</th><th>الموظف</th><th>الوقت</th><th>الحالة</th><th>الدفع</th><th>الإجمالي</th></tr></thead>
            <tbody>
              {[...orders].sort((a, b) => b.createdAt - a.createdAt).map((o) => (
                <tr key={o.id}>
                  <td className="mono">#{o.id}</td>
                  <td>{orderLabel(o)}</td>
                  <td>{(o.waiters || [o.staffName]).join("، ")}</td>
                  <td>{timeAgo(o.createdAt, now)}</td>
                  <td><span className={`badge ${o.status}`}>{o.status === "paid" ? "مدفوع" : o.status === "held" ? "معلّقة" : "قيد الانتظار"}</span></td>
                  <td>{o.paymentMethod === "مقسّم" ? `نقدي ${money(o.cashAmount || 0)} + بطاقة ${money(o.cardAmount || 0)}` : o.paymentMethod || "—"}</td>
                  <td className="mono">{money(o.total)}</td>
                </tr>
              ))}
              {orders.length === 0 && <tr><td colSpan={7} style={{ textAlign: "center", padding: 20 }}>ما في طلبات بعد</td></tr>}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

// تشغيل التطبيق فعلياً داخل الصفحة
const rootEl = document.getElementById("root");
ReactDOM.createRoot(rootEl).render(<CafePOS />);
