// N9NE Admin Dashboard — nine.ub9.com

// ─── Login ────────────────────────────────────────────────────
function LoginScreen({ onLogin }) {
  const [user, setUser] = React.useState("");
  const [pass, setPass] = React.useState("");
  const [err,  setErr]  = React.useState("");
  const [show, setShow] = React.useState(false);

  const login = () => {
    if (user === "ireedui8060" && pass === "admin0829") {
      sessionStorage.setItem("n9_admin_auth", "1");
      // Clear any old sample data — keep only real orders
      try {
        const saved = JSON.parse(localStorage.getItem("n9_admin_orders") || "[]");
        const real = saved.filter(o => o.customer && o.phone && o.address);
        localStorage.setItem("n9_admin_orders", JSON.stringify(real));
      } catch(e) {}
      onLogin();
    } else {
      setErr("Нэвтрэх нэр эсвэл нууц үг буруу байна.");
    }
  };

  return (
    <div style={{ minHeight:"100vh", background:"#1F1D23", display:"flex", alignItems:"center", justifyContent:"center", padding:24 }}>
      <div style={{ background:"#fff", borderRadius:24, padding:"48px 40px", width:400, boxShadow:"0 8px 40px rgba(0,0,0,0.3)" }}>
        <div style={{ fontFamily:"JetBrains Mono, monospace", fontSize:11, letterSpacing:"0.18em", textTransform:"uppercase", color:"#8A8990", marginBottom:8 }}>
          / ADMIN · nine.ub9.com /
        </div>
        <h1 style={{ fontFamily:"Inter, sans-serif", fontWeight:900, fontSize:36, letterSpacing:"-0.03em", textTransform:"uppercase", color:"#0E0D11", margin:"0 0 32px", lineHeight:0.95 }}>
          N9NE<br/>ADMIN
        </h1>
        <div style={{ marginBottom:16 }}>
          <label style={{ fontFamily:"JetBrains Mono, monospace", fontSize:10, letterSpacing:"0.12em", textTransform:"uppercase", color:"#8A8990", display:"block", marginBottom:7 }}>
            Нэвтрэх нэр
          </label>
          <input
            style={{ width:"100%", border:"1px solid #E8E7E9", borderRadius:12, padding:"13px 14px", fontFamily:"Inter, sans-serif", fontSize:14, color:"#0E0D11", outline:"none", boxSizing:"border-box" }}
            value={user}
            onChange={e => { setUser(e.target.value); setErr(""); }}
            placeholder="username"
            onKeyDown={e => e.key === "Enter" && login()}
          />
        </div>
        <div style={{ marginBottom:8 }}>
          <label style={{ fontFamily:"JetBrains Mono, monospace", fontSize:10, letterSpacing:"0.12em", textTransform:"uppercase", color:"#8A8990", display:"block", marginBottom:7 }}>
            Нууц үг
          </label>
          <div style={{ position:"relative" }}>
            <input
              type={show ? "text" : "password"}
              style={{ width:"100%", border:"1px solid #E8E7E9", borderRadius:12, padding:"13px 44px 13px 14px", fontFamily:"Inter, sans-serif", fontSize:14, color:"#0E0D11", outline:"none", boxSizing:"border-box" }}
              value={pass}
              onChange={e => { setPass(e.target.value); setErr(""); }}
              placeholder="••••••••"
              onKeyDown={e => e.key === "Enter" && login()}
            />
            <button onClick={() => setShow(!show)} style={{ position:"absolute", right:12, top:"50%", transform:"translateY(-50%)", background:"none", border:"none", cursor:"pointer", color:"#8A8990", fontSize:16 }}>
              {show ? "○" : "●"}
            </button>
          </div>
        </div>
        {err && <div style={{ fontFamily:"Inter, sans-serif", fontSize:13, color:"#FF3B6F", marginBottom:12 }}>{err}</div>}
        <button onClick={login} style={{ width:"100%", background:"#1F1D23", color:"#fff", border:"none", borderRadius:12, padding:"15px", fontFamily:"Inter, sans-serif", fontWeight:700, fontSize:15, cursor:"pointer", marginTop:8 }}>
          Нэвтрэх
        </button>
        <div style={{ marginTop:20, textAlign:"center" }}>
          <a href="index.html" style={{ fontFamily:"Inter, sans-serif", fontSize:13, color:"#8A8990", textDecoration:"none" }}>
            ← Дэлгүүр рүү буцах
          </a>
        </div>
      </div>
    </div>
  );
}

// ─── Utils ────────────────────────────────────────────────────
const fmtPrice = n => "₮" + Number(n).toLocaleString();

function rndCode() {
  const a = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
  return "N9-" + Array.from({length: 6}, () => a[Math.floor(Math.random() * a.length)]).join("");
}

function lsGet(k, d) {
  try { const v = localStorage.getItem(k); return v ? JSON.parse(v) : d; } catch(e) { return d; }
}
function lsSave(k, v) {
  try { localStorage.setItem(k, JSON.stringify(v)); } catch(e) {}
}

// ─── Keys ─────────────────────────────────────────────────────
const PRODUCTS_KEY  = "n9_admin_products";
const ORDERS_KEY    = "n9_admin_orders";
const COUPONS_KEY   = "n9_admin_coupons";
const CATS_KEY      = "n9_admin_cats";
const TAGS_KEY      = "n9_admin_tags";

// ─── Constants ────────────────────────────────────────────────
const DEFAULT_CATS = ["All", "iPod", "MP4", "iPhone", "Earphones", "Accessories"];
const DEFAULT_TAGS = ["NEW DROP", "LIMITED", "BEST SELLER", "TOP RATED", "SOLD OUT", "COMING SOON"];

const STATUS_LIST  = ["pending", "confirmed", "shipping", "delivered", "cancelled"];
const STATUS_MN    = { pending: "Хүлээгдэж байна", confirmed: "Баталгаажсан", shipping: "Хүргэлтэнд", delivered: "Хүргэгдсэн", cancelled: "Цуцлагдсан" };
const STATUS_COLOR = { pending: "#FF6A30", confirmed: "#D97706", shipping: "#2563EB", delivered: "#16A34A", cancelled: "#98979E" };

const INITIAL_COUPONS = [
  { id: 1, code: "N9-LAUNCH", discount: 15, expires: "2026-06-30", uses: 3, maxUses: 50, active: true },
  { id: 2, code: "N9-VIP20",  discount: 20, expires: "2026-05-31", uses: 8, maxUses: 20, active: true },
];

