// Kotleto · ADMIN tabs

// Reusable card shell
function Panel({ title, action, children, span, padded = true }) {
  return (
    <section style={{
      background: "#15100B", border: "1px solid rgba(255,244,226,0.08)",
      borderRadius: 18, overflow: "hidden",
      gridColumn: span,
    }}>
      {title && (
        <header style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "18px 22px 0" }}>
          <div className="display" style={{ fontSize: 18 }}>{title}</div>
          {action}
        </header>
      )}
      <div className={padded ? undefined : "table-scroll"} style={{ padding: padded ? "16px 22px 22px" : 0 }}>{children}</div>
    </section>
  );
}

function getAdminOrders() {
  const localOrders = LocalDB.get("orders", []).map(order => ({
    id: order.id,
    name: T(order.customer?.name || "مشتری وب", order.customer?.name || "Web customer"),
    items: order.items,
    total: order.total,
    status: order.status === "placed" ? "new" : order.status,
    channel: "وب",
    time: "الان",
  }));
  const localIds = new Set(localOrders.map(order => order.id));
  return [...localOrders, ...ORDER_FEED.filter(order => !localIds.has(order.id))];
}

function Stat({ label, value, delta, color, icon }) {
  return (
    <div style={{
      background: "#15100B", border: "1px solid rgba(255,244,226,0.08)",
      borderRadius: 18, padding: 20, position: "relative", overflow: "hidden",
    }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
        <div style={{ width: 36, height: 36, borderRadius: 10, background: color + "22", color: color, display: "grid", placeItems: "center" }}>{icon}</div>
        {delta != null && (
          <span style={{
            fontSize: 11, fontWeight: 800,
            color: delta >= 0 ? "#7FCB5A" : "#FF6B5A",
            background: delta >= 0 ? "rgba(127,203,90,0.1)" : "rgba(255,107,90,0.1)",
            padding: "3px 8px", borderRadius: 999,
          }}>{delta >= 0 ? "↑" : "↓"} {Math.abs(delta)}%</span>
        )}
      </div>
      <div style={{ fontSize: 12, color: "rgba(255,244,226,0.5)", marginTop: 14 }}>{label}</div>
      <div className="display tnum" style={{ fontSize: 30, marginTop: 4 }}>{value}</div>
    </div>
  );
}

// -------- CUSTOMERS TAB
function CustomersTab({ accent }) {
  const { lang } = useLang();
  const [tagFilter, setTagFilter] = useState("all");
  const [selected, setSelected] = useState(null);

  const TAGS = {
    vip:     { fa: "VIP",       en: "VIP",      color: accent,    bg: "rgba(217,70,30,0.15)" },
    regular: { fa: "وفادار",     en: "Regular",  color: "#E8B14A", bg: "rgba(232,177,74,0.15)" },
    new:     { fa: "تازه",       en: "New",      color: "#9AB8E8", bg: "rgba(154,184,232,0.15)" },
  };
  const filters = [
    { id: "all",     fa: "همه",     en: "All",     count: CUSTOMERS.length },
    { id: "vip",     fa: "VIP",     en: "VIP",     count: CUSTOMERS.filter(c=>c.tag==="vip").length },
    { id: "regular", fa: "وفادار",  en: "Regular", count: CUSTOMERS.filter(c=>c.tag==="regular").length },
    { id: "new",     fa: "تازه",    en: "New",     count: CUSTOMERS.filter(c=>c.tag==="new").length },
  ];
  const rows = tagFilter === "all" ? CUSTOMERS : CUSTOMERS.filter(c => c.tag === tagFilter);

  const totalRevenue = CUSTOMERS.reduce((s, c) => s + c.spent, 0);
  const totalOrders = CUSTOMERS.reduce((s, c) => s + c.orders, 0);

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
      {/* KPIs */}
      <div className="grid grid-kpi" style={{ gap: 18 }}>
        <Stat label={lang==="fa"?"کل مشتری":"Total customers"} value={lang==="fa"?toFa(CUSTOMERS.length):CUSTOMERS.length} delta={14} color={accent} icon={<Ico.User/>}/>
        <Stat label={lang==="fa"?"VIPها":"VIPs"} value={lang==="fa"?toFa(filters[1].count):filters[1].count} delta={6} color="#E8B14A" icon={<Ico.Star/>}/>
        <Stat label={lang==="fa"?"درآمد کل":"Total revenue"} value={<Price value={totalRevenue}/>} delta={22} color="#7FCB5A" icon={<Ico.Chart/>}/>
        <Stat label={lang==="fa"?"میانگین سفارش":"Avg orders/cust"} value={lang==="fa"?toFa((totalOrders/CUSTOMERS.length).toFixed(1)):(totalOrders/CUSTOMERS.length).toFixed(1)} delta={4} color="#9AB8E8" icon={<Ico.Bag/>}/>
      </div>

      {/* Filters */}
      <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
        {filters.map(f => (
          <button key={f.id} onClick={()=>setTagFilter(f.id)} style={{
            padding: "9px 14px", borderRadius: 10, fontSize: 13, fontWeight: 600,
            background: tagFilter===f.id ? accent : "rgba(255,244,226,0.05)",
            color: tagFilter===f.id ? "#fff" : "rgba(255,244,226,0.7)",
            border: "1px solid " + (tagFilter===f.id ? accent : "rgba(255,244,226,0.1)"),
            display: "inline-flex", alignItems: "center", gap: 8,
          }}>{f[lang]} <span style={{ opacity: 0.6, fontSize: 11 }}>{lang==="fa"?toFa(f.count):f.count}</span></button>
        ))}
      </div>

      {/* Customers table */}
      <Panel padded={false}>
        <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13 }}>
          <thead>
            <tr style={{ background: "rgba(255,244,226,0.03)" }}>
              {[
                lang==="fa"?"مشتری":"Customer",
                lang==="fa"?"تلفن":"Phone",
                lang==="fa"?"سفارش":"Orders",
                lang==="fa"?"کل خرید":"Total spent",
                lang==="fa"?"آخرین":"Last order",
                lang==="fa"?"دسته":"Tag",
                "",
              ].map((h, i) => (
                <th key={i} style={{ textAlign: "start", padding: "12px 18px", fontSize: 11, fontWeight: 700, color: "rgba(255,244,226,0.5)", textTransform: "uppercase", letterSpacing: "0.1em", borderBottom: "1px solid rgba(255,244,226,0.06)" }}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {rows.map((c, i) => {
              const fav = MENU.find(m => m.id === c.fav);
              return (
                <tr key={c.id} style={{ borderBottom: "1px solid rgba(255,244,226,0.05)", cursor: "pointer" }}
                    onClick={()=>setSelected(c)}>
                  <td style={tdStyle}>
                    <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                      <div style={{ width: 36, height: 36, borderRadius: 999, background: ["#D9461E","#5B6B3A","#E8B14A","#9AB8E8","#7B4A1C","#B83020","#8B2510"][i%7], color: "#fff", display: "grid", placeItems: "center", fontFamily: "var(--display)", fontSize: 14 }}>{pick(c.name, lang).slice(0,1)}</div>
                      <div>
                        <div style={{ fontWeight: 700 }}>{pick(c.name, lang)}</div>
                        <div style={{ fontSize: 11, color: "rgba(255,244,226,0.4)", marginTop: 2 }}>#{c.id}</div>
                      </div>
                    </div>
                  </td>
                  <td style={{ ...tdStyle, fontFamily: "var(--display)", fontSize: 12, opacity: 0.7 }} dir="ltr">{pick(c.phone, lang)}</td>
                  <td style={tdStyle}><span className="tnum" style={{ fontWeight: 700 }}>{lang==="fa"?toFa(c.orders):c.orders}</span></td>
                  <td style={tdStyle}><Price value={c.spent}/></td>
                  <td style={{ ...tdStyle, opacity: 0.6 }}>{pick(c.last, lang)}</td>
                  <td style={tdStyle}>
                    <span style={{
                      display: "inline-flex", alignItems: "center", gap: 6,
                      padding: "5px 10px", borderRadius: 999, fontSize: 11, fontWeight: 700,
                      background: TAGS[c.tag].bg, color: TAGS[c.tag].color,
                    }}>{TAGS[c.tag][lang]}</span>
                  </td>
                  <td style={tdStyle}><span style={{ color: "rgba(255,244,226,0.5)", fontSize: 12 }}>{lang==="fa"?"جزئیات →":"Details →"}</span></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </Panel>

      {selected && <CustomerDetailModal customer={selected} onClose={()=>setSelected(null)} accent={accent}/>}
    </div>
  );
}

function CustomerDetailModal({ customer, onClose, accent }) {
  const { lang } = useLang();
  const c = customer;
  const fav = MENU.find(m => m.id === c.fav);
  // Pull a few orders from feed as if they were this customer's
  const orders = ORDER_FEED.slice(0, 4);

  return (
    <>
      <div onClick={onClose} style={{ position: "fixed", inset: 0, zIndex: 60, background: "rgba(0,0,0,0.5)", backdropFilter: "blur(4px)" }}/>
      <div style={{
        position: "fixed", zIndex: 61, top: 0, bottom: 0,
        [lang === "fa" ? "left" : "right"]: 0,
        width: "min(520px, 96vw)",
        background: "#15100B", borderInlineStart: "1px solid rgba(255,244,226,0.12)",
        display: "flex", flexDirection: "column",
        boxShadow: "0 0 80px rgba(0,0,0,0.6)",
        animation: "drawerIn .3s ease",
      }}>
        <header style={{ padding: 24, borderBottom: "1px solid rgba(255,244,226,0.08)" }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 18 }}>
            <span className="chip" style={{ background: "rgba(255,244,226,0.06)", color: "rgba(255,244,226,0.7)", border: "1px solid rgba(255,244,226,0.1)" }}>
              {lang === "fa" ? "پروفایل مشتری" : "Customer profile"} · #{c.id}
            </span>
            <button onClick={onClose} style={{ color: "rgba(255,244,226,0.5)" }}><Ico.X/></button>
          </div>
          <div style={{ display: "flex", gap: 14, alignItems: "center" }}>
            <div style={{ width: 64, height: 64, borderRadius: 999, background: accent, color: "#fff", display: "grid", placeItems: "center", fontFamily: "var(--display)", fontSize: 26 }}>{pick(c.name, lang).slice(0,1)}</div>
            <div>
              <h2 className="display" style={{ margin: 0, fontSize: 26, color: "var(--paper)" }}>{pick(c.name, lang)}</h2>
              <div style={{ fontSize: 12, color: "rgba(255,244,226,0.5)", marginTop: 4 }} dir="ltr">{pick(c.phone, lang)}</div>
              <div style={{ fontSize: 11, color: "rgba(255,244,226,0.5)", marginTop: 4 }}>{lang === "fa" ? "عضو از: " : "Joined: "}{pick(c.joined, lang)}</div>
            </div>
          </div>
        </header>

        <div style={{ flex: 1, overflowY: "auto", padding: 24, display: "flex", flexDirection: "column", gap: 22 }}>
          {/* Stats */}
          <div className="grid grid-3" style={{ gap: 12 }}>
            {[
              { label: lang==="fa"?"تعداد سفارش":"Total orders", value: lang==="fa"?toFa(c.orders):c.orders },
              { label: lang==="fa"?"کل خرید":"Total spent",   value: <Price value={c.spent}/> },
              { label: lang==="fa"?"میانگین":"Avg basket",     value: <Price value={Math.round(c.spent/c.orders)}/> },
            ].map((s, i) => (
              <div key={i} style={{ padding: 14, background: "rgba(255,244,226,0.04)", border: "1px solid rgba(255,244,226,0.06)", borderRadius: 14 }}>
                <div style={{ fontSize: 11, color: "rgba(255,244,226,0.5)" }}>{s.label}</div>
                <div className="display tnum" style={{ fontSize: 20, color: "var(--paper)", marginTop: 4 }}>{s.value}</div>
              </div>
            ))}
          </div>

          {/* Favorite */}
          {fav && (
            <div>
              <div style={{ fontSize: 11, fontWeight: 700, color: "rgba(255,244,226,0.5)", textTransform: "uppercase", letterSpacing: "0.1em", marginBottom: 10 }}>{lang==="fa"?"غذای محبوب":"Favorite item"}</div>
              <div style={{ display: "flex", alignItems: "center", gap: 14, padding: 14, background: "rgba(255,244,226,0.04)", border: "1px solid rgba(255,244,226,0.06)", borderRadius: 14 }}>
                <div style={{ width: 50, height: 50, borderRadius: 12, background: fav.color, display: "grid", placeItems: "center", fontSize: 24 }}>{fav.emoji}</div>
                <div style={{ flex: 1 }}>
                  <div className="display" style={{ fontSize: 17 }}>{fav[lang].name}</div>
                  <div style={{ fontSize: 12, color: "rgba(255,244,226,0.5)", marginTop: 2 }}><Price value={fav.price}/></div>
                </div>
                <Ico.Heart style={{ color: accent }}/>
              </div>
            </div>
          )}

          {/* Recent orders */}
          <div>
            <div style={{ fontSize: 11, fontWeight: 700, color: "rgba(255,244,226,0.5)", textTransform: "uppercase", letterSpacing: "0.1em", marginBottom: 10 }}>{lang==="fa"?"سفارش‌های اخیر":"Recent orders"}</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
              {orders.map(o => (
                <div key={o.id} style={{ display: "flex", justifyContent: "space-between", padding: "12px 14px", background: "rgba(255,244,226,0.04)", borderRadius: 12, fontSize: 13 }}>
                  <span style={{ fontFamily: "var(--display)" }}>{o.id}</span>
                  <span style={{ opacity: 0.5 }}>{o.time}</span>
                  <Price value={o.total}/>
                </div>
              ))}
            </div>
          </div>
        </div>

        <footer style={{ padding: 20, borderTop: "1px solid rgba(255,244,226,0.08)", display: "flex", gap: 10 }}>
          <a href={"tel:" + toEn(pick(c.phone, lang)).replace(/\s/g, "")} className="btn btn-ghost" style={{ flex: 1, color: "var(--paper)", borderColor: "rgba(255,244,226,0.2)" }}><Ico.Phone/> {lang==="fa"?"تماس":"Call"}</a>
          <button onClick={() => { navigator.clipboard?.writeText("BAHAR15"); notify(lang==="fa"?"کد تخفیف کپی شد":"Promo code copied"); }} className="btn btn-primary" style={{ flex: 1 }}><Ico.Sparkle/> {lang==="fa"?"ارسال تخفیف":"Send promo"}</button>
        </footer>
      </div>
      <style>{`@keyframes drawerIn { from { transform: translateX(${lang === "fa" ? "-100%" : "100%"}); } to { transform: translateX(0); } }`}</style>
    </>
  );
}

// -------- OVERVIEW
function Overview({ accent }) {
  const { lang } = useLang();
  const adminOrders = getAdminOrders();
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 22 }}>
      {/* KPI row */}
      <div className="grid grid-kpi" style={{ gap: 18 }}>
        <Stat label={lang==="fa"?"درآمد امروز":"Today's revenue"} value={<><Price value={18420000}/></>} delta={12} color="#7FCB5A" icon={<Ico.Chart/>}/>
        <Stat label={lang==="fa"?"سفارش‌ها":"Orders"} value={lang==="fa"?toFa("۸۴"):"84"} delta={8} color={accent} icon={<Ico.Bag/>}/>
        <Stat label={lang==="fa"?"میانگین سبد":"Avg basket"} value={<Price value={219000}/>} delta={-3} color="#E8B14A" icon={<Ico.Sparkle/>}/>
        <Stat label={lang==="fa"?"امتیاز رضایت":"Satisfaction"} value={lang==="fa"?"۴.۹★":"4.9★"} delta={2} color="#9AB8E8" icon={<Ico.Star/>}/>
      </div>

      <div className="grid grid-overview" style={{ gap: 22 }}>
        {/* Revenue chart */}
        <Panel title={lang==="fa"?"فروش این هفته":"This week's sales"}
          action={<select style={selStyle} defaultValue="7"><option value="7">{lang==="fa"?"۷ روز":"7 days"}</option><option value="30">30 days</option></select>}>
          <RevenueChart accent={accent}/>
        </Panel>

        {/* Best sellers */}
        <Panel title={lang==="fa"?"پرفروش‌ها":"Top sellers"}>
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {MENU.slice(0,5).map((m,i)=>{
              const sold = [142, 98, 76, 54, 41][i];
              const max = 142;
              return (
                <div key={m.id} style={{ display:"flex", alignItems:"center", gap:12 }}>
                  <div style={{ width: 36, height: 36, borderRadius: 10, background: m.color, display:"grid", placeItems:"center", fontSize: 18, flexShrink:0 }}>{m.emoji}</div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13, fontWeight: 600, whiteSpace:"nowrap", overflow:"hidden", textOverflow:"ellipsis" }}>{m[lang].name}</div>
                    <div style={{ height: 6, background: "rgba(255,244,226,0.08)", borderRadius: 999, marginTop: 6, overflow: "hidden" }}>
                      <div style={{ width: `${sold/max*100}%`, height: "100%", background: accent }}/>
                    </div>
                  </div>
                  <div className="tnum" style={{ fontSize: 14, fontWeight: 700, minWidth: 40, textAlign: "end" }}>{lang==="fa"?toFa(sold):sold}</div>
                </div>
              );
            })}
          </div>
        </Panel>
      </div>

      {/* Live orders */}
      <Panel title={lang==="fa"?"سفارش‌های لحظه‌ای":"Live orders"}
        action={<span className="chip brand" style={{ fontSize: 11 }}><Ico.Dot/>{lang==="fa"?"به‌روز":"Live"}</span>}
        padded={false}>
        <OrdersTable rows={adminOrders.slice(0,5)} accent={accent} compact/>
      </Panel>
    </div>
  );
}

