const { useState, useEffect, useCallback } = React;

const BRANCHES = [
  { id: "army", name: "القوات البرية", nameEn: "GROUND FORCES", code: "GF-01", color: "#2e7d32" },
  { id: "airforce", name: "القوات الجوية", nameEn: "AIR FORCES", code: "AF-02", color: "#1565c0" },
  { id: "navy", name: "القوات البحرية", nameEn: "NAVAL FORCES", code: "NF-03", color: "#00695c" },
];

const WAREHOUSES = [
  { id: "ammo", name: "الذخيرة", nameEn: "AMMUNITION", color: "#c62828", idealTemp: [15, 25], idealHumidity: [30, 50] },
  { id: "medical", name: "المواد الطبية", nameEn: "MEDICAL", color: "#2e7d32", idealTemp: [2, 8], idealHumidity: [35, 65] },
  { id: "general", name: "المواد العامة", nameEn: "GENERAL", color: "#e65100", idealTemp: [10, 30], idealHumidity: [30, 60] },
];

const ITEMS_DATA = {
  ammo: [
    { id: 1, name: "طلقات 5.56mm NATO", unit: "صندوق", max: 1000, current: 850, category: "ذخيرة خفيفة" },
    { id: 2, name: "طلقات 7.62mm", unit: "صندوق", max: 800, current: 120, category: "ذخيرة خفيفة" },
    { id: 3, name: "قنابل يدوية M67", unit: "قطعة", max: 500, current: 420, category: "متفجرات" },
    { id: 4, name: "صواريخ TOW", unit: "قطعة", max: 200, current: 28, category: "صواريخ" },
    { id: 5, name: "قذائف هاون 81mm", unit: "صندوق", max: 300, current: 280, category: "قذائف" },
    { id: 6, name: "طلقات 9mm", unit: "صندوق", max: 600, current: 65, category: "ذخيرة خفيفة" },
    { id: 7, name: "قنابل دخانية", unit: "قطعة", max: 400, current: 350, category: "متفجرات" },
    { id: 8, name: "صواعق تفجير", unit: "قطعة", max: 250, current: 45, category: "متفجرات" },
  ],
  medical: [
    { id: 1, name: "ضمادات ميدانية", unit: "عبوة", max: 2000, current: 1800, category: "إسعافات أولية" },
    { id: 2, name: "محاليل وريدية", unit: "كرتون", max: 500, current: 70, category: "سوائل" },
    { id: 3, name: "مورفين", unit: "أمبول", max: 1000, current: 750, category: "أدوية" },
    { id: 4, name: "أموكسيسيلين", unit: "عبوة", max: 800, current: 150, category: "مضادات حيوية" },
    { id: 5, name: "أطقم جراحية", unit: "طقم", max: 100, current: 85, category: "معدات" },
    { id: 6, name: "أكياس دم O-", unit: "وحدة", max: 300, current: 40, category: "بنك دم" },
    { id: 7, name: "جبائر طبية", unit: "قطعة", max: 600, current: 520, category: "إسعافات أولية" },
    { id: 8, name: "أقنعة أكسجين", unit: "قطعة", max: 200, current: 180, category: "معدات" },
  ],
  general: [
    { id: 1, name: "وقود ديزل JP-8", unit: "برميل", max: 5000, current: 4200, category: "وقود" },
    { id: 2, name: "زيوت محركات", unit: "جالون", max: 1000, current: 160, category: "زيوت" },
    { id: 3, name: "قطع غيار MRAP", unit: "قطعة", max: 2000, current: 1500, category: "قطع غيار" },
    { id: 4, name: "بطاريات 24V", unit: "قطعة", max: 500, current: 55, category: "كهرباء" },
    { id: 5, name: "إطارات تكتيكية", unit: "قطعة", max: 300, current: 260, category: "قطع غيار" },
    { id: 6, name: "أجهزة اتصال", unit: "جهاز", max: 200, current: 170, category: "اتصالات" },
    { id: 7, name: "مولدات كهربائية", unit: "مولد", max: 50, current: 8, category: "كهرباء" },
    { id: 8, name: "خيام ميدانية", unit: "خيمة", max: 150, current: 130, category: "تجهيزات" },
  ],
};

function genEnv(wid) {
  const w = WAREHOUSES.find(x => x.id === wid);
  const [tMin, tMax] = w.idealTemp;
  const [hMin, hMax] = w.idealHumidity;
  return {
    temp: +(tMin + Math.random() * (tMax - tMin) * 1.5 - (tMax - tMin) * 0.15).toFixed(1),
    humidity: +Math.max(5, Math.min(95, hMin + Math.random() * (hMax - hMin) * 1.4 - (hMax - hMin) * 0.1)).toFixed(1),
  };
}

const READINESS = ["جاهز", "متوسط", "حرج"];
const OPTEMPO = ["منخفض", "متوسط", "مرتفع"];

function initData() {
  const d = {};
  BRANCHES.forEach(b => {
    d[b.id] = {};
    WAREHOUSES.forEach(w => {
      const env = genEnv(w.id);
      d[b.id][w.id] = {
        items: ITEMS_DATA[w.id].map(item => {
          const v = Math.floor(Math.random() * item.max * 0.25);
          return { ...item, current: Math.max(3, Math.min(item.max, Math.floor(item.current + (Math.random() > 0.5 ? v : -v)))) };
        }),
        temp: env.temp, humidity: env.humidity,
      };
    });
  });
  return d;
}

function initRequests() {
  const types = ["وقود", "ذخيرة", "مواد طبية", "قطع غيار", "معدات اتصال"];
  const priorities = ["عادي", "عاجل", "طوارئ"];
  return BRANCHES.map((b, i) => ({
    id: `ORD-${String(Math.floor(Math.random() * 90000 + 10000))}`,
    branch: b,
    type: types[i % types.length],
    priority: priorities[i],
    quantity: Math.floor(Math.random() * 500 + 50),
    currentPct: Math.floor(Math.random() * 40 + 10),
    distance: Math.floor(Math.random() * 700 + 100),
    eta: (Math.random() * 3 + 0.5).toFixed(1),
    status: "pending",
    time: new Date().toLocaleTimeString("en-US", { hour12: false }),
  }));
}

const TH = 0.25;

/* ──── SVG Icons ──── */
const I = {
  shield: (s=18,c="#2e7d32") => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>,
  box: (s=18,c="#555") => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/><path d="M3.27 6.96L12 12.01l8.73-5.05"/><path d="M12 22.08V12"/></svg>,
  alert: (s=18,c="#c62828") => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>,
  temp: (s=18,c="#1565c0") => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M14 14.76V3.5a2.5 2.5 0 0 0-5 0v11.26a4.5 4.5 0 1 0 5 0z"/></svg>,
  drop: (s=18,c="#0097a7") => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 2.69l5.66 5.66a8 8 0 1 1-11.31 0z"/></svg>,
  chart: (s=18,c="#555") => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="18" y1="20" x2="18" y2="10"/><line x1="12" y1="20" x2="12" y2="4"/><line x1="6" y1="20" x2="6" y2="14"/></svg>,
  log: (s=18,c="#555") => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/></svg>,
  bell: (s=18,c="#555") => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 0 1-3.46 0"/></svg>,
  user: (s=18,c="#555") => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>,
  lock: (s=18,c="#555") => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>,
  edit: (s=14,c="#2e7d32") => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>,
  trash: (s=14,c="#c62828") => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>,
  plus: (s=14,c="#fff") => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2.5" strokeLinecap="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>,
  check: (s=14,c="#2e7d32") => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>,
  x: (s=14,c="#999") => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2.5" strokeLinecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>,
  chevL: (s=14,c="#999") => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="15 18 9 12 15 6"/></svg>,
  search: (s=14,c="#999") => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>,
  arrow: (s=14,c="#2e7d32") => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/></svg>,
  home: (s=18,c="#555") => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/></svg>,
  target: (s=18,c="#555") => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2"><circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="6"/><circle cx="12" cy="12" r="2"/></svg>,
  truck: (s=18,c="#555") => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="1" y="3" width="15" height="13"/><polygon points="16 8 20 8 23 11 23 16 16 16 16 8"/><circle cx="5.5" cy="18.5" r="2.5"/><circle cx="18.5" cy="18.5" r="2.5"/></svg>,
  clock: (s=18,c="#555") => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>,
  inbox: (s=18,c="#555") => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="22 12 16 12 14 15 10 15 8 12 2 12"/><path d="M5.45 5.11L2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z"/></svg>,
  activity: (s=18,c="#555") => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/></svg>,
  menu: (s=18,c="#555") => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2" strokeLinecap="round"><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="18" x2="21" y2="18"/></svg>,
  warehouse: (s=18,c="#555") => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 21V8l9-5 9 5v13"/><path d="M3 21h18"/><path d="M9 21V13h6v8"/></svg>,
};