// ─── Styles ───────────────────────────────────────────────────
const S = {
  sidebar: { width: 220, minHeight: "100vh", background: "#1F1D23", display: "flex", flexDirection: "column", flexShrink: 0 },
  logo: { padding: "28px 24px 20px", borderBottom: "1px solid rgba(255,255,255,0.08)" },
  logoMark: { fontFamily: "Inter, sans-serif", fontWeight: 900, fontSize: 22, letterSpacing: "-0.03em", textTransform: "uppercase", color: "#fff", margin: 0 },
  logoSub: { fontFamily: "JetBrains Mono, monospace", fontSize: 10, letterSpacing: "0.15em", color: "rgba(255,255,255,0.35)", textTransform: "uppercase", marginTop: 5 },
  navItem: active => ({
    display: "flex", alignItems: "center", gap: 10, padding: "12px 24px", width: "100%", textAlign: "left",
    fontFamily: "Inter, sans-serif", fontSize: 14, fontWeight: active ? 600 : 400,
    color: active ? "#fff" : "rgba(255,255,255,0.45)",
    background: active ? "rgba(255,255,255,0.07)" : "transparent",
    borderLeft: active ? "2px solid #FFEC42" : "2px solid transparent",
    border: "none", cursor: "pointer", transition: "all 0.15s",
  }),
  main: { flex: 1, background: "#FAFAFB", minHeight: "100vh" },
  wrap: { maxWidth: 1080, margin: "0 auto", padding: "36px 32px" },
  panelHead: { display: "flex", justifyContent: "space-between", alignItems: "flex-end", marginBottom: 28 },
  meta: { fontFamily: "JetBrains Mono, monospace", fontSize: 10, letterSpacing: "0.15em", textTransform: "uppercase", color: "#8A8990" },
  h2: { margin: "6px 0 0", fontFamily: "Inter, sans-serif", fontWeight: 900, fontSize: 34, letterSpacing: "-0.03em", textTransform: "uppercase", color: "#0E0D11" },
  tableBox: { background: "#fff", border: "1px solid #E8E7E9", borderRadius: 16, overflow: "hidden" },
  table: { width: "100%", borderCollapse: "collapse" },
  th: { fontFamily: "JetBrains Mono, monospace", fontSize: 10, letterSpacing: "0.12em", textTransform: "uppercase", color: "#8A8990", padding: "12px 16px", textAlign: "left", background: "#FAFAFB", borderBottom: "1px solid #E8E7E9" },
  td: { fontFamily: "Inter, sans-serif", fontSize: 14, color: "#0E0D11", padding: "14px 16px", borderBottom: "1px solid #F2F1F3", verticalAlign: "middle" },
  sub: { fontFamily: "Inter, sans-serif", fontSize: 12, color: "#8A8990", marginTop: 2, display: "block" },
  btnDark: { background: "#1F1D23", color: "#fff", border: "none", borderRadius: 10, padding: "12px 20px", fontFamily: "Inter, sans-serif", fontWeight: 600, fontSize: 14, cursor: "pointer" },
  btnSm: { background: "transparent", border: "1px solid #E8E7E9", borderRadius: 8, padding: "6px 12px", fontFamily: "Inter, sans-serif", fontSize: 13, cursor: "pointer", color: "#0E0D11" },
  btnOutline: { background: "transparent", border: "1px solid #E8E7E9", borderRadius: 10, padding: "11px 18px", fontFamily: "Inter, sans-serif", fontWeight: 500, fontSize: 14, cursor: "pointer", color: "#0E0D11", width: "100%" },
  salePill: { background: "#FF6A30", color: "#fff", fontFamily: "JetBrains Mono, monospace", fontSize: 10, letterSpacing: "0.1em", padding: "3px 9px", borderRadius: 999 },
  badgePill: { background: "#FFEC42", color: "#0E0D11", fontFamily: "JetBrains Mono, monospace", fontSize: 10, letterSpacing: "0.1em", padding: "3px 9px", borderRadius: 999 },
  chip: { background: "#FAFAFB", border: "1px solid #E8E7E9", color: "#4A4852", fontFamily: "JetBrains Mono, monospace", fontSize: 10, letterSpacing: "0.1em", padding: "3px 9px", borderRadius: 999 },
  statCard: { background: "#fff", border: "1px solid #E8E7E9", borderRadius: 16, padding: "24px", flex: 1 },
  statNum: { fontFamily: "Inter, sans-serif", fontWeight: 900, fontSize: 44, letterSpacing: "-0.04em", color: "#0E0D11", lineHeight: 1 },
  statLbl: { fontFamily: "JetBrains Mono, monospace", fontSize: 10, letterSpacing: "0.15em", textTransform: "uppercase", color: "#8A8990", marginTop: 8 },
  overlay: { position: "fixed", inset: 0, background: "rgba(14,13,17,0.5)", zIndex: 200, display: "flex", alignItems: "center", justifyContent: "center", padding: 24 },
  modal: { background: "#fff", borderRadius: 20, padding: "32px", width: 580, maxHeight: "88vh", overflowY: "auto", boxShadow: "0 8px 32px rgba(14,13,17,0.14)" },
  modalTitle: { fontFamily: "Inter, sans-serif", fontWeight: 900, fontSize: 22, letterSpacing: "-0.02em", color: "#0E0D11", margin: "0 0 24px" },
  label: { fontFamily: "JetBrains Mono, monospace", fontSize: 10, letterSpacing: "0.12em", textTransform: "uppercase", color: "#8A8990", display: "block", marginBottom: 7 },
  input: { width: "100%", border: "1px solid #E8E7E9", borderRadius: 12, padding: "11px 14px", fontFamily: "Inter, sans-serif", fontSize: 14, color: "#0E0D11", background: "#fff", outline: "none", boxSizing: "border-box" },
  select: { width: "100%", border: "1px solid #E8E7E9", borderRadius: 12, padding: "11px 14px", fontFamily: "Inter, sans-serif", fontSize: 14, color: "#0E0D11", background: "#fff", outline: "none", boxSizing: "border-box" },
  row: { marginBottom: 18 },
  grid2: { display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 },
};

// ─── Mobile hook ──────────────────────────────────────────────
function useIsMobile() {
  const [m, setM] = React.useState(window.innerWidth < 768);
  React.useEffect(() => {
    const h = () => setM(window.innerWidth < 768);
    window.addEventListener("resize", h);
    return () => window.removeEventListener("resize", h);
  }, []);
  return m;
}

// ─── Shared components ────────────────────────────────────────
function StatusBadge({ status }) {
  const color = STATUS_COLOR[status] || "#98979E";
  return (
    <span style={{ background: color + "1A", color, fontFamily: "JetBrains Mono, monospace", fontSize: 10, letterSpacing: "0.1em", padding: "4px 10px", borderRadius: 999, textTransform: "uppercase", whiteSpace: "nowrap" }}>
      {STATUS_MN[status] || status}
    </span>
  );
}

// ─── ProductModal ─────────────────────────────────────────────
function resizeImg(file, cb) {
  const reader = new FileReader();
  reader.onload = ev => {
    const canvas = document.createElement("canvas");
    const img = document.createElement("img");
    img.onload = () => {
      const max = 700;
      let w = img.naturalWidth, h = img.naturalHeight;
      if (w > max || h > max) {
        if (w > h) { h = Math.round(h * max / w); w = max; }
        else { w = Math.round(w * max / h); h = max; }
      }
      canvas.width = w; canvas.height = h;
      canvas.getContext("2d").drawImage(img, 0, 0, w, h);
      cb(canvas.toDataURL("image/jpeg", 0.82));
    };
    img.src = ev.target.result;
  };
  reader.readAsDataURL(file);
}

function ProductModal({ p, cats, tags, onSave, onClose }) {
  const existImgs = p.imgs && p.imgs.length ? p.imgs : (p.img ? [p.img] : []);
  const [f, setF] = React.useState({
    name: p.name || "", sub: p.sub || "", cat: p.cat || "iPod",
    price: p.price || "", was: p.was || "", sale: p.sale || "",
    badge: p.badge || "", tagline: p.tagline || "",
    desc: p.desc || "",
    colors: (p.colors || []).join(", "),
    imgs: existImgs,
  });
  const set = (k, v) => setF(x => ({...x, [k]: v}));

  const autoSale = (price, was) => {
    const p = Number(price), w = Number(was);
    if (p > 0 && w > p) return String(Math.round((1 - p / w) * 100));
    return "";
  };

  const handlePrice = v => {
    setF(x => ({ ...x, price: v, sale: autoSale(v, x.was) }));
  };
  const handleWas = v => {
    setF(x => ({ ...x, was: v, sale: autoSale(x.price, v) }));
  };

  const handleImgs = e => {
    const files = Array.from(e.target.files);
    files.forEach(file => {
      resizeImg(file, url => {
        setF(x => ({ ...x, imgs: [...x.imgs, url] }));
      });
    });
    e.target.value = "";
  };

  const removeImg = idx => setF(x => ({ ...x, imgs: x.imgs.filter((_, i) => i !== idx) }));
  const moveImg = (idx, dir) => {
    setF(x => {
      const arr = [...x.imgs];
      const to = idx + dir;
      if (to < 0 || to >= arr.length) return x;
      [arr[idx], arr[to]] = [arr[to], arr[idx]];
      return { ...x, imgs: arr };
    });
  };

  const save = () => {
    if (!f.name || !f.price) return;
    onSave({
      ...p,
      ...f,
      price: Number(f.price),
      was: f.was ? Number(f.was) : null,
      sale: f.sale ? Number(f.sale) : null,
      badge: f.badge || null,
      imgs: f.imgs,
      img: f.imgs[0] || null,
      colors: f.colors.split(",").map(c => c.trim()).filter(Boolean),
      palette: p.palette || ["#FAFAFB", "#0E0D11"],
      id: p.id || (f.name.toLowerCase().replace(/[^a-z0-9]/g, "-") + "-" + Date.now().toString(36)),
    });
  };

  const allTags = ["", ...tags];

  return (
    <div style={S.overlay} onClick={e => e.target === e.currentTarget && onClose()}>
      <div style={S.modal}>
        <h3 style={S.modalTitle}>{p.id ? "Бараа засах" : "Шинэ бараа нэмэх"}</h3>

        {/* Multi-image upload */}
        <div style={{ ...S.row, marginBottom: 22 }}>
          <label style={S.label}>Барааны зурагнууд</label>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 10, marginBottom: 10 }}>
            {f.imgs.map((src, i) => (
              <div key={i} style={{ position: "relative", width: 80, height: 80, borderRadius: 12, border: i === 0 ? "2px solid #0E0D11" : "1px solid #E8E7E9", overflow: "hidden", flexShrink: 0 }}>
                <img src={src} style={{ width: "100%", height: "100%", objectFit: "cover" }} />
                {i === 0 && <div style={{ position: "absolute", bottom: 0, left: 0, right: 0, background: "#0E0D11", color: "#fff", fontFamily: "JetBrains Mono", fontSize: 8, letterSpacing: "0.1em", textAlign: "center", padding: "3px 0" }}>ҮНДСЭН</div>}
                <button onClick={() => removeImg(i)} style={{ position: "absolute", top: 3, right: 3, width: 18, height: 18, borderRadius: 999, background: "#FF3B6F", color: "#fff", border: "none", cursor: "pointer", fontSize: 10, lineHeight: 1, display: "flex", alignItems: "center", justifyContent: "center" }}>×</button>
                {i > 0 && <button onClick={() => moveImg(i, -1)} style={{ position: "absolute", top: 3, left: 3, width: 18, height: 18, borderRadius: 999, background: "rgba(0,0,0,0.5)", color: "#fff", border: "none", cursor: "pointer", fontSize: 10 }}>←</button>}
              </div>
            ))}
            <label style={{ width: 80, height: 80, borderRadius: 12, border: "1.5px dashed #C9C8CE", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", cursor: "pointer", gap: 4, background: "#FAFAFB" }}>
              <span style={{ fontSize: 22, color: "#C9C8CE" }}>+</span>
              <span style={{ fontFamily: "Inter", fontSize: 10, color: "#C9C8CE" }}>Зураг</span>
              <input type="file" accept="image/*" multiple style={{ display: "none" }} onChange={handleImgs} />
            </label>
          </div>
          <span style={{ fontFamily: "Inter", fontSize: 12, color: "#C9C8CE" }}>JPG, PNG · Max 700px · Эхний зураг үндсэн зураг болно</span>
        </div>

        <div style={S.grid2}>
          <div style={S.row}>
            <label style={S.label}>Нэр *</label>
            <input style={S.input} value={f.name} onChange={e => set("name", e.target.value)} placeholder="iPod nano 4th gen" />
          </div>
          <div style={S.row}>
            <label style={S.label}>Дэд нэр</label>
            <input style={S.input} value={f.sub} onChange={e => set("sub", e.target.value)} placeholder="Silver · 8GB" />
          </div>
          <div style={S.row}>
            <label style={S.label}>Үнэ (₮) *</label>
            <input style={S.input} type="number" value={f.price} onChange={e => handlePrice(e.target.value)} placeholder="189000" />
          </div>
          <div style={S.row}>
            <label style={S.label}>Анхны үнэ (₮)</label>
            <input style={S.input} type="number" value={f.was} onChange={e => handleWas(e.target.value)} placeholder="320000" />
          </div>
          <div style={S.row}>
            <label style={S.label}>Хямдрал (%){f.sale && f.was ? " · авто тооцоолсон" : ""}</label>
            <input style={{...S.input, background: f.sale && f.was ? "#FFEC4220" : "#fff"}} type="number" min="0" max="100" value={f.sale} onChange={e => set("sale", e.target.value)} placeholder="40" />
          </div>
          <div style={S.row}>
            <label style={S.label}>Ангилал</label>
            <select style={S.select} value={f.cat} onChange={e => set("cat", e.target.value)}>
              {cats.filter(c => c !== "All").map(c => <option key={c}>{c}</option>)}
            </select>
          </div>
        </div>
        <div style={S.row}>
          <label style={S.label}>Badge / Tag</label>
          <select style={S.select} value={f.badge} onChange={e => set("badge", e.target.value)}>
            {allTags.map(t => <option key={t} value={t}>{t || "— Badge байхгүй —"}</option>)}
          </select>
        </div>
        <div style={S.row}>
          <label style={S.label}>Tagline</label>
          <input style={S.input} value={f.tagline} onChange={e => set("tagline", e.target.value)} placeholder="Чамайг харсан хүн бүхэн асуух болно." />
        </div>
        <div style={S.row}>
          <label style={S.label}>Тайлбар</label>
          <textarea style={{...S.input, minHeight:90, resize:"vertical", lineHeight:1.6}} value={f.desc} onChange={e => set("desc", e.target.value)} placeholder="Барааны дэлгэрэнгүй тайлбар..." />
        </div>
        <div style={S.row}>
          <label style={S.label}>Өнгөнүүд (таслалаар)</label>
          <input style={S.input} value={f.colors} onChange={e => set("colors", e.target.value)} placeholder="Silver, Black, Pink" />
        </div>
        <div style={{ display: "flex", gap: 10, justifyContent: "flex-end", marginTop: 8 }}>
          <button style={S.btnOutline} onClick={onClose}>Цуцлах</button>
          <button style={S.btnDark} onClick={save}>Хадгалах</button>
        </div>
      </div>
    </div>
  );
}