const selStyle = {
  background: "rgba(255,244,226,0.06)", color: "var(--paper)",
  border: "1px solid rgba(255,244,226,0.1)", borderRadius: 10,
  padding: "6px 12px", fontSize: 12, fontFamily: "inherit",
};

// -------- ORDERS TAB
function OrdersTab({ accent }) {
  const { lang } = useLang();
  const [filter, setFilter] = useState("all");
  const allOrders = getAdminOrders();
  const filters = [
    { id: "all", fa: "همه", en: "All", count: allOrders.length },
    { id: "new", fa: "جدید", en: "New", count: allOrders.filter(o=>o.status==="new").length },
    { id: "preparing", fa: "در حال آماده‌سازی", en: "Preparing", count: allOrders.filter(o=>o.status==="preparing").length },
    { id: "out", fa: "در راه", en: "On the way", count: allOrders.filter(o=>o.status==="out").length },
    { id: "delivered", fa: "تحویل شد", en: "Delivered", count: allOrders.filter(o=>o.status==="delivered").length },
  ];
  const rows = filter === "all" ? allOrders : allOrders.filter(o => o.status === filter);

  return (
    <div style={{ display:"flex", flexDirection:"column", gap: 18 }}>
      <div style={{ display:"flex", gap: 8, flexWrap:"wrap" }}>
        {filters.map(f => (
          <button key={f.id} onClick={()=>setFilter(f.id)} style={{
            padding: "9px 14px", borderRadius: 10, fontSize: 13, fontWeight: 600,
            background: filter===f.id ? accent : "rgba(255,244,226,0.05)",
            color: filter===f.id ? "#fff" : "rgba(255,244,226,0.7)",
            border: "1px solid " + (filter===f.id ? accent : "rgba(255,244,226,0.1)"),
            display:"inline-flex", alignItems:"center", gap: 8,
          }}>{f[lang]} <span style={{ opacity: 0.6, fontSize: 11 }}>{lang==="fa"?toFa(f.count):f.count}</span></button>
        ))}
      </div>
      <Panel padded={false}><OrdersTable rows={rows} accent={accent}/></Panel>
    </div>
  );
}

