/* Otmix Dashboard — admin overview */
const { useState, useEffect, useMemo, useRef } = React;

const I = ({ d, s = 16, sw = 1.8 }) => (
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={sw} strokeLinecap="round" strokeLinejoin="round">{d}</svg>
);
const ic = {
  home: <I d={<><path d="M3 12L12 3l9 9"/><path d="M5 10v10h14V10"/></>}/>,
  bot: <I d={<><rect x="4" y="8" width="16" height="12" rx="2"/><path d="M12 4v4"/><circle cx="9" cy="14" r="1"/><circle cx="15" cy="14" r="1"/><path d="M9 18h6"/></>}/>,
  ops: <I d={<><path d="M4 4h6v6H4z"/><path d="M14 4h6v6h-6z"/><path d="M4 14h6v6H4z"/><path d="M14 14h6v6h-6z"/></>}/>,
  users: <I d={<><circle cx="9" cy="8" r="3"/><path d="M3 20c0-3 3-5 6-5s6 2 6 5"/><circle cx="17" cy="8" r="2"/><path d="M21 18c0-2-1.5-3.5-4-4"/></>}/>,
  reports: <I d={<><path d="M4 20V8"/><path d="M10 20V4"/><path d="M16 20v-8"/><path d="M22 20H2"/></>}/>,
  card: <I d={<><rect x="3" y="6" width="18" height="13" rx="2"/><path d="M3 10h18"/></>}/>,
  plug: <I d={<><path d="M9 7V3M15 7V3"/><rect x="6" y="7" width="12" height="7" rx="2"/><path d="M12 14v4"/><path d="M9 21h6"/></>}/>,
  cog: <I d={<><circle cx="12" cy="12" r="3"/><path d="M12 2v3M12 19v3M2 12h3M19 12h3M5 5l2 2M17 17l2 2M5 19l2-2M17 7l2-2"/></>}/>,
  search: <I d={<><circle cx="11" cy="11" r="7"/><path d="M21 21l-4-4"/></>}/>,
  bell: <I d={<><path d="M6 9a6 6 0 1112 0v6l2 3H4l2-3z"/><path d="M10 21h4"/></>}/>,
  bolt: <I d={<><path d="M13 3L4 14h7l-1 7 9-11h-7z"/></>}/>,
  chev: <I d={<polyline points="6 9 12 15 18 9"/>}/>,
  chevR: <I d={<polyline points="9 18 15 12 9 6"/>}/>,
  arrow: <I d={<><path d="M5 12h14"/><path d="M13 5l7 7-7 7"/></>}/>,
  arrowL: <I d={<><path d="M19 12H5"/><path d="M11 5l-7 7 7 7"/></>}/>,
  plus: <I d={<><path d="M12 5v14M5 12h14"/></>}/>,
  filter: <I d={<><path d="M3 5h18l-7 9v6l-4-2v-4z"/></>}/>,
  download: <I d={<><path d="M12 3v12"/><path d="M7 10l5 5 5-5"/><path d="M5 21h14"/></>}/>,
  more: <I d={<><circle cx="5" cy="12" r="1.5"/><circle cx="12" cy="12" r="1.5"/><circle cx="19" cy="12" r="1.5"/></>}/>,
  eye: <I d={<><path d="M2 12s4-7 10-7 10 7 10 7-4 7-10 7S2 12 2 12z"/><circle cx="12" cy="12" r="3"/></>}/>,
  edit: <I d={<><path d="M3 21l4-1 11-11-3-3L4 17l-1 4z"/></>}/>,
  sun: <I d={<><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M2 12h2M20 12h2M5 5l1.5 1.5M17.5 17.5L19 19M5 19l1.5-1.5M17.5 6.5L19 5"/></>}/>,
  spark: <I d={<><path d="M12 3l2 5 5 1-4 4 1 6-4-3-4 3 1-6-4-4 5-1z"/></>}/>,
  alert: <I d={<><path d="M12 3l10 17H2z"/><path d="M12 10v4M12 18v.01"/></>}/>,
  cash: <I d={<><rect x="3" y="6" width="18" height="12" rx="2"/><circle cx="12" cy="12" r="2.5"/></>}/>,
  flame: <I d={<><path d="M12 3c1 4 5 5 5 10a5 5 0 11-10 0c0-3 2-3 2-7 2 1 3 2 3 4 0-3 0-5 0-7z"/></>}/>,
};

const AGENTS = [
  { code:"P1", name:"الذمم الدائنة", icon:"AP", status:"live", kpi:"١٬٢٤٧", unit:"فاتورة هذا الأسبوع", spark:[8,11,9,14,12,18,17] },
  { code:"P2", name:"الطلبات", icon:"OR", status:"live", kpi:"٤٢٣", unit:"طلب اليوم", spark:[10,12,15,11,18,22,28] },
  { code:"P3", name:"السمعة", icon:"RP", status:"live", kpi:"٨٩", unit:"تقييم تم الرد", spark:[5,8,6,9,7,11,10] },
  { code:"P4", name:"المطابقة", icon:"RC", status:"warn", kpi:"٣ استثناءات", unit:"تحتاج مراجعة", spark:[14,12,15,11,9,7,3] },
  { code:"P5", name:"الرواتب", icon:"PR", status:"idle", kpi:"٢٤٨", unit:"موظف · جاهز", spark:[6,6,6,6,6,6,6] },
  { code:"P6", name:"التوظيف", icon:"TL", status:"live", kpi:"٥٧", unit:"سيرة فُرزت", spark:[3,5,8,7,11,9,13] },
  { code:"P7", name:"العقود", icon:"CT", status:"live", kpi:"١٢", unit:"عقد قيد المراجعة", spark:[4,6,5,7,8,10,9] },
  { code:"P8", name:"التسويق", icon:"MK", status:"live", kpi:"٣٤", unit:"محتوى نُشر", spark:[7,9,11,10,13,15,14] },
  { code:"P9", name:"المعرفة", icon:"KN", status:"live", kpi:"٢٬٨٤٠", unit:"محادثة هذا الأسبوع", spark:[18,22,19,25,28,32,30] },
];

const KPIS = [
  { lbl:"الفواتير المعالجة", v:"١٢٬٨٤٧", delta:"+12.4%", unit:"", spark:[12,15,14,18,17,22,21,26,28,30,29,34], dn:false },
  { lbl:"الوكلاء النشطون", v:"٨", small:"/٩", delta:"+1", unit:"", spark:[7,7,7,8,8,8,8,8,8,8,8,8], dn:false },
  { lbl:"التوفير الشهري", v:"٤٨٬٢٩٠", small:"ر.س", delta:"+18%", spark:[20,22,25,24,28,30,33,35,38,42,45,48], dn:false },
  { lbl:"متوسط زمن المعالجة", v:"٨", small:"دقائق", delta:"-22%", spark:[18,17,15,14,13,12,11,10,9,9,8,8], dn:true },
];

const ACTIVITY = [
  { id:"#OPS-48291", type:"فاتورة", agent:"P1 · الذمم", agentColor:"AP", amt:"٤٬٨٢٠ ر.س", status:"معالج", sk:"ok", time:"قبل ٢ د" },
  { id:"#ORD-12847", type:"طلب", agent:"P2 · الطلبات", agentColor:"OR", amt:"١٥٦ ر.س", status:"معالج", sk:"ok", time:"قبل ٤ د" },
  { id:"#REC-00428", type:"مطابقة", agent:"P4 · المطابقة", agentColor:"RC", amt:"٢٤٬٣٤٠ ر.س", status:"استثناء", sk:"exc", time:"قبل ٧ د" },
  { id:"#KNW-92041", type:"محادثة", agent:"P9 · المعرفة", agentColor:"KN", amt:"—", status:"معالج", sk:"ok", time:"قبل ١١ د" },
  { id:"#OPS-48289", type:"فاتورة", agent:"P1 · الذمم", agentColor:"AP", amt:"٢٬١٤٠ ر.س", status:"قيد المراجعة", sk:"rev", time:"قبل ١٤ د" },
  { id:"#TLT-04812", type:"سيرة ذاتية", agent:"P6 · التوظيف", agentColor:"TL", amt:"—", status:"معالج", sk:"ok", time:"قبل ١٨ د" },
  { id:"#REP-22841", type:"تقييم", agent:"P3 · السمعة", agentColor:"RP", amt:"⭐ ٤", status:"معالج", sk:"ok", time:"قبل ٢٢ د" },
  { id:"#CTR-01294", type:"عقد", agent:"P7 · العقود", agentColor:"CT", amt:"خطر متوسط", status:"قيد المراجعة", sk:"rev", time:"قبل ٢٧ د" },
];

const INSIGHTS = [
  { kind:"g", ico:ic.flame, ev:<><b>وكيل الفواتير</b> اكتشف ١٢ فاتورة مكررة من Vendor X هذا الأسبوع. <b style={{color:"var(--green-dim)"}}>وفّر ٤٬٨٠٠ ر.س</b>.</>, time:"قبل ٤ د", tag:"ذمم دائنة", act:"مراجعة" },
  { kind:"y", ico:ic.alert, ev:<><b>المطابقة البنكية</b> سجّلت ٣ استثناءات في حساب الراجحي تحتاج موافقة يدوية.</>, time:"قبل ١٢ د", tag:"مطابقة", act:"اعتماد" },
  { kind:"g", ico:ic.cash, ev:<><b>الطلبات</b> رفعت متوسط القيمة من <b>٤٢ ر.س</b> إلى <b>٥٨ ر.س</b> عبر بيع تكميلي تلقائي.</>, time:"قبل ٢٥ د", tag:"طلبات", act:"عرض" },
  { kind:"b", ico:ic.spark, ev:<><b>المعرفة</b> أجاب على ٢٬٨٤٠ سؤال هذا الأسبوع · ٩٤٪ بثقة عالية بدون تصعيد.</>, time:"قبل ساعة", tag:"معرفة", act:"عرض" },
  { kind:"r", ico:ic.alert, ev:<><b>الرواتب</b> · ٣ موظفين لم يكتمل تسجيلهم في GOSI قبل تنفيذ راتب الشهر.</>, time:"قبل ٢ س", tag:"رواتب", act:"إصلاح" },
];

/* ---------- Sparkline (mini) ---------- */
function Spark({ data, color = "currentColor", h = 30, fill = false }) {
  const w = 100;
  const max = Math.max(...data); const min = Math.min(...data);
  const range = Math.max(1, max - min);
  const pts = data.map((v, i) => [(i/(data.length-1))*w, h - ((v-min)/range)*(h-4) - 2]);
  const d = pts.map((p,i) => (i===0?"M":"L") + p[0].toFixed(1) + " " + p[1].toFixed(1)).join(" ");
  return (
    <svg viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none" style={{width:"100%",height:h,display:"block"}}>
      {fill && <path d={d + ` L ${w} ${h} L 0 ${h} Z`} fill={color} opacity={0.12}/>}
      <path d={d} fill="none" stroke={color} strokeWidth={1.6} strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
}

/* ---------- Big Chart ---------- */
function BigChart({ tab }) {
  const datasets = {
    invoices: [180,210,260,240,310,340,380,360,420,440,490,520,540,580,610,640,670,690,710,750,780,810,800,860,890,920,940,970,1010,1050],
    orders:   [80,95,110,140,160,180,210,240,260,280,310,340,360,390,420,460,490,510,540,580,610,640,680,720,760,800,830,870,910,950],
    payroll:  [40,40,42,42,44,44,46,46,48,48,50,50,52,52,54,54,56,56,58,58,60,60,62,62,64,64,66,66,68,68],
    all:      [300,360,400,440,500,560,600,640,720,780,850,910,980,1040,1110,1180,1250,1320,1390,1460,1540,1610,1690,1770,1860,1950,2030,2110,2200,2300],
  };
  const data = datasets[tab] || datasets.invoices;
  const W = 800, H = 200, PL = 40, PR = 14, PT = 18, PB = 30;
  const max = Math.max(...data); const min = 0;
  const range = max - min;
  const ix = i => PL + (i/(data.length-1))*(W-PL-PR);
  const iy = v => PT + (1 - (v-min)/range)*(H-PT-PB);
  const pts = data.map((v,i) => [ix(i), iy(v)]);
  const d = pts.map((p,i) => (i===0?"M":"L") + p[0].toFixed(1) + " " + p[1].toFixed(1)).join(" ");
  const fillD = d + ` L ${ix(data.length-1).toFixed(1)} ${(H-PB).toFixed(1)} L ${ix(0).toFixed(1)} ${(H-PB).toFixed(1)} Z`;

  const [hover, setHover] = useState(null);
  const onMove = (e) => {
    const rect = e.currentTarget.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const fx = (x / rect.width) * W;
    const idx = Math.round(((fx - PL) / (W - PL - PR)) * (data.length-1));
    if (idx >= 0 && idx < data.length) setHover({ idx, v: data[idx], x: pts[idx][0], y: pts[idx][1] });
  };

  // y-axis ticks
  const ticks = [0, 0.25, 0.5, 0.75, 1].map(t => ({ y: PT + (1-t)*(H-PT-PB), v: Math.round(min + t*range) }));
  // x-axis ticks (every 5 days)
  const xTicks = [0,5,10,15,20,25,29].map(i => ({ x: ix(i), label: (i+1) }));

  return (
    <div className="chart-box" onMouseMove={onMove} onMouseLeave={() => setHover(null)}>
      <svg viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none">
        <defs>
          <linearGradient id="gfill" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="#4bec42" stopOpacity="0.30"/>
            <stop offset="100%" stopColor="#4bec42" stopOpacity="0"/>
          </linearGradient>
        </defs>
        {ticks.map((t,i) => (
          <g key={i}>
            <line x1={PL} y1={t.y} x2={W-PR} y2={t.y} stroke="#EAEAE6" strokeWidth="1" strokeDasharray={i===0?"0":"3 3"}/>
            <text x={PL-8} y={t.y+3} fontSize="9" fill="#9A9A93" textAnchor="end" fontFamily="IBM Plex Mono">{t.v >= 1000 ? (t.v/1000).toFixed(1)+"k" : t.v}</text>
          </g>
        ))}
        {xTicks.map((t,i) => (
          <text key={i} x={t.x} y={H-10} fontSize="9" fill="#9A9A93" textAnchor="middle" fontFamily="IBM Plex Mono">{t.label}</text>
        ))}
        <path d={fillD} fill="url(#gfill)"/>
        <path d={d} fill="none" stroke="#080808" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
        {hover && (
          <g>
            <line x1={hover.x} y1={PT} x2={hover.x} y2={H-PB} stroke="#080808" strokeWidth="1" strokeDasharray="3 3"/>
            <circle cx={hover.x} cy={hover.y} r="5" fill="#4bec42" stroke="#080808" strokeWidth="2"/>
          </g>
        )}
      </svg>
      {hover && (
        <div className="chart-tt" style={{left:`${(hover.x/W)*100}%`, top:`${(hover.y/H)*100}%`}}>
          يوم {hover.idx+1}: <b>{hover.v.toLocaleString("ar-EG")}</b>
        </div>
      )}
    </div>
  );
}

/* ---------- Donut ---------- */
function Donut() {
  const data = [
    { code:"P1", label:"الذمم", v:32, c:"#4bec42" },
    { code:"P2", label:"الطلبات", v:24, c:"#080808" },
    { code:"P9", label:"المعرفة", v:18, c:"#888" },
    { code:"P3", label:"السمعة", v:8, c:"#bdbdb7" },
    { code:"P6", label:"التوظيف", v:6, c:"#888" },
    { code:"P4", label:"المطابقة", v:5, c:"#444" },
    { code:"P8", label:"التسويق", v:4, c:"#aaa" },
    { code:"P7", label:"العقود", v:2, c:"#666" },
    { code:"P5", label:"الرواتب", v:1, c:"#ccc" },
  ];
  const total = data.reduce((a,b)=>a+b.v,0);
  const size = 160; const r = 64; const cx = size/2; const cy = size/2; const sw = 24;
  let acc = 0;
  const C = 2*Math.PI*r;
  return (
    <div style={{display:"flex",gap:18,alignItems:"center"}}>
      <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{flexShrink:0}}>
        <circle cx={cx} cy={cy} r={r} fill="none" stroke="#F0F0EC" strokeWidth={sw}/>
        {data.map((d,i) => {
          const frac = d.v/total;
          const dash = frac*C;
          const offset = -acc*C;
          acc += frac;
          return (
            <circle key={i} cx={cx} cy={cy} r={r} fill="none" stroke={d.c} strokeWidth={sw}
              strokeDasharray={`${dash} ${C-dash}`} strokeDashoffset={offset}
              transform={`rotate(-90 ${cx} ${cy})`} style={{transition:"all .4s"}}/>
          );
        })}
        <text x={cx} y={cy-4} textAnchor="middle" fontFamily="IBM Plex Sans Arabic" fontWeight="700" fontSize="22" fill="#080808">١٤٬٢١٠</text>
        <text x={cx} y={cy+12} textAnchor="middle" fontFamily="IBM Plex Mono" fontSize="9" fill="#6B6B66" letterSpacing="0.08em">عملية / ٧ أيام</text>
      </svg>
      <div style={{display:"flex",flexDirection:"column",gap:5,fontSize:12.5,flex:1,minWidth:0}}>
        {data.slice(0,6).map((d,i)=>(
          <div key={i} style={{display:"flex",alignItems:"center",gap:8}}>
            <i style={{width:9,height:9,borderRadius:2,background:d.c,flexShrink:0}}/>
            <span style={{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}>{d.code} · {d.label}</span>
            <span style={{fontFamily:"IBM Plex Mono",color:"#6B6B66",fontSize:11.5}}>{d.v}٪</span>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ---------- Sidebar ---------- */
function Sidebar() {
  const [agentsOpen, setAgentsOpen] = useState(true);
  return (
    <aside className="sidebar">
      <div className="side-top">
        <div className="brand">
          <img src="assets/otmix-full.svg" alt="Otmix"/>
        </div>
        <div className="org-switch">
          <div className="av">ش</div>
          <div style={{flex:1,minWidth:0}}>
            <div className="name">شركة الأفق المحدودة</div>
            <div className="plan">GROWTH · v2.4</div>
          </div>
          {ic.chev}
        </div>
      </div>

      <nav className="nav-scroll">
        <div className="nav-group">
          <div className="grouplbl">عام</div>
          <a className="nav-item active">{ic.home}<span className="nm">الرئيسية</span></a>
          <div onClick={()=>setAgentsOpen(o=>!o)} className="nav-item" style={{justifyContent:"space-between"}}>
            <span style={{display:"flex",alignItems:"center",gap:10}}>{ic.bot}<span className="nm">الوكلاء</span></span>
            <span className="badge">٩</span>
          </div>
          {agentsOpen && (
            <div className="nav-sub" style={{display:"flex"}}>
              {AGENTS.map(a => (
                <a key={a.code} className="nav-item">
                  <span className={`dot ${a.status}`}/>
                  <span className="nm">{a.code} · {a.name}</span>
                </a>
              ))}
            </div>
          )}
          <a className="nav-item">{ic.ops}<span className="nm">العمليات</span><span className="badge">١٢k</span></a>
          <a className="nav-item">{ic.users}<span className="nm">المستخدمون</span></a>
          <a className="nav-item">{ic.reports}<span className="nm">التقارير</span></a>
        </div>
        <div className="nav-group">
          <div className="grouplbl">الإدارة</div>
          <a className="nav-item">{ic.card}<span className="nm">الفوترة والاشتراكات</span></a>
          <a className="nav-item">{ic.plug}<span className="nm">التكاملات</span><span className="badge">٨</span></a>
          <a className="nav-item">{ic.cog}<span className="nm">الإعدادات</span></a>
        </div>
        <div className="nav-group">
          <div className="grouplbl">المساعدة</div>
          <a className="nav-item" href="index.html">{ic.arrowL}<span className="nm">العودة للموقع</span></a>
        </div>
      </nav>

      <div className="side-bot">
        <div className="av">أ</div>
        <div className="who">
          <div className="nm">أحمد العتيبي</div>
          <div className="role">مدير مالي · مسؤول</div>
        </div>
        <button className="icon" title="الثيم">{ic.sun}</button>
      </div>
    </aside>
  );
}

/* ---------- Topbar ---------- */
function Topbar({ openCmdK }) {
  return (
    <header className="topbar">
      <div className="crumb">
        <span>الرئيسية</span>{ic.chevR}<b>نظرة عامة</b>
      </div>
      <div className="search" onClick={openCmdK}>
        {ic.search}
        <input placeholder="ابحث في الوكلاء، العمليات، التقارير..." readOnly/>
        <span className="kbd">⌘K</span>
      </div>
      <div className="top-actions">
        <button className="ic-btn" title="إجراءات">{ic.bolt}</button>
        <button className="ic-btn" title="الإشعارات">{ic.bell}<span className="ndot"/></button>
        <div className="av">أ</div>
      </div>
    </header>
  );
}

/* ---------- Command Palette ---------- */
function CmdK({ open, onClose }) {
  const [q, setQ] = useState("");
  useEffect(() => {
    const onKey = (e) => {
      if (e.key === "Escape") onClose();
    };
    if (open) { window.addEventListener("keydown", onKey); setQ(""); }
    return () => window.removeEventListener("keydown", onKey);
  }, [open, onClose]);

  const items = [
    { g:"الانتقال", items:[
      { ico:ic.home, nm:"الرئيسية / نظرة عامة", kbd:"G H" },
      { ico:ic.bot, nm:"أخصائي الحسابات الدائنة المؤتمت", kbd:"G P1" },
      { ico:ic.bot, nm:"وكيل مبيعات الواتساب الذكي", kbd:"G P2" },
      { ico:ic.ops, nm:"العمليات", kbd:"G O" },
      { ico:ic.card, nm:"الفوترة والاشتراكات", kbd:"G B" },
    ]},
    { g:"إجراءات", items:[
      { ico:ic.plus, nm:"تشغيل وكيل جديد", kbd:"⇧ N" },
      { ico:ic.download, nm:"تصدير العمليات (CSV)" },
      { ico:ic.spark, nm:"اطلب من Claude تحليلاً" },
    ]},
  ];

  return (
    <div className={`cmdk-back ${open?"open":""}`} onClick={onClose}>
      <div className="cmdk" onClick={e=>e.stopPropagation()}>
        <div className="cmdk-input">
          {ic.search}
          <input autoFocus placeholder="اكتب أمراً أو ابحث..." value={q} onChange={e=>setQ(e.target.value)}/>
          <span className="esc">ESC</span>
        </div>
        <div className="cmdk-list">
          {items.map((g,gi)=>(
            <div key={gi}>
              <div className="cmdk-grouplbl">{g.g}</div>
              {g.items.filter(it=>!q||it.nm.includes(q)).map((it,i)=>(
                <div key={i} className="cmdk-item">
                  <span className="ico">{it.ico}</span>
                  <span className="nm">{it.nm}</span>
                  {it.kbd && <span className="kbd">{it.kbd}</span>}
                </div>
              ))}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

/* ---------- Main ---------- */
function App() {
  const [tab, setTab] = useState("invoices");
  const [cmdOpen, setCmdOpen] = useState(false);
  const [counts, setCounts] = useState(KPIS.map(() => 0));

  useEffect(() => {
    const onKey = (e) => {
      if ((e.metaKey||e.ctrlKey) && e.key.toLowerCase()==="k") { e.preventDefault(); setCmdOpen(true); }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  return (
    <div className="app">
      <Sidebar/>
      <div className="main">
        <Topbar openCmdK={()=>setCmdOpen(true)}/>
        <div className="content">

          {/* Welcome */}
          <div className="welcome">
            <div>
              <h2>صباح الخير، أحمد 👋</h2>
              <div className="tip">
                <span style={{color:"var(--green)"}}>💡</span>
                <span>وكيل الفواتير اكتشف <b>١٢ فاتورة مكررة</b> هذا الأسبوع — وفّر <b>٤٬٨٠٠ ر.س</b>.</span>
              </div>
            </div>
            <div className="welcome-actions">
              <button className="btn btn-ghost-d">تقرير الأسبوع</button>
              <button className="btn btn-green">تشغيل وكيل جديد {ic.arrow}</button>
            </div>
          </div>

          {/* KPI Row */}
          <div className="kpis">
            {KPIS.map((k,i)=>(
              <div className="kpi" key={i}>
                <div className="lbl">{k.lbl}</div>
                <div className="v">{k.v}{k.small && <small>{k.small}</small>}</div>
                <div className="meta">
                  <span className={"delta"+(k.dn?" dn":"")}>{k.dn?"▼":"▲"} {k.delta}</span>
                  <span className="vs">مقارنة بالشهر السابق</span>
                </div>
                <div className="spark"><Spark data={k.spark} color={k.dn?"#E5484D":"#080808"} fill h={32}/></div>
              </div>
            ))}
          </div>

          {/* Two-column row: chart + insights */}
          <div className="row-2">
            <div className="panel">
              <div className="panel-head">
                <div>
                  <h4>العمليات عبر آخر ٣٠ يوماً</h4>
                  <div className="sub">إجمالي ١٢٬٨٤٧ عملية · متوسط ٤٢٨/يوم</div>
                </div>
                <div className="tabs">
                  {[["invoices","الفواتير"],["orders","الطلبات"],["payroll","الرواتب"],["all","الكل"]].map(([k,l])=>(
                    <button key={k} className={tab===k?"active":""} onClick={()=>setTab(k)}>{l}</button>
                  ))}
                </div>
              </div>
              <BigChart tab={tab}/>
              <div className="chart-legend">
                <span><i style={{background:"#080808"}}/>عمليات يومية</span>
                <span><i style={{background:"rgba(75, 236, 66,0.30)"}}/>منطقة التراكم</span>
                <span style={{marginInlineStart:"auto",fontFamily:"IBM Plex Mono",fontSize:11.5}}>تحديث منذ ٤٢ ث</span>
              </div>
            </div>

            <div className="panel">
              <div className="panel-head">
                <h4>رؤى من Claude</h4>
                <button className="btn btn-outline" style={{padding:"6px 10px",fontSize:12}}>عرض الكل</button>
              </div>
              <div className="insights">
                {INSIGHTS.map((it,i)=>(
                  <div className="insight" key={i}>
                    <div className={"ico "+it.kind}>{it.ico}</div>
                    <div className="body">
                      <div className="ev">{it.ev}</div>
                      <div className="meta"><span>{it.time}</span><span>·</span><span>{it.tag}</span></div>
                    </div>
                    <button className="act">{it.act} {ic.arrow}</button>
                  </div>
                ))}
              </div>
            </div>
          </div>

          {/* Donut + Agents */}
          <div className="row-2" style={{gridTemplateColumns:"1fr 1.65fr"}}>
            <div className="panel">
              <div className="panel-head">
                <h4>توزيع العمليات حسب الوكيل</h4>
                <span className="sub">آخر ٧ أيام</span>
              </div>
              <Donut/>
            </div>
            <div className="panel">
              <div className="panel-head">
                <h4>أداء الوكلاء</h4>
                <button className="btn btn-outline" style={{padding:"6px 10px",fontSize:12}}>إدارة الكل {ic.arrow}</button>
              </div>
              <div className="agents-grid" style={{margin:0}}>
                {AGENTS.slice(0,6).map(a => (
                  <div className="agent-card" key={a.code}>
                    <div className="top">
                      <div className="nm">
                        <div className="icbox">{a.icon}</div>
                        <span>{a.code} · {a.name}</span>
                      </div>
                      <span className={"stat "+a.status}>
                        <span className="d"/>{a.status==="live"?"نشط":a.status==="warn"?"تحذير":"خامل"}
                      </span>
                    </div>
                    <div className="kpi-mini"><span className="num">{a.kpi}</span><span className="unit">{a.unit}</span></div>
                    <div className="mini-spark"><Spark data={a.spark} color={a.status==="warn"?"#F4B400":"#080808"} fill h={30}/></div>
                    <div className="foot">
                      <span>زمن التشغيل ٩٩٫٩٪</span>
                      <span className="ok">↗ {a.code==="P4"?"-12%":"+8%"}</span>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>

          {/* Activity Table */}
          <div className="table-wrap">
            <div className="table-head">
              <div>
                <h4>آخر العمليات</h4>
                <div className="sub" style={{fontSize:12.5,color:"var(--muted)",marginTop:2}}>تحديث لحظي · ٣٤٢ عملية اليوم</div>
              </div>
              <div className="table-tools">
                <button className="chip-filter">{ic.filter} كل الوكلاء</button>
                <button className="chip-filter">آخر ٢٤ ساعة</button>
                <button className="chip-filter">{ic.download} تصدير CSV</button>
              </div>
            </div>
            <table className="tbl">
              <thead>
                <tr>
                  <th>المعرّف</th>
                  <th>النوع</th>
                  <th>الوكيل</th>
                  <th>القيمة</th>
                  <th>الحالة</th>
                  <th>الوقت</th>
                  <th></th>
                </tr>
              </thead>
              <tbody>
                {ACTIVITY.map((r,i)=>(
                  <tr key={i}>
                    <td className="id">{r.id}</td>
                    <td>{r.type}</td>
                    <td><div className="who"><div className="av">{r.agentColor}</div><span>{r.agent}</span></div></td>
                    <td className="amount">{r.amt}</td>
                    <td><span className={"stat-pill "+r.sk}><span className="d"/>{r.status}</span></td>
                    <td className="id">{r.time}</td>
                    <td><div className="row-acts"><button title="عرض">{ic.eye}</button><button title="المزيد">{ic.more}</button></div></td>
                  </tr>
                ))}
              </tbody>
            </table>
            <div className="table-foot">
              <span>عرض ١-٨ من ٣٤٢</span>
              <div className="pager">
                <button>{ic.chevR}</button>
                <button className="active">١</button><button>٢</button><button>٣</button><button>...</button><button>٤٣</button>
                <button style={{transform:"rotate(180deg)"}}>{ic.chevR}</button>
              </div>
            </div>
          </div>

        </div>
      </div>
      <CmdK open={cmdOpen} onClose={()=>setCmdOpen(false)}/>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App/>);