// ─── ProductsPanel ────────────────────────────────────────────
function ProductsPanel({ cats, tags }) {
  const isMobile = useIsMobile();
  const [products, setProducts] = React.useState(() => lsGet(PRODUCTS_KEY, []));
  const [editing, setEditing] = React.useState(null);
  const [adding, setAdding] = React.useState(false);
  const initialized = React.useRef(false);

  React.useEffect(() => {
    fetch("/api/get-products?t=" + Date.now())
      .then(r => r.json())
      .then(data => {
        if (data && data.length) {
          setProducts(data);
          lsSave(PRODUCTS_KEY, data);
        } else {
          if (!products.length) setProducts(window.N9_PRODUCTS || []);
          const local = lsGet(PRODUCTS_KEY, []);
          if (local.length) {
            fetch("/api/save-products", {
              method: "POST",
              headers: { "Content-Type": "application/json", "x-admin-key": "admin0829" },
              body: JSON.stringify(local),
            }).catch(() => {});
          }
        }
        initialized.current = true;
      })
      .catch(() => { initialized.current = true; });
  }, []);

  React.useEffect(() => {
    if (!initialized.current) return;
    lsSave(PRODUCTS_KEY, products);
    fetch("/api/save-products", {
      method: "POST",
      headers: { "Content-Type": "application/json", "x-admin-key": "admin0829" },
      body: JSON.stringify(products),
    }).catch(() => {});
  }, [products]);

  const save = p => {
    if (p.id && products.find(x => x.id === p.id)) {
      setProducts(products.map(x => x.id === p.id ? p : x));
    } else {
      setProducts([...products, p]);
    }
    setEditing(null); setAdding(false);
  };

  const del = id => {
    if (!confirm("Энэ барааг устгах уу?")) return;
    setProducts(products.filter(p => p.id !== id));
  };

  return (
    <div style={S.wrap}>
      <div style={S.panelHead}>
        <div>
          <div style={S.meta}>/ БҮТЭЭГДЭХҮҮН /</div>
          <h2 style={S.h2}>{products.length} барааны жагсаалт</h2>
        </div>
        <button style={S.btnDark} onClick={() => setAdding(true)}>+ Шинэ бараа</button>
      </div>
      <div style={{ ...S.tableBox, overflowX: isMobile ? "auto" : "visible", WebkitOverflowScrolling: "touch" }}>
        <table style={{ ...S.table, minWidth: isMobile ? 700 : "100%" }}>
          <thead>
            <tr>
              {["", "Бараа", "Ангилал", "Үнэ", "Үндсэн үнэ", "Хямдрал", "Badge", ""].map((h, i) => <th key={i} style={S.th}>{h}</th>)}
            </tr>
          </thead>
          <tbody>
            {products.map(p => (
              <tr key={p.id}>
                <td style={{ ...S.td, width: 56, padding: "10px 8px 10px 16px" }}>
                  <div style={{ width: 44, height: 44, borderRadius: 10, background: p.palette ? p.palette[0] : "#FAFAFB", border: "1px solid #E8E7E9", overflow: "hidden", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                    {(p.imgs && p.imgs[0]) || p.img
                      ? <img src={(p.imgs && p.imgs[0]) || p.img} style={{ width: "100%", height: "100%", objectFit: "cover" }} />
                      : <span style={{ fontFamily: "JetBrains Mono, monospace", fontSize: 14, color: "#C9C8CE" }}>◎</span>
                    }
                  </div>
                </td>
                <td style={S.td}>
                  <div style={{ fontWeight: 600, whiteSpace: "nowrap" }}>{p.name}</div>
                  <span style={S.sub}>{p.sub}</span>
                </td>
                <td style={S.td}><span style={S.chip}>{p.cat}</span></td>
                <td style={S.td}><b style={{ whiteSpace: "nowrap" }}>{fmtPrice(p.price)}</b></td>
                <td style={S.td}>
                  {p.was
                    ? <span style={{ fontFamily: "Inter", fontSize: 13, color: "#8A8990", textDecoration: "line-through", whiteSpace: "nowrap" }}>{fmtPrice(p.was)}</span>
                    : <span style={{ color: "#C9C8CE" }}>—</span>
                  }
                </td>
                <td style={S.td}>{p.sale ? <span style={S.salePill}>-{p.sale}%</span> : <span style={{ color: "#C9C8CE" }}>—</span>}</td>
                <td style={S.td}>{p.badge ? <span style={S.badgePill}>{p.badge}</span> : <span style={{ color: "#C9C8CE" }}>—</span>}</td>
                <td style={S.td}>
                  <button style={{ ...S.btnSm, whiteSpace: "nowrap" }} onClick={() => setEditing(p)}>Засах</button>
                  <button style={{ ...S.btnSm, marginLeft: 8, color: "#FF3B6F", borderColor: "#FF3B6F33", whiteSpace: "nowrap" }} onClick={() => del(p.id)}>Устгах</button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      {(editing || adding) && (
        <ProductModal
          p={editing || {}} cats={cats} tags={tags}
          onSave={save}
          onClose={() => { setEditing(null); setAdding(false); }}
        />
      )}
    </div>
  );
}

// ─── OrderDetail ──────────────────────────────────────────────
function OrderDetail({ order, onBack, onStatusChange }) {
  const [curStatus, setCurStatus] = React.useState(order.status);

  const copy = (text) => navigator.clipboard.writeText(String(text)).catch(() => {});

  const handleStatus = (s) => {
    setCurStatus(s);
    onStatusChange(order.id, s);
  };

  const addrParts = (order.address || "").split(", ").filter(Boolean);

  const addrLabels = ["Хот/аймаг", "Дүүрэг/сум", "Хороо/баг", "Байр", "Давхар", "Тоот"];

  const card = { background: "#fff", borderRadius: 16, padding: "18px 20px", marginBottom: 12, boxShadow: "0 1px 4px rgba(0,0,0,0.06)" };
  const sectionTitle = { fontFamily: "Inter, sans-serif", fontWeight: 700, fontSize: 15, color: "#0E0D11", marginBottom: 12, marginTop: 0 };

  const InfoRow = ({ value }) => (
    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "11px 0", borderBottom: "1px solid #F2F1F3" }}>
      <span style={{ fontFamily: "Inter, sans-serif", fontSize: 15, color: "#0E0D11" }}>{value}</span>
      <button onClick={() => copy(value)} style={{ background: "none", border: "none", cursor: "pointer", padding: "4px 8px", color: "#8A8990", fontSize: 18, lineHeight: 1, flexShrink: 0 }}>⎘</button>
    </div>
  );

  return (
    <div style={{ ...S.wrap, paddingTop: 16 }}>
      <button onClick={onBack} style={{ background: "none", border: "none", cursor: "pointer", fontFamily: "Inter, sans-serif", fontWeight: 600, fontSize: 14, color: "#0E0D11", marginBottom: 18, padding: 0, display: "flex", alignItems: "center", gap: 6 }}>
        ← Буцах
      </button>

      {/* Status badges */}
      <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginBottom: 20 }}>
        <span style={{ padding: "6px 16px", borderRadius: 999, background: "#E8F0FF", color: "#2563EB", fontFamily: "Inter, sans-serif", fontWeight: 600, fontSize: 13 }}>Хүргэлтээр</span>
        <StatusBadge status={curStatus} />
      </div>

      {/* Customer info */}
      <div style={card}>
        <p style={sectionTitle}>Хэрэглэгчийн мэдээлэл</p>
        <InfoRow value={order.phone} />
        <InfoRow value={order.customer} />
        {order.email && <InfoRow value={order.email} />}
      </div>

      {/* Delivery & address */}
      <div style={card}>
        <p style={sectionTitle}>Хүргэлтийн төрөл</p>
        <div style={{ textAlign: "center", padding: "13px", background: "#E8F0FF", borderRadius: 12, fontFamily: "Inter, sans-serif", fontWeight: 600, fontSize: 14, color: "#2563EB", marginBottom: 20 }}>
          Хүргэлтээр
        </div>
        <p style={sectionTitle}>Хүргүүлэх хаягийн мэдээлэл</p>
        {addrParts.map((part, i) => (
          <div key={i} style={{ display: "flex", justifyContent: "space-between", padding: "7px 0", borderBottom: i < addrParts.length - 1 ? "1px solid #F2F1F3" : "none" }}>
            <span style={{ fontFamily: "Inter, sans-serif", fontSize: 13, color: "#8A8990" }}>{addrLabels[i] || ""}</span>
            <span style={{ fontFamily: "Inter, sans-serif", fontSize: 13, color: "#0E0D11", fontWeight: 500 }}>{part}</span>
          </div>
        ))}
      </div>

      {/* Products */}
      <div style={card}>
        <p style={sectionTitle}>Захиалсан бараа</p>
        <div style={{ fontFamily: "Inter, sans-serif", fontSize: 14, color: "#4A4852", lineHeight: 1.7 }}>{order.products}</div>
        <div style={{ display: "flex", justifyContent: "space-between", marginTop: 14, paddingTop: 12, borderTop: "1px solid #F2F1F3" }}>
          <span style={{ fontFamily: "Inter, sans-serif", fontWeight: 700, fontSize: 15 }}>Нийт</span>
          <span style={{ fontFamily: "Inter, sans-serif", fontWeight: 700, fontSize: 15 }}>{fmtPrice(order.total)}</span>
        </div>
      </div>

      {/* Payment */}
      <div style={card}>
        <p style={sectionTitle}>Төлбөрийн хэлбэр</p>
        <span style={{ background: order.payment === "bank" ? "#2563EB1A" : "#16A34A1A", color: order.payment === "bank" ? "#2563EB" : "#16A34A", fontFamily: "Inter, sans-serif", fontWeight: 600, fontSize: 13, padding: "6px 14px", borderRadius: 999 }}>
          {order.payment === "bank" ? "Дансаар" : "Бэлнээр"}
        </span>
      </div>

      {/* Status change */}
      <div style={card}>
        <p style={sectionTitle}>Статус өөрчлөх</p>
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          {STATUS_LIST.map(s => (
            <button key={s} onClick={() => handleStatus(s)} style={{
              padding: "12px 16px", borderRadius: 12, border: "none", cursor: "pointer", textAlign: "left",
              background: curStatus === s ? "#1F1D23" : "#F2F1F3",
              color: curStatus === s ? "#fff" : "#0E0D11",
              fontFamily: "Inter, sans-serif", fontWeight: 600, fontSize: 14,
              display: "flex", alignItems: "center", gap: 10,
            }}>
              <span style={{ width: 8, height: 8, borderRadius: 999, background: STATUS_COLOR[s], flexShrink: 0 }} />
              {STATUS_MN[s]}
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

// ─── OrdersPanel ──────────────────────────────────────────────
function OrdersPanel() {
  const [orders, setOrders] = React.useState(() => lsGet(ORDERS_KEY, []));
  const [filter, setFilter] = React.useState("all");
  const [search, setSearch] = React.useState("");
  const [loading, setLoading] = React.useState(false);
  const [selected, setSelected] = React.useState(null);
  const [backupBanner, setBackupBanner] = React.useState(null);

  const restoreFromBackup = (backup) => {
    setOrders(backup);
    lsSave(ORDERS_KEY, backup);
    fetch("/api/save-order-list", {
      method: "POST",
      headers: { "Content-Type": "application/json", "x-admin-key": "admin0829" },
      body: JSON.stringify(backup),
    }).catch(() => {});
    setBackupBanner(null);
  };

  const fetchOrders = () => {
    setLoading(true);
    fetch("/api/get-orders?t=" + Date.now())
      .then(r => r.json())
      .then(data => {
        if (data && data.length) {
          setOrders(data);
          lsSave(ORDERS_KEY, data);
        } else {
          const backup = lsGet(ORDERS_KEY, []);
          if (backup.length) setBackupBanner(backup);
        }
        setLoading(false);
      })
      .catch(() => setLoading(false));
  };

  React.useEffect(() => {
    fetchOrders();
    const interval = setInterval(fetchOrders, 300000);
    return () => clearInterval(interval);
  }, []);

  const q = search.trim().toLowerCase();
  const visible = orders
    .filter(o => filter === "all" || o.status === filter)
    .filter(o => !q || (o.id || "").toLowerCase().includes(q) || (o.customer || "").toLowerCase().includes(q) || (o.phone || "").includes(q));
  const revenue = orders.reduce((s, o) => s + o.total, 0);
  const delivered = orders.filter(o => o.status === "delivered").length;

  const handleStatusChange = (id, status) => {
    const next = orders.map(o => o.id === id ? {...o, status} : o);
    setOrders(next);
    setSelected(prev => prev && prev.id === id ? {...prev, status} : prev);
    fetch("/api/save-order-list", {
      method: "POST",
      headers: { "Content-Type": "application/json", "x-admin-key": "admin0829" },
      body: JSON.stringify(next),
    }).catch(() => {});
  };

  const resetOrders = () => {
    if (!window.confirm(`Нийт ${orders.length} захиалгыг устгах уу? Энэ үйлдлийг буцаах боломжгүй.`)) return;
    lsSave(ORDERS_KEY, []);
    setOrders([]);
    fetch("/api/save-order-list", {
      method: "POST",
      headers: { "Content-Type": "application/json", "x-admin-key": "admin0829" },
      body: JSON.stringify([]),
    }).catch(() => {});
  };

  const exportExcel = () => {
    if (!orders.length) return;
    const cols = ["ID", "Огноо", "Хэрэглэгч", "Утас", "Бараа", "Хаяг", "Төлбөр", "Дүн (₮)", "Статус"];
    const rows = orders.map(o => [
      o.id, o.date, o.customer, o.phone, o.products, o.address,
      o.payment === "bank" ? "Дансаар" : "Бэлнээр", o.total, STATUS_MN[o.status] || o.status,
    ]);
    const csvContent = [cols, ...rows]
      .map(r => r.map(v => `"${String(v ?? "").replace(/"/g, '""')}"`).join(","))
      .join("\n");
    const blob = new Blob(["﻿" + csvContent], { type: "text/csv;charset=utf-8;" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `n9ne-zahialga-${new Date().toISOString().slice(0,10)}.csv`;
    a.click();
    URL.revokeObjectURL(url);
  };

  if (selected) {
    return (
      <OrderDetail
        order={selected}
        onBack={() => setSelected(null)}
        onStatusChange={handleStatusChange}
      />
    );
  }

  return (
    <div style={S.wrap}>
      {backupBanner && (
        <div style={{ background:"#FFF7E6", border:"1px solid #F59E0B", borderRadius:14, padding:"16px 20px", marginBottom:20, display:"flex", alignItems:"center", justifyContent:"space-between", flexWrap:"wrap", gap:12 }}>
          <div>
            <div style={{ fontFamily:"Inter,sans-serif", fontWeight:700, fontSize:15, color:"#92400E" }}>Backup олдлоо</div>
            <div style={{ fontFamily:"Inter,sans-serif", fontSize:13, color:"#92400E", marginTop:3 }}>Локал backup-д <b>{backupBanner.length}</b> захиалга байна. Сэргээх үү?</div>
          </div>
          <div style={{ display:"flex", gap:8 }}>
            <button onClick={() => restoreFromBackup(backupBanner)} style={{ background:"#F59E0B", color:"#fff", border:"none", borderRadius:9, padding:"9px 18px", fontFamily:"Inter,sans-serif", fontWeight:700, fontSize:13, cursor:"pointer" }}>
              Сэргээх
            </button>
            <button onClick={() => setBackupBanner(null)} style={{ background:"transparent", color:"#92400E", border:"1px solid #F59E0B", borderRadius:9, padding:"9px 18px", fontFamily:"Inter,sans-serif", fontWeight:600, fontSize:13, cursor:"pointer" }}>
              Үгүй
            </button>
          </div>
        </div>
      )}
      <div style={S.panelHead}>
        <div>
          <div style={S.meta}>/ ЗАХИАЛГА /</div>
          <h2 style={S.h2}>{orders.length} захиалга</h2>
        </div>
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap", justifyContent: "flex-end" }}>
          <button onClick={fetchOrders} disabled={loading} style={{ display:"flex", alignItems:"center", gap:6, padding:"9px 16px", borderRadius:10, border:"1px solid #E8E7E9", background: loading ? "#F2F1F3" : "#fff", color:"#0E0D11", fontFamily:"Inter,sans-serif", fontWeight:600, fontSize:13, cursor:"pointer" }}>
            <span style={{ fontSize:16, lineHeight:1 }}>↻</span> Шинэчлэх
          </button>
          <button onClick={exportExcel} style={{ display:"flex", alignItems:"center", gap:6, padding:"9px 16px", borderRadius:10, border:"none", background:"#16A34A", color:"#fff", fontFamily:"Inter,sans-serif", fontWeight:600, fontSize:13, cursor:"pointer" }}>
            <span style={{ fontSize:14, lineHeight:1 }}>↓</span> Excel
          </button>
          <button onClick={resetOrders} style={{ display:"flex", alignItems:"center", gap:6, padding:"9px 16px", borderRadius:10, border:"1px solid #FF3B6F44", background:"#FF3B6F0D", color:"#FF3B6F", fontFamily:"Inter,sans-serif", fontWeight:600, fontSize:13, cursor:"pointer" }}>
            <span style={{ fontSize:14, lineHeight:1 }}>✕</span> Цэвэрлэх
          </button>
        </div>
      </div>

      {/* Stats */}
      <div style={{ display: "flex", gap: 16, marginBottom: 24 }}>
        <div style={S.statCard}><div style={S.statNum}>{orders.length}</div><div style={S.statLbl}>Нийт захиалга</div></div>
        <div style={S.statCard}><div style={S.statNum}>{delivered}</div><div style={S.statLbl}>Хүргэгдсэн</div></div>
        <div style={S.statCard}><div style={{...S.statNum, fontSize: 28}}>{fmtPrice(revenue)}</div><div style={S.statLbl}>Нийт орлого</div></div>
      </div>

      {/* Filter tabs */}
      <div style={{ display: "flex", gap: 8, marginBottom: 12, flexWrap: "wrap" }}>
        {["all", ...STATUS_LIST].map(s => (
          <button key={s} onClick={() => setFilter(s)} style={{
            ...S.btnSm,
            background: filter === s ? "#1F1D23" : "#fff",
            color: filter === s ? "#fff" : "#0E0D11",
            borderColor: filter === s ? "#1F1D23" : "#E8E7E9",
          }}>
            {s === "all" ? `Бүгд (${orders.length})` : `${STATUS_MN[s]} (${orders.filter(o => o.status === s).length})`}
          </button>
        ))}
      </div>

      {/* Search */}
      <div style={{ position: "relative", marginBottom: 20 }}>
        <span style={{ position: "absolute", left: 14, top: "50%", transform: "translateY(-50%)", color: "#C9C8CE", fontSize: 15, pointerEvents: "none" }}>⌕</span>
        <input
          value={search}
          onChange={e => setSearch(e.target.value)}
          placeholder="Нэр, утас, Order ID-р хайх..."
          style={{ width: "100%", boxSizing: "border-box", border: "1px solid #E8E7E9", borderRadius: 12, padding: "11px 14px 11px 38px", fontFamily: "Inter, sans-serif", fontSize: 14, color: "#0E0D11", background: "#fff", outline: "none" }}
        />
        {search && (
          <button onClick={() => setSearch("")} style={{ position: "absolute", right: 12, top: "50%", transform: "translateY(-50%)", background: "none", border: "none", cursor: "pointer", color: "#8A8990", fontSize: 16, lineHeight: 1 }}>✕</button>
        )}
      </div>

      {/* Order cards */}
      {visible.length === 0 ? (
        <div style={{ background: "#fff", borderRadius: 16, padding: "60px 24px", textAlign: "center" }}>
          <div style={{ fontFamily: "JetBrains Mono, monospace", fontSize: 32, color: "#E8E7E9", marginBottom: 16 }}>◎</div>
          <div style={{ fontFamily: "Inter", fontWeight: 700, fontSize: 18, color: "#0E0D11", marginBottom: 8 }}>
            {search ? `"${search}" олдсонгүй` : "Захиалга байхгүй байна"}
          </div>
          <div style={{ fontFamily: "Inter", fontSize: 14, color: "#8A8990" }}>
            {search ? "Нэр, утас эсвэл Order ID-г шалгаад дахин хайна уу." : "Website-с захиалга ирэхэд энд харагдана."}
          </div>
        </div>
      ) : (
        visible.map(o => (
          <div key={o.id} onClick={() => setSelected(o)} style={{
            background: "#fff", borderRadius: 16, padding: "18px 20px", marginBottom: 10,
            cursor: "pointer", border: "1px solid #F2F1F3", boxShadow: "0 1px 3px rgba(0,0,0,0.05)",
          }}>
            {/* Top row: ID + status */}
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 12 }}>
              <div>
                <div style={{ fontFamily: "JetBrains Mono, monospace", fontWeight: 700, fontSize: 13, color: "#0E0D11" }}>{o.id}</div>
                <div style={{ fontFamily: "Inter, sans-serif", fontSize: 12, color: "#8A8990", marginTop: 2 }}>{o.date}</div>
              </div>
              <StatusBadge status={o.status} />
            </div>
            {/* Customer row */}
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 12 }}>
              <div style={{ width: 38, height: 38, borderRadius: 999, background: "#1F1D23", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                <span style={{ fontFamily: "Inter, sans-serif", fontWeight: 700, fontSize: 15, color: "#fff" }}>
                  {(o.customer || "?")[0].toUpperCase()}
                </span>
              </div>
              <div>
                <div style={{ fontFamily: "Inter, sans-serif", fontWeight: 600, fontSize: 14, color: "#0E0D11" }}>{o.phone}</div>
                <div style={{ fontFamily: "Inter, sans-serif", fontSize: 12, color: "#8A8990" }}>{o.customer}</div>
              </div>
            </div>
            {/* Products row */}
            {o.items && o.items.length > 0 ? (
              <div style={{ display: "flex", gap: 8, marginBottom: 12, flexWrap: "wrap" }}>
                {o.items.map((it, i) => (
                  <div key={i} style={{ display: "flex", alignItems: "center", gap: 6, background: "#F2F1F3", borderRadius: 8, padding: "5px 8px" }}>
                    {it.img
                      ? <img src={it.img} style={{ width: 28, height: 28, borderRadius: 6, objectFit: "cover", flexShrink: 0 }} />
                      : <div style={{ width: 28, height: 28, borderRadius: 6, background: (it.palette && it.palette[0]) || "#E8E7E9", flexShrink: 0 }} />
                    }
                    <span style={{ fontFamily: "Inter, sans-serif", fontSize: 12, fontWeight: 600, color: "#0E0D11" }}>{it.name}</span>
                    <span style={{ fontFamily: "Inter, sans-serif", fontSize: 11, color: "#8A8990" }}>×{it.qty}</span>
                  </div>
                ))}
              </div>
            ) : o.products ? (
              <div style={{ fontFamily: "Inter, sans-serif", fontSize: 12, color: "#4A4852", marginBottom: 12 }}>{o.products}</div>
            ) : null}
            {/* Bottom row: city + amount + payment */}
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <span style={{ fontFamily: "Inter, sans-serif", fontSize: 12, color: "#4A4852" }}>
                {(o.address || "").split(",")[0]}
              </span>
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <b style={{ fontFamily: "Inter, sans-serif", fontWeight: 700, fontSize: 15, color: "#0E0D11" }}>{fmtPrice(o.total)}</b>
                <span style={{ fontFamily: "Inter, sans-serif", fontSize: 11, fontWeight: 600, background: o.payment === "bank" ? "#2563EB1A" : "#16A34A1A", color: o.payment === "bank" ? "#2563EB" : "#16A34A", padding: "3px 10px", borderRadius: 999 }}>
                  {o.payment === "bank" ? "Дансаар" : "Бэлнээр"}
                </span>
              </div>
            </div>
          </div>
        ))
      )}
    </div>
  );
}

// ─── StatsPanel ───────────────────────────────────────────────
function StatsPanel() {
  const [orders, setOrders] = React.useState(() => lsGet(ORDERS_KEY, []));
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    const load = () => {
      fetch("/api/get-orders?t=" + Date.now())
        .then(r => r.json())
        .then(data => {
          if (data && data.length) {
            setOrders(data);
            lsSave(ORDERS_KEY, data);
          }
        })
        .catch(() => {})
        .finally(() => setLoading(false));
    };
    load();
    const interval = setInterval(load, 300000);
    return () => clearInterval(interval);
  }, []);

  const byDay = {};
  orders.forEach(o => {
    const d = parseInt((o.date || "").split("-")[2], 10);
    if (d) byDay[d] = (byDay[d] || 0) + 1;
  });
  const daysInMonth = 31;
  const counts = Array.from({length: daysInMonth}, (_, i) => byDay[i + 1] || 0);
  const maxCount = Math.max(...counts, 1);
  const activeDays = Object.keys(byDay).length;
  const avg = activeDays ? (orders.length / activeDays).toFixed(1) : "0";
  const peakEntry = Object.entries(byDay).sort((a, b) => b[1] - a[1])[0];

  return (
    <div style={S.wrap}>
      <div style={S.panelHead}>
        <div>
          <div style={S.meta}>/ СТАТИСТИК · 2026 5-Р САР /</div>
          <h2 style={S.h2}>Захиалгын дүн шинжилгээ</h2>
        </div>
      </div>

      <div style={{ display: "flex", gap: 16, marginBottom: 28, flexWrap: "wrap" }}>
        <div style={S.statCard}><div style={{ ...S.statNum, color: loading ? "#C9C8CE" : "#0E0D11" }}>{orders.length}</div><div style={S.statLbl}>Нийт захиалга</div></div>
        <div style={S.statCard}><div style={{ ...S.statNum, color: loading ? "#C9C8CE" : "#0E0D11" }}>{avg}</div><div style={S.statLbl}>Өдрийн дундаж</div></div>
        <div style={S.statCard}><div style={{ ...S.statNum, color: loading ? "#C9C8CE" : "#0E0D11" }}>{peakEntry ? peakEntry[1] : 0}</div><div style={S.statLbl}>Хамгийн их өдөр {peakEntry ? `(5/${peakEntry[0]})` : ""}</div></div>
        <div style={S.statCard}><div style={{ ...S.statNum, color: loading ? "#C9C8CE" : "#0E0D11" }}>{activeDays}</div><div style={S.statLbl}>Захиалга авсан өдөр</div></div>
      </div>

      {/* Bar chart */}
      <div style={{ background: "#fff", border: "1px solid #E8E7E9", borderRadius: 16, padding: "28px 28px 20px" }}>
        <div style={S.meta}>Өдөр тус бүрийн захиалга — 5-р сар 2026</div>
        <div style={{ display: "flex", alignItems: "flex-end", gap: 3, height: 160, marginTop: 20 }}>
          {counts.map((c, i) => {
            const h = c === 0 ? 3 : Math.max(10, (c / maxCount) * 148);
            const isPeak = c === maxCount && c > 0;
            return (
              <div key={i} style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: 3 }}>
                {c > 0 && <span style={{ fontFamily: "Inter", fontSize: 10, color: "#4A4852", fontWeight: 600 }}>{c}</span>}
                <div title={`5/${i+1}: ${c} захиалга`} style={{
                  width: "100%", height: h,
                  background: c === 0 ? "#F2F1F3" : isPeak ? "#FFEC42" : "#0E0D11",
                  borderRadius: "3px 3px 0 0",
                }} />
                {(i + 1) % 5 === 0 || i === 0 ? (
                  <span style={{ fontFamily: "JetBrains Mono, monospace", fontSize: 8, color: "#C9C8CE" }}>{i + 1}</span>
                ) : null}
              </div>
            );
          })}
        </div>
        <div style={{ display: "flex", gap: 20, marginTop: 16, borderTop: "1px solid #F2F1F3", paddingTop: 14 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 7 }}>
            <div style={{ width: 12, height: 12, borderRadius: 2, background: "#0E0D11" }} />
            <span style={{ fontFamily: "Inter", fontSize: 12, color: "#4A4852" }}>Захиалга</span>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 7 }}>
            <div style={{ width: 12, height: 12, borderRadius: 2, background: "#FFEC42" }} />
            <span style={{ fontFamily: "Inter", fontSize: 12, color: "#4A4852" }}>Хамгийн их өдөр</span>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 7 }}>
            <div style={{ width: 12, height: 12, borderRadius: 2, background: "#F2F1F3" }} />
            <span style={{ fontFamily: "Inter", fontSize: 12, color: "#4A4852" }}>Захиалгагүй</span>
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── CouponsPanel ─────────────────────────────────────────────
function CouponsPanel() {
  const isMobile = useIsMobile();
  const [coupons, setCoupons] = React.useState(() => lsGet(COUPONS_KEY, INITIAL_COUPONS));
  const [code, setCode] = React.useState(rndCode());
  const [discount, setDiscount] = React.useState(10);
  const [expires, setExpires] = React.useState("2026-06-30");
  const [maxUses, setMaxUses] = React.useState(50);
  const [copied, setCopied] = React.useState(null);

  React.useEffect(() => { lsSave(COUPONS_KEY, coupons); }, [coupons]);

  const add = () => {
    if (!code.trim()) return;
    const existing = coupons.find(c => c.code === code.trim().toUpperCase());
    if (existing) { alert("Энэ код аль хэдийн байна."); return; }
    setCoupons([{ id: Date.now(), code: code.trim().toUpperCase(), discount: Number(discount), expires, uses: 0, maxUses: Number(maxUses), active: true }, ...coupons]);
    setCode(rndCode());
  };

  const toggle = id => setCoupons(coupons.map(c => c.id === id ? {...c, active: !c.active} : c));
  const del = id => setCoupons(coupons.filter(c => c.id !== id));

  const copy = c => {
    navigator.clipboard.writeText(c).catch(() => {});
    setCopied(c); setTimeout(() => setCopied(null), 2000);
  };

  const inputDark = { ...S.input, background: "rgba(255,255,255,0.07)", border: "1px solid rgba(255,255,255,0.12)", color: "#fff" };
  const labelDark = { ...S.label, color: "rgba(255,255,255,0.45)" };

  return (
    <div style={{ ...S.wrap, padding: isMobile ? "20px 16px" : "36px 32px" }}>
      <div style={{ ...S.panelHead, marginBottom: isMobile ? 20 : 28 }}>
        <div>
          <div style={S.meta}>/ КУПОН КОД /</div>
          <h2 style={{ ...S.h2, fontSize: isMobile ? 24 : 34 }}>Хямдралын кодууд</h2>
        </div>
      </div>

      {/* Generator */}
      <div style={{ background: "#1F1D23", borderRadius: 16, padding: isMobile ? "20px 16px" : "28px 28px", marginBottom: 20 }}>
        <div style={{ ...S.meta, color: "rgba(255,255,255,0.4)", marginBottom: 16 }}>Шинэ купон үүсгэх</div>

        {/* Code row — always full width */}
        <div style={{ marginBottom: 12 }}>
          <label style={labelDark}>Код</label>
          <div style={{ display: "flex", gap: 8 }}>
            <input
              style={{ ...inputDark, fontFamily: "JetBrains Mono, monospace", letterSpacing: "0.08em" }}
              value={code} onChange={e => setCode(e.target.value.toUpperCase())}
            />
            <button title="Санамсаргүй код" style={{ flexShrink: 0, background: "rgba(255,255,255,0.1)", border: "none", borderRadius: 10, padding: "0 16px", color: "#fff", cursor: "pointer", fontSize: 20 }} onClick={() => setCode(rndCode())}>↻</button>
          </div>
        </div>

        {/* 2-column grid for small fields */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginBottom: 12 }}>
          <div>
            <label style={labelDark}>Хямдрал %</label>
            <input style={inputDark} type="number" min="1" max="100" value={discount} onChange={e => setDiscount(e.target.value)} />
          </div>
          <div>
            <label style={labelDark}>Max ашиглалт</label>
            <input style={inputDark} type="number" min="1" value={maxUses} onChange={e => setMaxUses(e.target.value)} />
          </div>
        </div>

        {/* Date — full width */}
        <div style={{ marginBottom: 16 }}>
          <label style={labelDark}>Дуусах огноо</label>
          <input style={{ ...inputDark, colorScheme: "dark" }} type="date" value={expires} onChange={e => setExpires(e.target.value)} />
        </div>

        <button style={{ width: "100%", background: "#FFEC42", color: "#0E0D11", border: "none", borderRadius: 12, padding: "14px", fontFamily: "Inter, sans-serif", fontWeight: 700, fontSize: 15, cursor: "pointer" }} onClick={add}>
          + Купон нэмэх
        </button>
      </div>

      {/* Coupons list */}
      {isMobile ? (
        /* Mobile: card list */
        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          {coupons.map(c => (
            <div key={c.id} style={{ background: "#fff", border: "1px solid #E8E7E9", borderRadius: 16, padding: "16px", opacity: c.active ? 1 : 0.5 }}>
              {/* Code + copy */}
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12 }}>
                <span style={{ fontFamily: "JetBrains Mono, monospace", fontSize: 17, fontWeight: 700, letterSpacing: "0.06em", color: "#0E0D11" }}>{c.code}</span>
                <button onClick={() => copy(c.code)} style={{ background: copied === c.code ? "#16A34A1A" : "#FAFAFB", border: `1px solid ${copied === c.code ? "#16A34A44" : "#E8E7E9"}`, borderRadius: 8, padding: "6px 14px", fontSize: 13, cursor: "pointer", color: copied === c.code ? "#16A34A" : "#4A4852", fontFamily: "Inter", fontWeight: 500, transition: "all 0.2s" }}>
                  {copied === c.code ? "✓ Хуулсан" : "Хуулах"}
                </button>
              </div>

              {/* Info row */}
              <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginBottom: 12 }}>
                <span style={S.salePill}>-{c.discount}%</span>
                <span style={{ background: c.active ? "#16A34A1A" : "#98979E1A", color: c.active ? "#16A34A" : "#98979E", fontFamily: "JetBrains Mono, monospace", fontSize: 10, letterSpacing: "0.1em", padding: "4px 10px", borderRadius: 999 }}>
                  {c.active ? "ИДЭВХТЭЙ" : "ИДЭВХГҮЙ"}
                </span>
                <span style={{ fontFamily: "JetBrains Mono, monospace", fontSize: 11, color: "#8A8990", padding: "4px 0" }}>{c.expires} дуусна</span>
              </div>

              {/* Usage bar */}
              <div style={{ marginBottom: 14 }}>
                <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 5 }}>
                  <span style={{ fontFamily: "Inter", fontSize: 12, color: "#8A8990" }}>Ашигласан</span>
                  <span style={{ fontFamily: "JetBrains Mono, monospace", fontSize: 12, color: "#0E0D11", fontWeight: 600 }}>{c.uses} / {c.maxUses}</span>
                </div>
                <div style={{ width: "100%", height: 6, background: "#F2F1F3", borderRadius: 999 }}>
                  <div style={{ width: `${Math.min(100, (c.uses / c.maxUses) * 100)}%`, height: "100%", background: c.uses >= c.maxUses ? "#FF6A30" : "#0E0D11", borderRadius: 999 }} />
                </div>
              </div>

              {/* Actions */}
              <div style={{ display: "flex", gap: 8 }}>
                <button style={{ ...S.btnSm, flex: 1, textAlign: "center", padding: "9px 0" }} onClick={() => toggle(c.id)}>{c.active ? "Зогсоох" : "Идэвхжүүлэх"}</button>
                <button style={{ ...S.btnSm, flex: 1, textAlign: "center", padding: "9px 0", color: "#FF3B6F", borderColor: "#FF3B6F33" }} onClick={() => del(c.id)}>Устгах</button>
              </div>
            </div>
          ))}
        </div>
      ) : (
        /* Desktop: table */
        <div style={S.tableBox}>
          <table style={S.table}>
            <thead>
              <tr>
                {["Код", "Хямдрал", "Дуусах огноо", "Ашигласан", "Статус", ""].map(h => <th key={h} style={S.th}>{h}</th>)}
              </tr>
            </thead>
            <tbody>
              {coupons.map(c => (
                <tr key={c.id} style={{ opacity: c.active ? 1 : 0.45 }}>
                  <td style={S.td}>
                    <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                      <span style={{ fontFamily: "JetBrains Mono, monospace", fontSize: 15, fontWeight: 700, letterSpacing: "0.06em" }}>{c.code}</span>
                      <button onClick={() => copy(c.code)} style={{ background: "transparent", border: "1px solid #E8E7E9", borderRadius: 6, padding: "3px 9px", fontSize: 11, cursor: "pointer", color: copied === c.code ? "#16A34A" : "#8A8990", transition: "all 0.2s" }}>
                        {copied === c.code ? "✓ Хуулсан" : "Хуулах"}
                      </button>
                    </div>
                  </td>
                  <td style={S.td}><span style={S.salePill}>-{c.discount}%</span></td>
                  <td style={S.td}><span style={{ fontFamily: "JetBrains Mono, monospace", fontSize: 12 }}>{c.expires}</span></td>
                  <td style={S.td}>
                    <div style={{ fontFamily: "JetBrains Mono, monospace", fontSize: 12 }}>{c.uses} / {c.maxUses}</div>
                    <div style={{ width: "80px", height: 4, background: "#F2F1F3", borderRadius: 999, marginTop: 4 }}>
                      <div style={{ width: `${Math.min(100, (c.uses / c.maxUses) * 100)}%`, height: "100%", background: c.uses >= c.maxUses ? "#FF6A30" : "#0E0D11", borderRadius: 999 }} />
                    </div>
                  </td>
                  <td style={S.td}>
                    <span style={{ background: c.active ? "#16A34A1A" : "#98979E1A", color: c.active ? "#16A34A" : "#98979E", fontFamily: "JetBrains Mono, monospace", fontSize: 10, letterSpacing: "0.1em", padding: "4px 10px", borderRadius: 999 }}>
                      {c.active ? "ИДЭВХТЭЙ" : "ИДЭВХГҮЙ"}
                    </span>
                  </td>
                  <td style={S.td}>
                    <button style={S.btnSm} onClick={() => toggle(c.id)}>{c.active ? "Зогсоох" : "Идэвхжүүлэх"}</button>
                    <button style={{...S.btnSm, marginLeft: 8, color: "#FF3B6F", borderColor: "#FF3B6F33"}} onClick={() => del(c.id)}>Устгах</button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      <div style={{ marginTop: 16, padding: "14px 18px", background: "#FFEC4215", border: "1px solid #FFEC4240", borderRadius: 12, fontFamily: "Inter", fontSize: 13, color: "#4A4852" }}>
        💡 Купон кодыг shop-ийн cart дотор оруулбал автоматаар хямдрал тооцно.
      </div>
    </div>
  );
}

// ─── CategoriesPanel ──────────────────────────────────────────
function CategoriesPanel({ cats, setCats, tags, setTags }) {
  const isMobile = useIsMobile();
  const [newCat, setNewCat] = React.useState("");
  const [newTag, setNewTag] = React.useState("");

  const addCat = () => {
    const v = newCat.trim();
    if (!v || cats.includes(v)) return;
    setCats([...cats, v]); setNewCat("");
  };

  const delCat = c => {
    if (c === "All") return;
    setCats(cats.filter(x => x !== c));
  };

  const addTag = () => {
    const v = newTag.trim().toUpperCase();
    if (!v || tags.includes(v)) return;
    setTags([...tags, v]); setNewTag("");
  };

  const delTag = t => setTags(tags.filter(x => x !== t));

  const Card = ({ title, children }) => (
    <div style={{ background: "#fff", border: "1px solid #E8E7E9", borderRadius: 16, padding: 24 }}>
      <div style={{...S.meta, marginBottom: 18}}>{title}</div>
      {children}
    </div>
  );

  return (
    <div style={{ ...S.wrap, padding: isMobile ? "20px 16px" : "36px 32px" }}>
      <div style={{ ...S.panelHead, marginBottom: isMobile ? 20 : 28 }}>
        <div>
          <div style={S.meta}>/ АНГИЛАЛ · BADGE /</div>
          <h2 style={{ ...S.h2, fontSize: isMobile ? 24 : 34 }}>Ангилал & Badge</h2>
        </div>
      </div>

      <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>

        {/* Ангилал карт */}
        <div style={{ background: "#fff", border: "1px solid #E8E7E9", borderRadius: 16, padding: isMobile ? "18px 16px" : 24 }}>
          <div style={{ ...S.meta, marginBottom: 14 }}>/ АНГИЛАЛ /</div>
          <div style={{ display: "flex", gap: 8, marginBottom: 16 }}>
            <input
              style={{ ...S.input, flex: 1, fontSize: isMobile ? 16 : 14 }}
              value={newCat}
              onChange={e => setNewCat(e.target.value)}
              placeholder="Шинэ ангилал нэмэх..."
              onKeyDown={e => e.key === "Enter" && addCat()}
            />
            <button style={{ ...S.btnDark, padding: "0 20px", fontSize: 20, borderRadius: 12 }} onClick={addCat}>+</button>
          </div>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
            {cats.map(c => (
              <div key={c} style={{ display: "flex", alignItems: "center", gap: 0, background: "#FAFAFB", border: "1px solid #E8E7E9", borderRadius: 999, overflow: "hidden" }}>
                <span style={{ fontFamily: "Inter", fontSize: 14, padding: "8px 14px 8px 16px" }}>{c}</span>
                {c !== "All" && (
                  <button onClick={() => delCat(c)} style={{ background: "#FF3B6F11", border: "none", borderLeft: "1px solid #E8E7E9", cursor: "pointer", color: "#FF3B6F", fontSize: 15, padding: "8px 12px", lineHeight: 1, display: "flex", alignItems: "center" }}>×</button>
                )}
              </div>
            ))}
          </div>
          <div style={{ marginTop: 12, fontFamily: "Inter", fontSize: 12, color: "#C9C8CE" }}>
            "All" ангилалыг устгах боломжгүй.
          </div>
        </div>

        {/* Badge / Tag карт */}
        <div style={{ background: "#fff", border: "1px solid #E8E7E9", borderRadius: 16, padding: isMobile ? "18px 16px" : 24 }}>
          <div style={{ ...S.meta, marginBottom: 14 }}>/ BADGE · TAG /</div>
          <div style={{ display: "flex", gap: 8, marginBottom: 16 }}>
            <input
              style={{ ...S.input, flex: 1, fontSize: isMobile ? 16 : 14 }}
              value={newTag}
              onChange={e => setNewTag(e.target.value)}
              placeholder="BEST SELLER..."
              onKeyDown={e => e.key === "Enter" && addTag()}
            />
            <button style={{ ...S.btnDark, padding: "0 20px", fontSize: 20, borderRadius: 12 }} onClick={addTag}>+</button>
          </div>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
            {tags.map(t => (
              <div key={t} style={{ display: "flex", alignItems: "center", gap: 0, background: "#FFEC4218", border: "1px solid #FFEC4255", borderRadius: 999, overflow: "hidden" }}>
                <span style={{ fontFamily: "JetBrains Mono, monospace", fontSize: 12, letterSpacing: "0.08em", color: "#0E0D11", padding: "8px 14px 8px 16px" }}>{t}</span>
                <button onClick={() => delTag(t)} style={{ background: "#FF3B6F11", border: "none", borderLeft: "1px solid #FFEC4255", cursor: "pointer", color: "#FF3B6F", fontSize: 15, padding: "8px 12px", lineHeight: 1, display: "flex", alignItems: "center" }}>×</button>
              </div>
            ))}
          </div>
          <div style={{ marginTop: 14, padding: "12px 14px", background: "#FAFAFB", borderRadius: 10, fontFamily: "Inter", fontSize: 13, color: "#4A4852", lineHeight: 1.5 }}>
            Badge-ийг "Бараа засах" модалд сонгоно. Жишээ: BEST SELLER, TOP RATED...
          </div>
        </div>

      </div>
    </div>
  );
}

// ─── Sidebar ──────────────────────────────────────────────────
const NAV = [
  { id: "products",   icon: "▤", label: "Бараа" },
  { id: "orders",     icon: "≡", label: "Захиалга" },
  { id: "stats",      icon: "▦", label: "Статистик" },
  { id: "coupons",    icon: "✦", label: "Купон код" },
  { id: "categories", icon: "◈", label: "Ангилал" },
];

function Sidebar({ active, onNav, onLogout }) {
  return (
    <div style={S.sidebar}>
      <div style={S.logo}>
        <div style={S.logoMark}>N9NE</div>
        <div style={S.logoSub}>Admin Dashboard</div>
      </div>
      <nav style={{ padding: "12px 0", flex: 1 }}>
        {NAV.map(n => (
          <button key={n.id} style={S.navItem(active === n.id)} onClick={() => onNav(n.id)}>
            <span style={{ fontSize: 16, lineHeight: 1 }}>{n.icon}</span>
            {n.label}
          </button>
        ))}
      </nav>
      <div style={{ padding: "16px 24px", borderTop: "1px solid rgba(255,255,255,0.07)", display: "flex", flexDirection: "column", gap: 10 }}>
        <a href="index.html" style={{ fontFamily: "Inter", fontSize: 13, color: "rgba(255,255,255,0.35)", textDecoration: "none" }}>
          ← nine.ub9.com
        </a>
        {onLogout && (
          <button onClick={onLogout} style={{ background: "transparent", border: "1px solid rgba(255,255,255,0.12)", borderRadius: 8, padding: "7px 12px", fontFamily: "Inter", fontSize: 12, color: "rgba(255,255,255,0.35)", cursor: "pointer", textAlign: "left" }}>
            Гарах
          </button>
        )}
      </div>
    </div>
  );
}

// ─── AdminApp ─────────────────────────────────────────────────
function AdminApp() {
  const [authed, setAuthed] = React.useState(() => sessionStorage.getItem("n9_admin_auth") === "1");
  const [panel, setPanel]   = React.useState("products");
  const [cats, setCats]     = React.useState(() => lsGet(CATS_KEY, DEFAULT_CATS));
  const [tags, setTags]     = React.useState(() => lsGet(TAGS_KEY, DEFAULT_TAGS));
  const [menuOpen, setMenuOpen] = React.useState(false);
  const isMobile = useIsMobile();

  const initialized = React.useRef(false);

  React.useEffect(() => {
    fetch("/api/get-categories")
      .then(r => r.json())
      .then(data => {
        if (data && data.length) { setCats(data); lsSave(CATS_KEY, data); }
        initialized.current = true;
      })
      .catch(() => { initialized.current = true; });
  }, []);

  React.useEffect(() => {
    lsSave(CATS_KEY, cats);
    if (!initialized.current) return;
    fetch("/api/save-categories", {
      method: "POST",
      headers: { "Content-Type": "application/json", "x-admin-key": "admin0829" },
      body: JSON.stringify(cats),
    }).catch(() => {});
  }, [cats]);

  React.useEffect(() => { lsSave(TAGS_KEY, tags); }, [tags]);

  if (!authed) return <LoginScreen onLogin={() => setAuthed(true)} />;

  const logout = () => { sessionStorage.removeItem("n9_admin_auth"); setAuthed(false); };

  const panels = (
    <>
      {panel === "products"   && <ProductsPanel cats={cats} tags={tags} />}
      {panel === "orders"     && <OrdersPanel />}
      {panel === "stats"      && <StatsPanel />}
      {panel === "coupons"    && <CouponsPanel />}
      {panel === "categories" && <CategoriesPanel cats={cats} setCats={setCats} tags={tags} setTags={setTags} />}
    </>
  );

  if (isMobile) {
    const activeNav = NAV.find(n => n.id === panel);
    return (
      <div style={{ display: "flex", flexDirection: "column", minHeight: "100vh", background: "#FAFAFB" }}>

        {/* Mobile top bar */}
        <div style={{ background: "#1F1D23", padding: "14px 18px", display: "flex", justifyContent: "space-between", alignItems: "center", flexShrink: 0, position: "sticky", top: 0, zIndex: 100 }}>
          <div>
            <div style={{ fontFamily: "Inter, sans-serif", fontWeight: 900, fontSize: 18, letterSpacing: "-0.03em", color: "#fff", lineHeight: 1 }}>N9NE</div>
            <div style={{ fontFamily: "JetBrains Mono, monospace", fontSize: 9, letterSpacing: "0.15em", color: "rgba(255,255,255,0.35)", textTransform: "uppercase", marginTop: 3 }}>
              {activeNav ? activeNav.label : "Admin"}
            </div>
          </div>
          <button onClick={() => setMenuOpen(true)} style={{ background: "rgba(255,255,255,0.08)", border: "none", borderRadius: 10, width: 40, height: 40, color: "#fff", cursor: "pointer", fontSize: 18, display: "flex", alignItems: "center", justifyContent: "center" }}>
            ☰
          </button>
        </div>

        {/* Drawer overlay */}
        {menuOpen && (
          <div style={{ position: "fixed", inset: 0, zIndex: 300, background: "rgba(14,13,17,0.65)" }} onClick={() => setMenuOpen(false)}>
            <div style={{ position: "absolute", top: 0, left: 0, width: 270, height: "100%", background: "#1F1D23", display: "flex", flexDirection: "column" }} onClick={e => e.stopPropagation()}>
              <div style={{ padding: "24px 20px 18px", borderBottom: "1px solid rgba(255,255,255,0.08)" }}>
                <div style={{ fontFamily: "Inter, sans-serif", fontWeight: 900, fontSize: 20, color: "#fff" }}>N9NE</div>
                <div style={{ fontFamily: "JetBrains Mono, monospace", fontSize: 9, letterSpacing: "0.15em", color: "rgba(255,255,255,0.35)", textTransform: "uppercase", marginTop: 4 }}>Admin Dashboard</div>
              </div>
              <nav style={{ padding: "12px 0", flex: 1 }}>
                {NAV.map(n => (
                  <button key={n.id} style={S.navItem(panel === n.id)} onClick={() => { setPanel(n.id); setMenuOpen(false); }}>
                    <span style={{ fontSize: 16, lineHeight: 1 }}>{n.icon}</span>
                    {n.label}
                  </button>
                ))}
              </nav>
              <div style={{ padding: "16px 20px", borderTop: "1px solid rgba(255,255,255,0.07)" }}>
                <a href="index.html" style={{ fontFamily: "Inter", fontSize: 13, color: "rgba(255,255,255,0.35)", textDecoration: "none", display: "block", marginBottom: 12 }}>← nine.ub9.com</a>
                <button onClick={logout} style={{ background: "transparent", border: "1px solid rgba(255,255,255,0.12)", borderRadius: 8, padding: "9px 14px", fontFamily: "Inter", fontSize: 13, color: "rgba(255,255,255,0.35)", cursor: "pointer", width: "100%", textAlign: "left" }}>Гарах</button>
              </div>
            </div>
          </div>
        )}

        {/* Content */}
        <main style={{ flex: 1, overflowY: "auto", paddingBottom: 72 }}>
          {panels}
        </main>

        {/* Bottom tab bar */}
        <div style={{ background: "#1F1D23", display: "flex", borderTop: "1px solid rgba(255,255,255,0.08)", position: "fixed", bottom: 0, left: 0, right: 0, zIndex: 100 }}>
          {NAV.map(n => (
            <button key={n.id} onClick={() => setPanel(n.id)} style={{
              flex: 1, background: "transparent", border: "none",
              padding: "8px 4px 10px",
              display: "flex", flexDirection: "column", alignItems: "center", gap: 3, cursor: "pointer",
              borderTop: panel === n.id ? "2px solid #FFEC42" : "2px solid transparent",
            }}>
              <span style={{ fontSize: 17, lineHeight: 1 }}>{n.icon}</span>
              <span style={{ fontFamily: "Inter, sans-serif", fontSize: 9, letterSpacing: "0.06em", textTransform: "uppercase", color: panel === n.id ? "#FFEC42" : "rgba(255,255,255,0.35)", fontWeight: panel === n.id ? 700 : 400 }}>{n.label}</span>
            </button>
          ))}
        </div>
      </div>
    );
  }

  return (
    <div style={{ display: "flex", minHeight: "100vh" }}>
      <Sidebar active={panel} onNav={setPanel} onLogout={logout} />
      <main style={S.main}>
        {panels}
      </main>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("app")).render(<AdminApp />);