function OrdersTable({ rows, accent, compact }) {
  const { lang } = useLang();
  const STATUS = {
    new:        { fa: "جدید", en: "New", color: "#9AB8E8" },
    preparing:  { fa: "در حال پخت", en: "Preparing", color: accent },
    out:        { fa: "در راه", en: "On the way", color: "#E8B14A" },
    delivered:  { fa: "تحویل شد", en: "Delivered", color: "#7FCB5A" },
  };
  return (
    <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13 }}>
      <thead>
        <tr style={{ background: "rgba(255,244,226,0.03)" }}>
          {[
            lang==="fa"?"کد سفارش":"Order #",
            lang==="fa"?"مشتری":"Customer",
            lang==="fa"?"آیتم":"Items",
            lang==="fa"?"مبلغ":"Total",
            lang==="fa"?"کانال":"Channel",
            lang==="fa"?"زمان":"When",
            lang==="fa"?"وضعیت":"Status",
            "",
          ].map((h,i)=>(
            <th key={i} style={{ textAlign:"start", padding: "12px 18px", fontSize: 11, fontWeight: 700, color: "rgba(255,244,226,0.5)", textTransform: "uppercase", letterSpacing: "0.1em", borderBottom: "1px solid rgba(255,244,226,0.06)" }}>{h}</th>
          ))}
        </tr>
      </thead>
      <tbody>
        {rows.map(r => (
          <tr key={r.id} style={{ borderBottom: "1px solid rgba(255,244,226,0.05)" }}>
            <td style={tdStyle}><span style={{ fontFamily:"var(--display)", fontSize: 14 }}>{r.id}</span></td>
            <td style={tdStyle}>{pick(r.name, lang)}</td>
            <td style={tdStyle}>{lang==="fa"?toFa(r.items):r.items}</td>
            <td style={tdStyle}><Price value={r.total}/></td>
            <td style={tdStyle}><span style={{ opacity: 0.6 }}>{r.channel}</span></td>
            <td style={tdStyle}><span style={{ opacity: 0.6 }}>{r.time}</span></td>
            <td style={tdStyle}>
              <span style={{
                display: "inline-flex", alignItems: "center", gap: 6,
                padding: "5px 10px", borderRadius: 999, fontSize: 11, fontWeight: 700,
                background: STATUS[r.status].color + "22", color: STATUS[r.status].color,
              }}><span style={{ width: 6, height: 6, borderRadius: 999, background: STATUS[r.status].color }}/> {STATUS[r.status][lang]}</span>
            </td>
            <td style={tdStyle}><button aria-label={lang==="fa"?"جزئیات سفارش":"Order details"} onClick={() => notify((lang==="fa"?"سفارش ":"Order ") + r.id + (lang==="fa"?" انتخاب شد":" selected"))} style={{ color: "rgba(255,244,226,0.5)", fontSize: 12 }}>•••</button></td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}
const tdStyle = { padding: "14px 18px", verticalAlign: "middle" };

// -------- MENU TAB
function MenuTab({ accent }) {
  const { lang } = useLang();
  return (
    <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(280px, 1fr))", gap: 18 }}>
      {/* "Add new" card */}
      <button onClick={() => notify(lang==="fa"?"فرم افزودن آیتم در نسخه محلی آماده اتصال است":"Add-item form is ready for the local version")} style={{
        background: "transparent", border: "2px dashed rgba(255,244,226,0.15)", borderRadius: 18,
        minHeight: 240, display: "grid", placeItems: "center", color: "rgba(255,244,226,0.5)",
      }}>
        <div style={{ textAlign: "center" }}>
          <div style={{ fontSize: 40, marginBottom: 6 }}>+</div>
          <div style={{ fontSize: 14, fontWeight: 700 }}>{lang==="fa"?"افزودن آیتم":"Add item"}</div>
        </div>
      </button>
      {MENU.slice(0, 11).map(item => (
        <div key={item.id} style={{
          background: "#15100B", border: "1px solid rgba(255,244,226,0.08)", borderRadius: 18, overflow: "hidden",
        }}>
          <div style={{ background: item.color, height: 96, display: "grid", placeItems: "center", fontSize: 40, position: "relative" }}>
            {item.emoji}
            <button onClick={() => notify((lang==="fa"?"ویرایش ":"Edit ") + item[lang].name)} aria-label={lang==="fa"?"ویرایش آیتم":"Edit item"} style={{
              position: "absolute", top: 10, insetInlineEnd: 10,
              width: 30, height: 30, borderRadius: 10, background: "rgba(0,0,0,0.4)", color: "#fff",
              fontSize: 14, fontWeight: 800,
            }}>⋯</button>
          </div>
          <div style={{ padding: 16 }}>
            <div className="display" style={{ fontSize: 16 }}>{item[lang].name}</div>
            <div style={{ fontSize: 11, color: "rgba(255,244,226,0.5)", marginTop: 4 }}>{CATEGORIES.find(c=>c.id===item.cat)?.[lang]}</div>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 14 }}>
              <span style={{ fontFamily: "var(--display)", color: accent, fontSize: 16 }}><Price value={item.price}/></span>
              <label style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 11, color: "rgba(255,244,226,0.6)" }}>
                <span>{lang==="fa"?"فعال":"Active"}</span>
                <Toggle defaultOn={true}/>
              </label>
            </div>
          </div>
        </div>
      ))}
    </div>
  );
}