function Bar({ pct, h = 7, color }) {
  const c = color || (pct <= 10 ? "#c62828" : pct <= 25 ? "#e65100" : pct <= 50 ? "#f9a825" : "#2e7d32");
  return <div style={{ width: "100%", height: h, background: "#eee", borderRadius: h/2, overflow: "hidden" }}><div style={{ width: `${Math.min(100, pct)}%`, height: "100%", borderRadius: h/2, background: c }} /></div>;
}

function Dot({ pct }) {
  const c = pct <= 10 ? "#c62828" : pct <= 25 ? "#e65100" : pct <= 50 ? "#f9a825" : "#2e7d32";
  return <span style={{ display: "inline-block", width: 8, height: 8, borderRadius: "50%", background: c }} />;
}

function Badge({ children, color = "#c62828" }) {
  return <span style={{ background: color, color: "#fff", borderRadius: 10, padding: "2px 8px", fontSize: 10, fontWeight: 700, display: "inline-flex", alignItems: "center" }}>{children}</span>;
}

function MetricBox({ label, value, unit, color = "#2e7d32", warn }) {
  return (
    <div style={{ background: warn ? "#fff5f5" : "#f5faf5", border: `1px solid ${warn ? "#ffcdd2" : "#c8e6c9"}`, borderRadius: 8, padding: "8px 12px", textAlign: "center", minWidth: 70 }}>
      <div style={{ fontSize: 18, fontWeight: 900, color: warn ? "#c62828" : color, fontFamily: "'IBM Plex Sans'" }}>{value}</div>
      <div style={{ fontSize: 9, color: "#888", fontWeight: 600 }}>{unit || ""}</div>
      <div style={{ fontSize: 9, color: "#aaa", marginTop: 2 }}>{label}</div>
    </div>
  );
}

const css = `
@import url('https://fonts.googleapis.com/css2?family=Tajawal:wght@300;400;500;700;800;900&family=IBM+Plex+Sans:wght@400;500;600;700&display=swap');
* { box-sizing:border-box; margin:0; padding:0; }
::-webkit-scrollbar { width:4px }
::-webkit-scrollbar-track { background:#f5f5f5 }
::-webkit-scrollbar-thumb { background:#ccc; border-radius:3px }
.hov:hover { background: #f8faf8 !important; }
.hov-card:hover { box-shadow: 0 2px 12px rgba(0,0,0,0.06) !important; border-color: #c8e6c9 !important; }
input:focus, select:focus { border-color: #4CAF50 !important; outline: none; box-shadow: 0 0 0 3px rgba(76,175,80,0.08) !important; }
`;

const S = {
  input: { padding: "9px 12px", borderRadius: 7, border: "1px solid #ddd", background: "#fff", color: "#333", fontSize: 13, fontFamily: "'Tajawal'", outline: "none", direction: "rtl", width: "100%" },
  btnP: { padding: "8px 18px", borderRadius: 7, border: "none", background: "#2e7d32", color: "#fff", cursor: "pointer", fontSize: 12, fontWeight: 700, fontFamily: "'Tajawal'", display: "inline-flex", alignItems: "center", gap: 5 },
  btnG: { padding: "7px 14px", borderRadius: 7, border: "1px solid #c8e6c9", background: "#fff", color: "#2e7d32", cursor: "pointer", fontSize: 11, fontWeight: 600, fontFamily: "'Tajawal'", display: "inline-flex", alignItems: "center", gap: 4 },
  btnD: { padding: "5px 10px", borderRadius: 6, border: "1px solid #ffcdd2", background: "#fff", color: "#c62828", cursor: "pointer", fontSize: 10, fontFamily: "'Tajawal'", display: "inline-flex", alignItems: "center", gap: 3 },
  card: { background: "#fff", border: "1px solid #e8e8e8", borderRadius: 10, padding: 16 },
  th: { padding: "10px 12px", textAlign: "right", color: "#888", fontWeight: 600, borderBottom: "2px solid #eee", fontSize: 10, whiteSpace: "nowrap", letterSpacing: 0.3 },
  td: { padding: "10px 12px", borderBottom: "1px solid #f3f3f3", fontSize: 12 },
};