function Toggle({ defaultOn = false, color = "#D9461E" }) {
  const [on, setOn] = useState(defaultOn);
  return (
    <button onClick={()=>setOn(!on)} style={{
      width: 34, height: 20, borderRadius: 999, position: "relative",
      background: on ? color : "rgba(255,244,226,0.15)", transition: "all .15s ease",
    }}>
      <span style={{
        position: "absolute", top: 2, [on ? "right" : "left"]: 2,
        width: 16, height: 16, borderRadius: 999, background: "#fff",
        transition: "all .15s ease",
      }}/>
    </button>
  );
}

// -------- STAFF TAB
function StaffTab({ accent }) {
  const { lang } = useLang();
  const STATUS_S = { on: { fa: "در شیفت", en: "On shift", color: "#7FCB5A" }, break: { fa: "استراحت", en: "On break", color: "#E8B14A" }, off: { fa: "خارج از شیفت", en: "Off", color: "rgba(255,244,226,0.4)" } };
  return (
    <Panel padded={false}>
      <table style={{ width:"100%", borderCollapse: "collapse", fontSize: 13 }}>
        <thead><tr style={{ background: "rgba(255,244,226,0.03)" }}>
          {[(lang==="fa"?"کارمند":"Staff"),(lang==="fa"?"نقش":"Role"),(lang==="fa"?"شیفت":"Shift"),(lang==="fa"?"امروز":"Today"),(lang==="fa"?"وضعیت":"Status"),""].map((h,i)=>(
            <th key={i} style={{ textAlign:"start", padding: "12px 18px", fontSize: 11, fontWeight: 700, color: "rgba(255,244,226,0.5)", textTransform: "uppercase", letterSpacing: "0.1em" }}>{h}</th>
          ))}
        </tr></thead>
        <tbody>
          {STAFF.map((s, i) => (
            <tr key={i} style={{ borderTop: "1px solid rgba(255,244,226,0.05)" }}>
              <td style={tdStyle}>
                <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                  <div style={{ width: 36, height: 36, borderRadius: 999, background: ["#D9461E","#5B6B3A","#E8B14A","#9AB8E8","#7B4A1C"][i%5], color: "#fff", display: "grid", placeItems: "center", fontFamily: "var(--display)", fontSize: 14 }}>{pick(s.name, lang).slice(0,1)}</div>
                  <div>
                    <div style={{ fontWeight: 700 }}>{pick(s.name, lang)}</div>
                  </div>
                </div>
              </td>
              <td style={tdStyle}>{pick(s.role, lang)}</td>
              <td style={{ ...tdStyle, fontFamily: "var(--display)", fontSize: 13 }}>{s.shift}</td>
              <td style={tdStyle}>{s.today > 0 ? (lang==="fa"?`${toFa(s.today)} سفارش`:`${s.today} orders`) : "—"}</td>
              <td style={tdStyle}>
                <span style={{ display:"inline-flex", alignItems:"center", gap: 6, fontSize: 12, color: STATUS_S[s.status].color, fontWeight: 700 }}>
                  <span style={{ width: 6, height: 6, borderRadius: 999, background: STATUS_S[s.status].color }}/>{STATUS_S[s.status][lang]}
                </span>
              </td>
              <td style={tdStyle}><button onClick={() => notify((lang==="fa"?"کارمند ":"Staff ") + pick(s.name, lang))} aria-label={lang==="fa"?"جزئیات کارمند":"Staff details"} style={{ color: "rgba(255,244,226,0.5)", fontSize: 12 }}>•••</button></td>
            </tr>
          ))}
        </tbody>
      </table>
    </Panel>
  );
}

// -------- REPORTS TAB
function ReportsTab({ accent }) {
  const { lang } = useLang();
  return (
    <div className="grid grid-reports" style={{ gap: 22 }}>
      <Panel title={lang==="fa"?"فروش ماهانه":"Monthly sales"}><MonthChart accent={accent}/></Panel>
      <Panel title={lang==="fa"?"توزیع کانال":"Channel split"}><DonutChart accent={accent}/></Panel>
      <Panel title={lang==="fa"?"ساعت‌های شلوغ":"Peak hours"} span="1 / -1"><HeatmapChart accent={accent}/></Panel>
    </div>
  );
}

// -------- SETTINGS TAB
function SettingsTab({ accent }) {
  const { lang } = useLang();
  return (
    <div className="grid grid-2" style={{ gap: 22 }}>
      <div style={{ gridColumn: "1 / -1", display: "flex", justifyContent: "flex-end" }}>
        <button className="btn btn-ghost btn-sm" onClick={() => { LocalDB.export(); notify(lang==="fa"?"فایل JSON دانلود شد":"JSON database downloaded"); }} style={{ color: "var(--paper)", borderColor: "rgba(255,244,226,.25)" }}>{lang==="fa"?"خروجی دیتابیس JSON":"Export JSON database"}</button>
      </div>
      <Panel title={lang==="fa"?"ساعت کاری":"Business hours"}>
        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
          {HOURS.map((h,i)=>(
            <div key={i} style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "10px 14px", background: "rgba(255,244,226,0.04)", borderRadius: 12 }}>
              <span style={{ fontSize: 13 }}>{h[lang]}</span>
              <span className="tnum" style={{ fontFamily: "var(--display)" }}>{h.time}</span>
              <Toggle defaultOn={true} color={accent}/>
            </div>
          ))}
        </div>
      </Panel>
      <Panel title={lang==="fa"?"اعلان‌ها":"Notifications"}>
        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          {[
            { fa: "سفارش جدید", en: "New order", on: true },
            { fa: "گزارش روزانه", en: "Daily report", on: true },
            { fa: "هشدار موجودی", en: "Low stock alert", on: true },
            { fa: "نظر جدید", en: "New review", on: false },
          ].map((n,i)=>(
            <div key={i} style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "12px 14px", background: "rgba(255,244,226,0.04)", borderRadius: 12 }}>
              <span style={{ fontSize: 13 }}>{n[lang]}</span>
              <Toggle defaultOn={n.on} color={accent}/>
            </div>
          ))}
        </div>
      </Panel>
      <Panel title={lang==="fa"?"محدودهٔ ارسال":"Delivery zone"} span="1 / -1">
        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          <Field2 label={lang==="fa"?"حداکثر فاصله":"Max distance"} value={lang==="fa"?"۸ کیلومتر":"8 km"}/>
          <Field2 label={lang==="fa"?"حداقل سفارش":"Minimum order"} value={<Price value={120000}/>}/>
          <Field2 label={lang==="fa"?"ارسال رایگان از":"Free delivery from"} value={<Price value={350000}/>}/>
        </div>
      </Panel>
    </div>
  );
}
function Field2({ label, value }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "12px 14px", background: "rgba(255,244,226,0.04)", borderRadius: 12 }}>
      <span style={{ fontSize: 13, opacity: 0.7 }}>{label}</span>
      <span style={{ fontFamily: "var(--display)", fontSize: 15 }}>{value}</span>
    </div>
  );
}

window.Overview = Overview;
window.OrdersTab = OrdersTab;
window.MenuTab = MenuTab;
window.StaffTab = StaffTab;
window.ReportsTab = ReportsTab;
window.SettingsTab = SettingsTab;
window.OrdersTable = OrdersTable;
window.Panel = Panel;
window.CustomersTab = CustomersTab;