function App() {
  const [appState, setAppState] = useState("landing");
  const [data, setData] = useState(initData);
  const [requests, setRequests] = useState(initRequests);
  const [page, setPage] = useState("home");
  const [tab, setTab] = useState("dashboard");
  const [branch, setBranch] = useState(null);
  const [warehouse, setWarehouse] = useState(null);
  const [search, setSearch] = useState("");
  const [editId, setEditId] = useState(null);
  const [editVal, setEditVal] = useState("");
  const [showAdd, setShowAdd] = useState(false);
  const [newItem, setNewItem] = useState({ name: "", unit: "", max: "", current: "", category: "" });
  const [toast, setToast] = useState(null);
  const [filterCat, setFilterCat] = useState("all");
  const [sortBy, setSortBy] = useState("name");
  const [logs, setLogs] = useState([]);
  const [loginForm, setLoginForm] = useState({ username: "", password: "" });
  const [loginError, setLoginError] = useState("");
  const [sideOpen, setSideOpen] = useState(true);
  const [time, setTime] = useState(new Date());

  useEffect(() => { const t = setInterval(() => setTime(new Date()), 1000); return () => clearInterval(t); }, []);
  useEffect(() => {
    const t = setInterval(() => {
      setData(prev => {
        const n = JSON.parse(JSON.stringify(prev));
        BRANCHES.forEach(b => { WAREHOUSES.forEach(w => { const e = genEnv(w.id); n[b.id][w.id].temp = e.temp; n[b.id][w.id].humidity = e.humidity; }); });
        return n;
      });
    }, 20000);
    return () => clearInterval(t);
  }, []);

  const notify = (msg, type = "success") => { setToast({ msg, type }); setTimeout(() => setToast(null), 3000); };
  const addLog = (a) => setLogs(p => [{ action: a, time: new Date().toLocaleTimeString("en-US", { hour12: false }), date: new Date().toLocaleDateString("en-US") }, ...p].slice(0, 80));
  const goTo = (p, b, w) => { setPage(p); setBranch(b); setWarehouse(w); setSearch(""); setFilterCat("all"); setShowAdd(false); setEditId(null); };

  const getAlerts = useCallback(() => {
    const a = [];
    BRANCHES.forEach(b => {
      WAREHOUSES.forEach(w => {
        const wd = data[b.id]?.[w.id]; if (!wd) return;
        wd.items.forEach(item => { const p = item.current / item.max; if (p <= TH) a.push({ branch: b, warehouse: w, item, pct: p }); });
        const wi = WAREHOUSES.find(x => x.id === w.id);
        if (wd.temp < wi.idealTemp[0] || wd.temp > wi.idealTemp[1]) a.push({ branch: b, warehouse: w, type: "temp", value: wd.temp, ideal: wi.idealTemp });
        if (wd.humidity < wi.idealHumidity[0] || wd.humidity > wi.idealHumidity[1]) a.push({ branch: b, warehouse: w, type: "humidity", value: wd.humidity, ideal: wi.idealHumidity });
      });
    });
    return a.sort((x, y) => (x.pct || 0) - (y.pct || 0));
  }, [data]);

  const alerts = getAlerts();
  const itemAlerts = alerts.filter(a => a.item);
  const envAlerts = alerts.filter(a => a.type);
  const pendingReqs = requests.filter(r => r.status === "pending");

  const branchAlertCount = (bid) => { let c = 0; WAREHOUSES.forEach(w => { (data[bid]?.[w.id]?.items || []).forEach(i => { if (i.current / i.max <= TH) c++; }); }); return c; };

  const branchMCR = (bid) => {
    let tot = 0, cur = 0;
    WAREHOUSES.forEach(w => { (data[bid]?.[w.id]?.items || []).forEach(i => { tot += i.max; cur += i.current; }); });
    return tot > 0 ? Math.round((cur / tot) * 100) : 0;
  };

  const totalStats = () => {
    let items = 0, max = 0, cur = 0, low = 0, envW = 0;
    BRANCHES.forEach(b => { WAREHOUSES.forEach(w => {
      const wd = data[b.id]?.[w.id]; if (!wd) return;
      wd.items.forEach(i => { items++; max += i.max; cur += i.current; if (i.current / i.max <= TH) low++; });
      const wi = WAREHOUSES.find(x => x.id === w.id);
      if (wd.temp < wi.idealTemp[0] || wd.temp > wi.idealTemp[1]) envW++;
      if (wd.humidity < wi.idealHumidity[0] || wd.humidity > wi.idealHumidity[1]) envW++;
    }); });
    return { items, max, cur, low, envW, pct: max > 0 ? (cur / max) * 100 : 0 };
  };
  const stats = totalStats();

  const updateItem = (bid, wid, itemId, val) => {
    const v = parseInt(val); if (isNaN(v) || v < 0) return;
    setData(prev => { const n = JSON.parse(JSON.stringify(prev)); const idx = n[bid][wid].items.findIndex(i => i.id === itemId); if (idx !== -1) { const old = n[bid][wid].items[idx].current; n[bid][wid].items[idx].current = Math.min(v, n[bid][wid].items[idx].max); addLog(`تحديث "${n[bid][wid].items[idx].name}" من ${old} إلى ${v}`); } return n; });
    setEditId(null); notify("تم تحديث الكمية بنجاح");
  };

  const addNewItem = (bid, wid) => {
    if (!newItem.name || !newItem.unit || !newItem.max || !newItem.current) return;
    setData(prev => { const n = JSON.parse(JSON.stringify(prev)); const maxId = n[bid][wid].items.reduce((m, i) => Math.max(m, i.id), 0); n[bid][wid].items.push({ id: maxId + 1, name: newItem.name, unit: newItem.unit, max: +newItem.max, current: +newItem.current, category: newItem.category || "عام" }); addLog(`إضافة بند "${newItem.name}"`); return n; });
    setNewItem({ name: "", unit: "", max: "", current: "", category: "" }); setShowAdd(false); notify("تم إضافة البند");
  };

  const deleteItem = (bid, wid, itemId) => {
    const item = data[bid][wid].items.find(i => i.id === itemId);
    setData(prev => { const n = JSON.parse(JSON.stringify(prev)); n[bid][wid].items = n[bid][wid].items.filter(i => i.id !== itemId); return n; });
    addLog(`حذف بند "${item?.name}"`); notify("تم حذف البند", "warn");
  };

  const handleRequest = (id, action) => {
    setRequests(prev => prev.map(r => r.id === id ? { ...r, status: action } : r));
    addLog(`${action === "approved" ? "الموافقة على" : "رفض"} طلب الإمداد ${id}`);
    notify(action === "approved" ? "تمت الموافقة على الطلب" : "تم رفض الطلب", action === "approved" ? "success" : "warn");
  };

  const handleLogin = () => { if (loginForm.username === "admin" && loginForm.password === "admin") { setAppState("app"); } else { setLoginError("بيانات الدخول غير صحيحة"); } };

  /* ═══════ LANDING ═══════ */
  if (appState === "landing") return (
    <div style={{ direction: "rtl", fontFamily: "'Tajawal', sans-serif", background: "#fff", minHeight: "100vh" }}>
      <style>{css}</style>
      <nav style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "14px 40px", borderBottom: "1px solid #eee", position: "sticky", top: 0, background: "rgba(255,255,255,0.97)", zIndex: 100, backdropFilter: "blur(10px)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          {I.shield(24, "#2e7d32")}
          <div><div style={{ fontSize: 15, fontWeight: 900, color: "#1a1a1a" }}>منصة إدارة المستودعات</div><div style={{ fontSize: 8, color: "#888", fontFamily: "'IBM Plex Sans'", letterSpacing: 2, fontWeight: 600 }}>WAREHOUSE MANAGEMENT SYSTEM</div></div>
        </div>
        <button onClick={() => setAppState("login")} style={{ ...S.btnP, padding: "8px 24px" }}>تسجيل الدخول</button>
      </nav>

      <section style={{ padding: "70px 40px", maxWidth: 1100, margin: "0 auto", display: "flex", alignItems: "center", gap: 50 }}>
        <div style={{ flex: 1 }}>
          <div style={{ display: "inline-flex", alignItems: "center", gap: 6, background: "#e8f5e9", padding: "5px 14px", borderRadius: 20, marginBottom: 18 }}><span style={{ fontSize: 11, color: "#2e7d32", fontWeight: 600 }}>Defensethon 2026</span></div>
          <h1 style={{ fontSize: 36, fontWeight: 900, color: "#1a1a1a", lineHeight: 1.4, marginBottom: 16 }}>منصة إدارة ومراقبة<br /><span style={{ color: "#2e7d32" }}>المستودعات العسكرية</span></h1>
          <p style={{ fontSize: 15, color: "#666", lineHeight: 1.8, marginBottom: 28, maxWidth: 460 }}>نظام متكامل لإدارة مستودعات الذخيرة والمواد الطبية والعامة مع مراقبة بيئية وطلبات إمداد ذكية وتنبيهات لحظية</p>
          <button onClick={() => setAppState("login")} style={{ ...S.btnP, padding: "14px 36px", fontSize: 14, borderRadius: 10 }}>ابدأ الآن {I.arrow(16, "#fff")}</button>
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ background: "#f8faf8", border: "1px solid #e0e0e0", borderRadius: 14, padding: 24 }}>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
              {[{ v: "9", l: "مستودع", s: "نشط", ic: I.warehouse(20, "#2e7d32") }, { v: "3", l: "أفرع", s: "عسكرية", ic: I.target(20, "#1565c0") }, { v: "72+", l: "بند", s: "مراقب", ic: I.box(20, "#e65100") }, { v: "24/7", l: "مراقبة", s: "مستمرة", ic: I.activity(20, "#c62828") }].map((s, i) => (
                <div key={i} style={{ background: "#fff", borderRadius: 10, padding: 14, border: "1px solid #eee" }}>
                  <div style={{ marginBottom: 6 }}>{s.ic}</div>
                  <div style={{ fontSize: 22, fontWeight: 900, color: "#1a1a1a", fontFamily: "'IBM Plex Sans'" }}>{s.v}</div>
                  <div style={{ fontSize: 11, fontWeight: 700, color: "#333" }}>{s.l}</div>
                  <div style={{ fontSize: 9, color: "#999" }}>{s.s}</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </section>

      <section style={{ padding: "50px 40px", background: "#fafafa", borderTop: "1px solid #eee" }}>
        <div style={{ maxWidth: 1100, margin: "0 auto" }}>
          <h2 style={{ fontSize: 24, fontWeight: 900, color: "#1a1a1a", marginBottom: 8, textAlign: "center" }}>مميزات المنصة</h2>
          <p style={{ fontSize: 13, color: "#888", textAlign: "center", marginBottom: 36 }}>أدوات متقدمة لإدارة ومراقبة المستودعات العسكرية بكفاءة</p>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(280px, 1fr))", gap: 16 }}>
            {[
              { ic: I.chart(24, "#2e7d32"), t: "مراقبة المخزون", d: "تتبع لحظي لجميع البنود مع تنبيهات تلقائية عند انخفاض المخزون عن 25%" },
              { ic: I.temp(24, "#1565c0"), t: "المراقبة البيئية", d: "رصد درجة الحرارة والرطوبة بنطاقات مثالية مخصصة حسب نوع المواد" },
              { ic: I.inbox(24, "#e65100"), t: "طلبات الإمداد", d: "نظام طلبات إمداد ذكي مع إمكانية الموافقة والرفض وتتبع الحالة" },
              { ic: I.alert(24, "#c62828"), t: "نظام التنبيهات", d: "تنبيهات متعددة المستويات للمخزون والظروف البيئية" },
              { ic: I.log(24, "#00695c"), t: "سجل العمليات", d: "توثيق شامل لجميع العمليات مع الطوابع الزمنية" },
              { ic: I.shield(24, "#4a148c"), t: "أمان متقدم", d: "نظام تسجيل دخول آمن مع صلاحيات وصول محددة" },
            ].map((f, i) => (
              <div key={i} style={{ background: "#fff", borderRadius: 10, padding: 20, border: "1px solid #eee" }}>
                <div style={{ marginBottom: 10 }}>{f.ic}</div>
                <h3 style={{ fontSize: 14, fontWeight: 800, color: "#1a1a1a", marginBottom: 6 }}>{f.t}</h3>
                <p style={{ fontSize: 12, color: "#777", lineHeight: 1.7 }}>{f.d}</p>
              </div>
            ))}
          </div>
        </div>
      </section>
      <footer style={{ padding: "24px 40px", background: "#1a1a1a", color: "#888", textAlign: "center", fontSize: 11 }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 6, marginBottom: 6 }}>{I.shield(14, "#4CAF50")}<span style={{ color: "#fff", fontWeight: 700 }}>منصة إدارة المستودعات العسكرية</span></div>
        <span>جميع الحقوق محفوظة 2026</span>
      </footer>
    </div>
  );

  /* ═══════ LOGIN ═══════ */
  if (appState === "login") return (
    <div style={{ direction: "rtl", fontFamily: "'Tajawal'", minHeight: "100vh", background: "#f7f9f7", display: "flex", alignItems: "center", justifyContent: "center" }}>
      <style>{css}</style>
      <div style={{ width: 380, background: "#fff", borderRadius: 14, padding: 36, border: "1px solid #e8e8e8", boxShadow: "0 4px 30px rgba(0,0,0,0.04)" }}>
        <div style={{ textAlign: "center", marginBottom: 28 }}>
          <div style={{ width: 50, height: 50, borderRadius: 12, background: "#e8f5e9", display: "flex", alignItems: "center", justifyContent: "center", margin: "0 auto 12px" }}>{I.shield(26, "#2e7d32")}</div>
          <h1 style={{ fontSize: 18, fontWeight: 900, color: "#1a1a1a", marginBottom: 4 }}>تسجيل الدخول</h1>
          <p style={{ fontSize: 12, color: "#999" }}>منصة إدارة المستودعات العسكرية</p>
        </div>
        {loginError && <div style={{ background: "#ffebee", border: "1px solid #ffcdd2", borderRadius: 7, padding: "8px 12px", marginBottom: 14, fontSize: 11, color: "#c62828", display: "flex", alignItems: "center", gap: 6 }}>{I.alert(14, "#c62828")} {loginError}</div>}
        <div style={{ marginBottom: 14 }}>
          <label style={{ fontSize: 11, fontWeight: 600, color: "#555", marginBottom: 5, display: "flex", alignItems: "center", gap: 5 }}>{I.user(13, "#888")} اسم المستخدم</label>
          <input value={loginForm.username} onChange={e => setLoginForm({ ...loginForm, username: e.target.value })} onKeyDown={e => e.key === "Enter" && handleLogin()} placeholder="admin" style={{ ...S.input, marginTop: 5 }} />
        </div>
        <div style={{ marginBottom: 22 }}>
          <label style={{ fontSize: 11, fontWeight: 600, color: "#555", marginBottom: 5, display: "flex", alignItems: "center", gap: 5 }}>{I.lock(13, "#888")} كلمة المرور</label>
          <input type="password" value={loginForm.password} onChange={e => setLoginForm({ ...loginForm, password: e.target.value })} onKeyDown={e => e.key === "Enter" && handleLogin()} placeholder="admin" style={{ ...S.input, marginTop: 5 }} />
        </div>
        <button onClick={handleLogin} style={{ ...S.btnP, width: "100%", justifyContent: "center", padding: 11, fontSize: 14, borderRadius: 9 }}>دخول</button>
        <div style={{ textAlign: "center", marginTop: 14 }}><span onClick={() => setAppState("landing")} style={{ fontSize: 11, color: "#2e7d32", cursor: "pointer" }}>العودة للرئيسية</span></div>
        <div style={{ textAlign: "center", marginTop: 16, padding: 10, background: "#f5f5f5", borderRadius: 7 }}><span style={{ fontSize: 10, color: "#999" }}>للتجربة: admin / admin</span></div>
      </div>
    </div>
  );

  /* ═══════ MAIN APP ═══════ */
  const NavItem = ({ icon, label, active, onClick, count }) => (
    <div onClick={onClick} style={{ display: "flex", alignItems: "center", gap: 9, padding: sideOpen ? "9px 14px" : "9px 0", cursor: "pointer", borderRadius: 7, margin: "1px 6px", background: active ? "#e8f5e9" : "transparent", borderRight: active ? "3px solid #2e7d32" : "3px solid transparent", justifyContent: sideOpen ? "flex-start" : "center" }}>
      <span style={{ minWidth: 20, display: "flex", justifyContent: "center" }}>{icon}</span>
      {sideOpen && <span style={{ fontSize: 12, fontWeight: active ? 700 : 500, color: active ? "#2e7d32" : "#555", flex: 1 }}>{label}</span>}
      {sideOpen && count > 0 && <Badge color="#c62828">{count}</Badge>}
    </div>
  );

  const Crumb = () => (
    <div style={{ display: "flex", alignItems: "center", gap: 5, fontSize: 11, flexWrap: "wrap" }}>
      <span onClick={() => goTo("home")} style={{ cursor: "pointer", color: page === "home" ? "#2e7d32" : "#888", fontWeight: page === "home" ? 700 : 400, display: "flex", alignItems: "center", gap: 3 }}>{I.home(13, page === "home" ? "#2e7d32" : "#888")} الرئيسية</span>
      {branch && <>{I.chevL(11, "#ccc")}<span onClick={() => goTo("branch", branch)} style={{ cursor: "pointer", color: !warehouse ? "#2e7d32" : "#888", fontWeight: !warehouse ? 700 : 400 }}>{BRANCHES.find(b => b.id === branch)?.name}</span></>}
      {warehouse && <>{I.chevL(11, "#ccc")}<span style={{ color: "#2e7d32", fontWeight: 700 }}>{WAREHOUSES.find(w => w.id === warehouse)?.name}</span></>}
    </div>
  );

  /* ── UNIT STATUS CARD (ATLAS style) ── */
  const UnitCard = ({ b }) => {
    const mcr = branchMCR(b.id);
    const ac = branchAlertCount(b.id);
    const readiness = mcr >= 70 ? "جاهز" : mcr >= 40 ? "متوسط" : "حرج";
    const rColor = mcr >= 70 ? "#2e7d32" : mcr >= 40 ? "#e65100" : "#c62828";
    return (
      <div className="hov-card" onClick={() => goTo("branch", b.id)} style={{ ...S.card, cursor: "pointer", padding: 0, overflow: "hidden" }}>
        <div style={{ height: 3, background: b.color }} />
        <div style={{ padding: "12px 14px" }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 10 }}>
            <div>
              <div style={{ fontSize: 13, fontWeight: 800, color: "#1a1a1a" }}>{b.name}</div>
              <div style={{ fontSize: 9, color: "#aaa", fontFamily: "'IBM Plex Sans'", letterSpacing: 0.5 }}>{b.code} — {b.nameEn}</div>
            </div>
            <span style={{ fontSize: 10, fontWeight: 700, color: rColor, padding: "3px 10px", borderRadius: 6, background: `${rColor}10`, border: `1px solid ${rColor}30` }}>{readiness}</span>
          </div>

          {WAREHOUSES.map(w => {
            const wd = data[b.id]?.[w.id]; if (!wd) return null;
            const tot = wd.items.reduce((s, i) => s + i.current, 0);
            const mx = wd.items.reduce((s, i) => s + i.max, 0);
            const p = mx > 0 ? (tot / mx) * 100 : 0;
            return (
              <div key={w.id} style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 6 }}>
                <span style={{ fontSize: 10, color: "#888", minWidth: 55, fontWeight: 600 }}>{w.name}</span>
                <div style={{ flex: 1 }}><Bar pct={p} h={6} /></div>
                <span style={{ fontSize: 10, fontWeight: 700, color: p <= 25 ? "#c62828" : "#555", minWidth: 30, textAlign: "left", fontFamily: "'IBM Plex Sans'" }}>{p.toFixed(0)}%</span>
              </div>
            );
          })}

          <div style={{ display: "flex", gap: 6, marginTop: 10 }}>
            <MetricBox label="Lead Time" value={(Math.random() * 3 + 0.5).toFixed(1)} unit="h" />
            <MetricBox label="DOS" value={(Math.random() * 10).toFixed(1)} unit="" />
            <MetricBox label="MCR" value={`${mcr}%`} unit="" color={rColor} warn={mcr < 40} />
          </div>
        </div>
      </div>
    );
  };

  /* ── SUPPLY REQUEST CARD ── */
  const RequestCard = ({ r }) => {
    const pColor = r.priority === "طوارئ" ? "#c62828" : r.priority === "عاجل" ? "#e65100" : "#2e7d32";
    return (
      <div style={{ ...S.card, padding: 12, marginBottom: 8, borderColor: r.status !== "pending" ? "#e8e8e8" : `${pColor}40`, opacity: r.status !== "pending" ? 0.5 : 1 }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 8 }}>
          <span style={{ fontSize: 10, color: "#aaa", fontFamily: "'IBM Plex Sans'", fontWeight: 600 }}>{r.id}</span>
          <span style={{ fontSize: 10, fontWeight: 700, color: pColor, background: `${pColor}10`, padding: "2px 8px", borderRadius: 4 }}>{r.priority}</span>
        </div>
        <div style={{ fontSize: 12, fontWeight: 700, color: "#1a1a1a", marginBottom: 4 }}>{r.branch.name}</div>
        <div style={{ fontSize: 11, color: "#666", marginBottom: 6 }}>
          طلب إمداد: <strong>{r.type}</strong> — الكمية: {r.quantity}
        </div>
        <div style={{ fontSize: 10, color: "#888", marginBottom: 4 }}>
          المستوى الحالي: <span style={{ color: r.currentPct <= 25 ? "#c62828" : "#555", fontWeight: 700 }}>{r.currentPct}%</span> — المسافة: {r.distance} كم
        </div>
        <div style={{ fontSize: 10, color: "#2e7d32", marginBottom: 8 }}>
          وقت التسليم المتوقع: {r.eta} ساعة
        </div>
        {r.status === "pending" ? (
          <div style={{ display: "flex", gap: 6 }}>
            <button style={{ ...S.btnP, flex: 1, justifyContent: "center", padding: 6, fontSize: 11 }} onClick={() => handleRequest(r.id, "approved")}>{I.check(12, "#fff")} موافق</button>
            <button style={{ ...S.btnD, flex: 1, justifyContent: "center", padding: 6, fontSize: 11 }} onClick={() => handleRequest(r.id, "rejected")}>{I.x(12, "#c62828")} رفض</button>
          </div>
        ) : (
          <div style={{ textAlign: "center", fontSize: 10, fontWeight: 700, color: r.status === "approved" ? "#2e7d32" : "#c62828" }}>
            {r.status === "approved" ? "تمت الموافقة" : "مرفوض"}
          </div>
        )}
      </div>
    );
  };

  /* ── MAIN DASHBOARD ── */
  const Dashboard = () => (
    <div style={{ display: "flex", gap: 16, height: "100%" }}>
      {/* Center content */}
      <div style={{ flex: 1, overflow: "auto", paddingLeft: 16 }}>
        {/* Top stats bar */}
        <div style={{ display: "flex", gap: 10, marginBottom: 16, flexWrap: "wrap" }}>
          {BRANCHES.map(b => {
            const mcr = branchMCR(b.id);
            return (
              <div key={b.id} style={{ display: "flex", alignItems: "center", gap: 8, background: "#fff", border: "1px solid #eee", borderRadius: 8, padding: "6px 14px" }}>
                <span style={{ fontSize: 10, color: "#888", fontWeight: 600 }}>{b.code}</span>
                <span style={{ fontSize: 11, fontWeight: 800, color: mcr >= 70 ? "#2e7d32" : mcr >= 40 ? "#e65100" : "#c62828", fontFamily: "'IBM Plex Sans'" }}>{mcr}%</span>
                <span style={{ fontSize: 9, color: "#bbb" }}>MCR</span>
              </div>
            );
          })}
          <div style={{ display: "flex", alignItems: "center", gap: 6, background: "#fff", border: "1px solid #eee", borderRadius: 8, padding: "6px 14px" }}>
            {I.alert(13, "#c62828")}
            <span style={{ fontSize: 11, fontWeight: 700, color: "#c62828", fontFamily: "'IBM Plex Sans'" }}>{stats.low}</span>
            <span style={{ fontSize: 9, color: "#888" }}>تنبيهات</span>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 6, background: "#fff", border: "1px solid #eee", borderRadius: 8, padding: "6px 14px" }}>
            {I.inbox(13, "#e65100")}
            <span style={{ fontSize: 11, fontWeight: 700, color: "#e65100", fontFamily: "'IBM Plex Sans'" }}>{pendingReqs.length}</span>
            <span style={{ fontSize: 9, color: "#888" }}>طلبات معلقة</span>
          </div>
        </div>

        {/* Unit cards grid */}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(300px, 1fr))", gap: 14, marginBottom: 20 }}>
          {BRANCHES.map(b => <UnitCard key={b.id} b={b} />)}
        </div>

        {/* Alerts table */}
        {itemAlerts.length > 0 && (
          <div style={{ ...S.card, padding: 0, marginBottom: 16 }}>
            <div style={{ padding: "12px 16px", borderBottom: "1px solid #f0f0f0", display: "flex", alignItems: "center", gap: 6 }}>
              {I.alert(16, "#c62828")}
              <span style={{ fontSize: 13, fontWeight: 800, color: "#c62828" }}>تنبيهات نقص المخزون</span>
              <Badge>{itemAlerts.length}</Badge>
            </div>
            <div style={{ maxHeight: 240, overflow: "auto" }}>
              <table style={{ width: "100%", borderCollapse: "collapse", direction: "rtl" }}>
                <thead><tr style={{ background: "#fafafa" }}>
                  {["الجهة", "المستودع", "البند", "الكمية", "النسبة"].map((h, i) => <th key={i} style={{ ...S.th, textAlign: i > 2 ? "center" : "right" }}>{h}</th>)}
                </tr></thead>
                <tbody>
                  {itemAlerts.slice(0, 10).map((a, i) => (
                    <tr key={i} className="hov" onClick={() => goTo("warehouse", a.branch.id, a.warehouse.id)} style={{ cursor: "pointer" }}>
                      <td style={S.td}>{a.branch.name}</td>
                      <td style={S.td}>{a.warehouse.name}</td>
                      <td style={{ ...S.td, fontWeight: 600, color: "#1a1a1a" }}>{a.item.name}</td>
                      <td style={{ ...S.td, textAlign: "center", fontFamily: "'IBM Plex Sans'", fontWeight: 600 }}><span style={{ color: "#c62828" }}>{a.item.current}</span> / {a.item.max}</td>
                      <td style={{ ...S.td, textAlign: "center" }}><Badge color={a.pct <= 0.1 ? "#c62828" : "#e65100"}>{(a.pct * 100).toFixed(0)}%</Badge></td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        )}

        {envAlerts.length > 0 && (
          <div style={{ ...S.card, padding: 0 }}>
            <div style={{ padding: "12px 16px", borderBottom: "1px solid #f0f0f0", display: "flex", alignItems: "center", gap: 6 }}>
              {I.temp(16, "#e65100")}
              <span style={{ fontSize: 13, fontWeight: 800, color: "#e65100" }}>تنبيهات بيئية</span>
              <Badge color="#e65100">{envAlerts.length}</Badge>
            </div>
            {envAlerts.map((a, i) => (
              <div key={i} className="hov" onClick={() => goTo("warehouse", a.branch.id, a.warehouse.id)} style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "10px 16px", borderBottom: "1px solid #f5f5f5", cursor: "pointer", fontSize: 12 }}>
                <span>{a.branch.name} — {a.warehouse.name}</span>
                <span style={{ color: "#c62828", fontWeight: 600, fontFamily: "'IBM Plex Sans'" }}>
                  {a.type === "temp" ? `${a.value}° (${a.ideal[0]}°-${a.ideal[1]}°)` : `${a.value}% (${a.ideal[0]}%-${a.ideal[1]}%)`}
                </span>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Right sidebar - Supply Requests */}
      <div style={{ width: 280, minWidth: 280, overflow: "auto", borderRight: "1px solid #eee", paddingRight: 16 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 12 }}>
          {I.inbox(16, "#2e7d32")}
          <span style={{ fontSize: 13, fontWeight: 800, color: "#1a1a1a" }}>طلبات الإمداد</span>
          {pendingReqs.length > 0 && <Badge>{pendingReqs.length}</Badge>}
        </div>
        {requests.map(r => <RequestCard key={r.id} r={r} />)}
      </div>
    </div>
  );

  /* ── Branch View ── */
  const BranchView = () => {
    const b = BRANCHES.find(x => x.id === branch); if (!b) return null;
    const mcr = branchMCR(b.id);
    const readiness = mcr >= 70 ? "جاهز" : mcr >= 40 ? "متوسط" : "حرج";
    const rColor = mcr >= 70 ? "#2e7d32" : mcr >= 40 ? "#e65100" : "#c62828";
    return (
      <div>
        <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 20 }}>
          <div style={{ width: 48, height: 48, borderRadius: 12, background: `${b.color}10`, display: "flex", alignItems: "center", justifyContent: "center" }}>{I.target(24, b.color)}</div>
          <div style={{ flex: 1 }}>
            <h2 style={{ fontSize: 20, fontWeight: 900, color: "#1a1a1a", margin: 0 }}>{b.name}</h2>
            <p style={{ fontSize: 10, color: "#999", fontFamily: "'IBM Plex Sans'", letterSpacing: 1 }}>{b.code} — {b.nameEn}</p>
          </div>
          <span style={{ fontSize: 12, fontWeight: 700, color: rColor, background: `${rColor}10`, padding: "6px 16px", borderRadius: 8, border: `1px solid ${rColor}30` }}>الجاهزية: {readiness} ({mcr}%)</span>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(300px, 1fr))", gap: 14 }}>
          {WAREHOUSES.map(w => {
            const wd = data[b.id]?.[w.id]; if (!wd) return null;
            const tot = wd.items.reduce((s, i) => s + i.current, 0);
            const mx = wd.items.reduce((s, i) => s + i.max, 0);
            const p = mx > 0 ? (tot / mx) * 100 : 0;
            const lowItems = wd.items.filter(i => i.current / i.max <= TH);
            const wi = WAREHOUSES.find(x => x.id === w.id);
            const tW = wd.temp < wi.idealTemp[0] || wd.temp > wi.idealTemp[1];
            const hW = wd.humidity < wi.idealHumidity[0] || wd.humidity > wi.idealHumidity[1];
            return (
              <div key={w.id} className="hov-card" onClick={() => goTo("warehouse", branch, w.id)} style={{ ...S.card, cursor: "pointer", padding: 0, overflow: "hidden" }}>
                <div style={{ height: 3, background: w.color }} />
                <div style={{ padding: 16 }}>
                  <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 14 }}>
                    <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                      <div style={{ width: 38, height: 38, borderRadius: 8, background: `${w.color}10`, display: "flex", alignItems: "center", justifyContent: "center" }}>{I.warehouse(18, w.color)}</div>
                      <div><div style={{ fontSize: 13, fontWeight: 800, color: "#1a1a1a" }}>{w.name}</div><div style={{ fontSize: 9, color: "#aaa", fontFamily: "'IBM Plex Sans'" }}>{w.nameEn} — {wd.items.length} ITEMS</div></div>
                    </div>
                    {lowItems.length > 0 && <Badge>{lowItems.length}</Badge>}
                  </div>
                  <div style={{ marginBottom: 14 }}>
                    <div style={{ display: "flex", justifyContent: "space-between", fontSize: 10, color: "#888", marginBottom: 5 }}><span>نسبة الامتلاء</span><span style={{ fontWeight: 800, color: p <= 25 ? "#c62828" : "#2e7d32", fontFamily: "'IBM Plex Sans'" }}>{p.toFixed(1)}%</span></div>
                    <Bar pct={p} />
                  </div>
                  <div style={{ display: "flex", gap: 12, justifyContent: "center", marginBottom: 10 }}>
                    <div style={{ textAlign: "center" }}>
                      <div style={{ display: "flex", alignItems: "center", gap: 3, justifyContent: "center" }}>{I.temp(14, tW ? "#c62828" : "#1565c0")}<span style={{ fontSize: 14, fontWeight: 700, color: tW ? "#c62828" : "#333", fontFamily: "'IBM Plex Sans'" }}>{wd.temp}°</span></div>
                      <div style={{ fontSize: 9, color: "#aaa" }}>{wi.idealTemp[0]}°-{wi.idealTemp[1]}°</div>
                    </div>
                    <div style={{ width: 1, background: "#eee" }} />
                    <div style={{ textAlign: "center" }}>
                      <div style={{ display: "flex", alignItems: "center", gap: 3, justifyContent: "center" }}>{I.drop(14, hW ? "#c62828" : "#0097a7")}<span style={{ fontSize: 14, fontWeight: 700, color: hW ? "#c62828" : "#333", fontFamily: "'IBM Plex Sans'" }}>{wd.humidity}%</span></div>
                      <div style={{ fontSize: 9, color: "#aaa" }}>{wi.idealHumidity[0]}%-{wi.idealHumidity[1]}%</div>
                    </div>
                  </div>
                  <div style={{ fontSize: 10, color: "#aaa", textAlign: "center", fontFamily: "'IBM Plex Sans'" }}>{tot.toLocaleString()} / {mx.toLocaleString()}</div>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    );
  };

  /* ── Warehouse Detail ── */
  const WarehouseView = () => {
    const b = BRANCHES.find(x => x.id === branch);
    const w = WAREHOUSES.find(x => x.id === warehouse);
    if (!b || !w) return null;
    const wd = data[b.id]?.[w.id]; if (!wd) return null;
    const wi = WAREHOUSES.find(x => x.id === w.id);
    const tW = wd.temp < wi.idealTemp[0] || wd.temp > wi.idealTemp[1];
    const hW = wd.humidity < wi.idealHumidity[0] || wd.humidity > wi.idealHumidity[1];
    const categories = ["all", ...new Set(wd.items.map(i => i.category))];
    let items = filterCat === "all" ? wd.items : wd.items.filter(i => i.category === filterCat);
    if (search) items = items.filter(i => i.name.includes(search) || i.category.includes(search));
    if (sortBy === "pct") items = [...items].sort((a, b) => (a.current / a.max) - (b.current / b.max));
    else if (sortBy === "current") items = [...items].sort((a, b) => a.current - b.current);
    else items = [...items].sort((a, b) => a.name.localeCompare(b.name, "ar"));

    return (
      <div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 12, marginBottom: 16 }}>
          <div style={{ ...S.card, display: "flex", alignItems: "center", gap: 12 }}>
            <div style={{ width: 40, height: 40, borderRadius: 8, background: `${w.color}10`, display: "flex", alignItems: "center", justifyContent: "center" }}>{I.warehouse(20, w.color)}</div>
            <div><div style={{ fontSize: 13, fontWeight: 800, color: "#1a1a1a" }}>{w.name}</div><div style={{ fontSize: 10, color: "#888" }}>{b.name}</div></div>
          </div>
          <div style={{ ...S.card, display: "flex", alignItems: "center", justifyContent: "center", gap: 16 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 4 }}>{I.temp(16, tW ? "#c62828" : "#1565c0")}<span style={{ fontSize: 16, fontWeight: 700, color: tW ? "#c62828" : "#333", fontFamily: "'IBM Plex Sans'" }}>{wd.temp}°</span><span style={{ fontSize: 9, color: "#aaa" }}>({wi.idealTemp[0]}°-{wi.idealTemp[1]}°)</span></div>
            <div style={{ width: 1, height: 20, background: "#eee" }} />
            <div style={{ display: "flex", alignItems: "center", gap: 4 }}>{I.drop(16, hW ? "#c62828" : "#0097a7")}<span style={{ fontSize: 16, fontWeight: 700, color: hW ? "#c62828" : "#333", fontFamily: "'IBM Plex Sans'" }}>{wd.humidity}%</span><span style={{ fontSize: 9, color: "#aaa" }}>({wi.idealHumidity[0]}%-{wi.idealHumidity[1]}%)</span></div>
          </div>
          <div style={{ ...S.card, display: "flex", alignItems: "center", gap: 10 }}>
            <div><div style={{ fontSize: 10, color: "#999" }}>إجمالي المخزون</div><div style={{ fontSize: 20, fontWeight: 900, color: "#1a1a1a", fontFamily: "'IBM Plex Sans'" }}>{wd.items.reduce((s, i) => s + i.current, 0).toLocaleString()}</div><div style={{ fontSize: 9, color: "#aaa" }}>من {wd.items.reduce((s, i) => s + i.max, 0).toLocaleString()}</div></div>
          </div>
        </div>

        <div style={{ display: "flex", gap: 8, marginBottom: 14, flexWrap: "wrap", alignItems: "center" }}>
          <div style={{ position: "relative", flex: 1, minWidth: 180 }}><input value={search} onChange={e => setSearch(e.target.value)} placeholder="بحث..." style={{ ...S.input, paddingRight: 32 }} /><span style={{ position: "absolute", right: 10, top: "50%", transform: "translateY(-50%)" }}>{I.search(13, "#bbb")}</span></div>
          <select value={filterCat} onChange={e => setFilterCat(e.target.value)} style={{ ...S.input, width: "auto", minWidth: 110, cursor: "pointer" }}>{categories.map(c => <option key={c} value={c}>{c === "all" ? "جميع الفئات" : c}</option>)}</select>
          <select value={sortBy} onChange={e => setSortBy(e.target.value)} style={{ ...S.input, width: "auto", minWidth: 110, cursor: "pointer" }}><option value="name">الاسم</option><option value="pct">النسبة</option><option value="current">الكمية</option></select>
          <button style={S.btnP} onClick={() => setShowAdd(true)}>{I.plus(13, "#fff")} إضافة بند</button>
        </div>

        {showAdd && (
          <div style={{ ...S.card, marginBottom: 14, borderColor: "#c8e6c9" }}>
            <div style={{ fontSize: 12, fontWeight: 700, color: "#2e7d32", marginBottom: 10, display: "flex", alignItems: "center", gap: 5 }}>{I.plus(14, "#2e7d32")} إضافة بند جديد</div>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(140px, 1fr))", gap: 8 }}>
              <input style={S.input} placeholder="اسم البند" value={newItem.name} onChange={e => setNewItem({ ...newItem, name: e.target.value })} />
              <input style={S.input} placeholder="الفئة" value={newItem.category} onChange={e => setNewItem({ ...newItem, category: e.target.value })} />
              <input style={S.input} placeholder="الوحدة" value={newItem.unit} onChange={e => setNewItem({ ...newItem, unit: e.target.value })} />
              <input style={S.input} placeholder="السعة القصوى" type="number" value={newItem.max} onChange={e => setNewItem({ ...newItem, max: e.target.value })} />
              <input style={S.input} placeholder="الكمية الحالية" type="number" value={newItem.current} onChange={e => setNewItem({ ...newItem, current: e.target.value })} />
            </div>
            <div style={{ display: "flex", gap: 6, marginTop: 10 }}><button style={S.btnP} onClick={() => addNewItem(branch, warehouse)}>{I.check(12, "#fff")} حفظ</button><button style={S.btnG} onClick={() => setShowAdd(false)}>إلغاء</button></div>
          </div>
        )}

        <div style={{ ...S.card, padding: 0, overflow: "hidden" }}>
          <div style={{ overflowX: "auto" }}>
            <table style={{ width: "100%", borderCollapse: "collapse", direction: "rtl", minWidth: 700 }}>
              <thead><tr style={{ background: "#fafafa" }}>
                {["#", "", "البند", "الفئة", "الوحدة", "الحالي / الأقصى", "المخزون", "إجراءات"].map((h, i) => <th key={i} style={{ ...S.th, textAlign: i > 4 ? "center" : "right", width: i < 2 ? 35 : "auto" }}>{h}</th>)}
              </tr></thead>
              <tbody>
                {items.map((item, idx) => {
                  const p = (item.current / item.max) * 100; const low = p <= 25; const crit = p <= 10;
                  return (
                    <tr key={item.id} className="hov" style={{ background: crit ? "#fff5f5" : low ? "#fffbf0" : "#fff" }}>
                      <td style={{ ...S.td, color: "#aaa", fontFamily: "'IBM Plex Sans'", fontWeight: 600 }}>{idx + 1}</td>
                      <td style={S.td}><Dot pct={p} /></td>
                      <td style={{ ...S.td, fontWeight: 700, color: "#1a1a1a" }}>{item.name}{low && <span style={{ marginRight: 6, fontSize: 9, padding: "2px 7px", borderRadius: 5, background: crit ? "#ffebee" : "#fff3e0", color: crit ? "#c62828" : "#e65100", fontWeight: 700 }}>{crit ? "حرج" : "منخفض"}</span>}</td>
                      <td style={{ ...S.td, color: "#888", fontSize: 10 }}>{item.category}</td>
                      <td style={{ ...S.td, color: "#888" }}>{item.unit}</td>
                      <td style={{ ...S.td, textAlign: "center" }}>
                        {editId === item.id ? (
                          <div style={{ display: "flex", gap: 3, justifyContent: "center", alignItems: "center" }}>
                            <input type="number" value={editVal} onChange={e => setEditVal(e.target.value)} onKeyDown={e => { if (e.key === "Enter") updateItem(branch, warehouse, item.id, editVal); if (e.key === "Escape") setEditId(null); }} style={{ ...S.input, width: 70, padding: "5px 7px", textAlign: "center" }} autoFocus />
                            <button style={{ ...S.btnG, padding: "5px 8px" }} onClick={() => updateItem(branch, warehouse, item.id, editVal)}>{I.check(12, "#2e7d32")}</button>
                            <button style={{ ...S.btnD, padding: "5px 7px" }} onClick={() => setEditId(null)}>{I.x(12, "#c62828")}</button>
                          </div>
                        ) : (
                          <span style={{ fontFamily: "'IBM Plex Sans'", fontWeight: 600 }}><span style={{ color: low ? "#c62828" : "#1a1a1a" }}>{item.current.toLocaleString()}</span><span style={{ color: "#ccc" }}> / {item.max.toLocaleString()}</span></span>
                        )}
                      </td>
                      <td style={{ ...S.td, minWidth: 110 }}><div style={{ display: "flex", alignItems: "center", gap: 5 }}><Bar pct={p} h={5} /><span style={{ fontSize: 10, fontWeight: 700, color: low ? "#c62828" : "#888", minWidth: 28, textAlign: "left", fontFamily: "'IBM Plex Sans'" }}>{p.toFixed(0)}%</span></div></td>
                      <td style={{ ...S.td, textAlign: "center", whiteSpace: "nowrap" }}>
                        <button style={{ ...S.btnG, padding: "4px 8px", marginLeft: 3 }} onClick={() => { setEditId(item.id); setEditVal(String(item.current)); }}>{I.edit(12, "#2e7d32")}</button>
                        <button style={{ ...S.btnD, padding: "4px 8px" }} onClick={() => deleteItem(branch, warehouse, item.id)}>{I.trash(12, "#c62828")}</button>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
          {items.length === 0 && <div style={{ padding: 30, textAlign: "center", color: "#aaa", fontSize: 12 }}>لا توجد نتائج</div>}
        </div>
      </div>
    );
  };

  const LogsView = () => (
    <div>
      <h2 style={{ fontSize: 16, fontWeight: 800, color: "#1a1a1a", marginBottom: 14, display: "flex", alignItems: "center", gap: 6 }}>{I.log(18, "#2e7d32")} سجل العمليات</h2>
      {logs.length === 0 ? <div style={{ ...S.card, textAlign: "center", padding: 30, color: "#aaa", fontSize: 12 }}>لا توجد عمليات مسجلة</div> : (
        <div style={{ ...S.card, padding: 0 }}>
          {logs.map((l, i) => (
            <div key={i} className="hov" style={{ display: "flex", justifyContent: "space-between", padding: "10px 16px", borderBottom: "1px solid #f5f5f5", fontSize: 12 }}>
              <span style={{ color: "#333" }}>{l.action}</span>
              <span style={{ color: "#aaa", fontSize: 10, fontFamily: "'IBM Plex Sans'", direction: "ltr" }}>{l.time} — {l.date}</span>
            </div>
          ))}
        </div>
      )}
    </div>
  );

  return (
    <div style={{ direction: "rtl", fontFamily: "'Tajawal'", minHeight: "100vh", background: "#f5f6f5", display: "flex", overflow: "hidden" }}>
      <style>{css}</style>

      {toast && <div style={{ position: "fixed", top: 14, left: "50%", transform: "translateX(-50%)", zIndex: 9999, background: toast.type === "success" ? "#2e7d32" : "#c62828", color: "#fff", padding: "10px 24px", borderRadius: 8, fontSize: 12, fontWeight: 700, fontFamily: "'Tajawal'", boxShadow: "0 4px 20px rgba(0,0,0,0.12)" }}>{toast.msg}</div>}

      {/* Sidebar */}
      <div style={{ width: sideOpen ? 210 : 54, minWidth: sideOpen ? 210 : 54, height: "100vh", background: "#fff", borderLeft: "1px solid #eee", display: "flex", flexDirection: "column", overflow: "hidden" }}>
        <div style={{ padding: sideOpen ? "14px 14px 10px" : "14px 6px 10px", borderBottom: "1px solid #eee", display: "flex", alignItems: "center", gap: 8, justifyContent: sideOpen ? "flex-start" : "center" }}>
          <div style={{ width: 30, height: 30, borderRadius: 7, background: "#e8f5e9", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>{I.shield(16, "#2e7d32")}</div>
          {sideOpen && <div><div style={{ fontSize: 11, fontWeight: 900, color: "#1a1a1a", lineHeight: 1.2 }}>إدارة المستودعات</div><div style={{ fontSize: 7, color: "#999", fontFamily: "'IBM Plex Sans'", letterSpacing: 1.5 }}>WMS v2.0</div></div>}
        </div>
        <div style={{ padding: "6px 0", flex: 1, overflow: "auto" }}>
          <NavItem icon={I.home(16, page === "home" ? "#2e7d32" : "#888")} label="لوحة التحكم" active={page === "home"} onClick={() => goTo("home")} count={stats.low + stats.envW} />
          {sideOpen && <div style={{ padding: "10px 16px 4px", fontSize: 8, color: "#bbb", letterSpacing: 1.5, fontWeight: 700 }}>الجهات</div>}
          {BRANCHES.map(b => <NavItem key={b.id} icon={I.target(16, branch === b.id && page !== "home" && page !== "logs" ? "#2e7d32" : "#888")} label={b.name} active={branch === b.id && page !== "home" && page !== "logs"} onClick={() => goTo("branch", b.id)} count={branchAlertCount(b.id)} />)}
          {sideOpen && <div style={{ padding: "10px 16px 4px", fontSize: 8, color: "#bbb", letterSpacing: 1.5, fontWeight: 700 }}>النظام</div>}
          <NavItem icon={I.inbox(16, page === "requests" ? "#2e7d32" : "#888")} label="طلبات الإمداد" active={page === "requests"} onClick={() => { setPage("requests"); setBranch(null); setWarehouse(null); }} count={pendingReqs.length} />
          <NavItem icon={I.log(16, page === "logs" ? "#2e7d32" : "#888")} label="سجل العمليات" active={page === "logs"} onClick={() => { setPage("logs"); setBranch(null); setWarehouse(null); }} />
        </div>
        <div style={{ borderTop: "1px solid #eee" }}>
          <div onClick={() => setSideOpen(!sideOpen)} style={{ display: "flex", alignItems: "center", justifyContent: "center", padding: 8, cursor: "pointer" }}>{I.menu(16, "#888")}</div>
        </div>
        <div style={{ padding: "8px 10px", borderTop: "1px solid #eee", display: "flex", alignItems: "center", gap: 6 }}>
          <div style={{ width: 26, height: 26, borderRadius: "50%", background: "#e8f5e9", display: "flex", alignItems: "center", justifyContent: "center" }}>{I.user(12, "#2e7d32")}</div>
          {sideOpen && <><div style={{ flex: 1 }}><div style={{ fontSize: 10, fontWeight: 700, color: "#333" }}>المشرف</div></div><span onClick={() => { setAppState("landing"); setPage("home"); setBranch(null); setWarehouse(null); }} style={{ cursor: "pointer", fontSize: 9, color: "#c62828", fontWeight: 600 }}>خروج</span></>}
        </div>
      </div>

      {/* Main */}
      <div style={{ flex: 1, height: "100vh", overflow: "hidden", display: "flex", flexDirection: "column" }}>
        <div style={{ height: 48, background: "#fff", borderBottom: "1px solid #eee", display: "flex", alignItems: "center", justifyContent: "space-between", padding: "0 18px", flexShrink: 0 }}>
          <Crumb />
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <span style={{ fontSize: 11, fontFamily: "'IBM Plex Sans'", color: "#2e7d32", fontWeight: 600, direction: "ltr", background: "#e8f5e9", padding: "3px 10px", borderRadius: 5 }}>{time.toLocaleTimeString("en-US", { hour12: false })}</span>
            <div style={{ display: "flex", alignItems: "center", gap: 4, padding: "3px 10px", borderRadius: 5, border: "1px solid #eee" }}>{I.bell(14, alerts.length > 0 ? "#c62828" : "#888")}{alerts.length > 0 && <Badge>{alerts.length}</Badge>}</div>
          </div>
        </div>
        <div style={{ flex: 1, overflow: "auto", padding: 18 }}>
          {page === "home" && <Dashboard />}
          {page === "branch" && <BranchView />}
          {page === "warehouse" && <WarehouseView />}
          {page === "logs" && <LogsView />}
          {page === "requests" && (
            <div>
              <h2 style={{ fontSize: 16, fontWeight: 800, color: "#1a1a1a", marginBottom: 14, display: "flex", alignItems: "center", gap: 6 }}>{I.inbox(18, "#2e7d32")} طلبات الإمداد</h2>
              <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(280px, 1fr))", gap: 12 }}>
                {requests.map(r => <RequestCard key={r.id} r={r} />)}
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
