import React, { useMemo, useState, useEffect } from "react";
import Modal from "../components/common/Modal";
import { Btn, Field, Pill, Select, TextInput } from "../components/common/UI";
import { DEFAULT_MATERIALS, UI } from "../constants/pvc";
import { uid, money } from "../utils/helpers";
import { createMaterial, updateMaterial, deleteMaterial } from "../utils/materialsDb";

/**
 * ✅ Updates per kërkesën tënde:
 * - Hequr “localStorage” pill nga header
 * - Hequr rreshti “P:1 • A:1 • X:3 • AK:0” nga Materialet
 * - Butoni "Shto" bëhet dinamik: “Shto Profile”, “Shto Armaturë”, “Shto Xham”, “Shto Aksesorë”
 * - Funksionet dhe logjika NUK preken (setMaterials / onBack / CRUD)
 */

export default function MaterialsManager({ materials, setMaterials, onBack, logoSrc, userLabel = "User" }) {
  const [tab, setTab] = useState("profiles"); // profiles | irons | glass | accessories
  const [q, setQ] = useState("");
  const [sort, setSort] = useState("name_asc"); // name_asc | name_desc | price_desc | price_asc

  const [editOpen, setEditOpen] = useState(false);
  const [mode, setMode] = useState("create"); // create | edit
  const [targetId, setTargetId] = useState(null);

  const [name, setName] = useState("");
  const [pricePerM, setPricePerM] = useState(0);
  const [pricePerM2, setPricePerM2] = useState(0);
  const [accUnit, setAccUnit] = useState("pcs");
  const [accPrice, setAccPrice] = useState(0);

  // Door panels (PNG) - EXTRA
const [panelPrice, setPanelPrice] = useState(0);
const [panelFile, setPanelFile] = useState(null); // File
const [panelPreview, setPanelPreview] = useState(""); // local blob url (optional)


const API_BASE = (import.meta.env.VITE_API_URL || "http://localhost:8000").replace(/\/$/, "");

const resolveImg = (raw) => {
  if (!raw || typeof raw !== "string") return "";

  // already absolute
  if (raw.startsWith("http://") || raw.startsWith("https://")) return raw;

  // normalize slashes
  const cleaned = raw.replace(/^\/+/, ""); // remove leading /

  // if DB stores "door-panels/xxx.png" -> public url is "/storage/door-panels/xxx.png"
  const publicPath = cleaned.startsWith("storage/")
    ? `/${cleaned}`
    : cleaned.startsWith("door-panels/")
    ? `/storage/${cleaned}`
    : `/${cleaned}`; // fallback

  return `${API_BASE}${publicPath}`;
};

const getPanelImgRaw = (x) =>
  x?.imageUrl || x?.image_url || x?.image || x?.url || x?.path || x?.photo || "";


useEffect(() => {
  if (!panelFile) {
    setPanelPreview("");
    return;
  }
  const url = URL.createObjectURL(panelFile);
  setPanelPreview(url);
  return () => URL.revokeObjectURL(url);
}, [panelFile]);


  const counts = useMemo(() => {
  return {
    prof: materials.profiles.length,
    iron: materials.irons.length,
    glass: materials.glassTypes.length,
    acc: materials.accessories.length,
    panels: (materials.doorPanels || []).length,
  };
}, [materials]);


const rawList = useMemo(() => {
  return tab === "profiles"
    ? materials.profiles
    : tab === "irons"
    ? materials.irons
    : tab === "glass"
    ? materials.glassTypes
    : tab === "accessories"
    ? materials.accessories
    : (materials.doorPanels || []);
}, [tab, materials]);


  const list = useMemo(() => {
    const s = q.trim().toLowerCase();
    let arr = !s ? rawList : rawList.filter((x) => (x.name || "").toLowerCase().includes(s));

    const getPrice = (x) =>
  tab === "glass"
    ? Number(x.pricePerM2 || 0)
    : tab === "accessories"
    ? Number(x.price || 0)
    : tab === "doorPanels"
    ? Number(x.price || 0)
    : Number(x.pricePerM || 0);


    const getName = (x) => (x.name || "").toLowerCase();

    arr = [...arr].sort((a, b) => {
      if (sort === "name_asc") return getName(a).localeCompare(getName(b));
      if (sort === "name_desc") return getName(b).localeCompare(getName(a));
      if (sort === "price_asc") return getPrice(a) - getPrice(b);
      if (sort === "price_desc") return getPrice(b) - getPrice(a);
      return 0;
    });

    return arr;
  }, [rawList, q, sort, tab]);

  const tabLabel =
  tab === "profiles"
    ? "Profile"
    : tab === "irons"
    ? "Armaturë"
    : tab === "glass"
    ? "Xham"
    : tab === "accessories"
    ? "Aksesorë"
    : "Panele Dyer";


  const addLabel =
  tab === "profiles"
    ? "Shto Profile"
    : tab === "irons"
    ? "Shto Armaturë"
    : tab === "glass"
    ? "Shto Xham"
    : tab === "accessories"
    ? "Shto Aksesorë"
    : "Shto Panel";


const tabUnitLabel = tab === "glass" ? "€/m²" : tab === "accessories" ? "Çmimi" : tab === "doorPanels" ? "Extra (€)" : "€/m";

  const openCreate = () => {
    setMode("create");
    setTargetId(null);
    setName("");
    setPricePerM(0);
    setPricePerM2(0);
    setAccUnit("pcs");
    setAccPrice(0);

    // door panel fields
setPanelPrice(0);
setPanelFile(null);
setPanelPreview("");
    setEditOpen(true);
  };

const openEdit = (item) => {
  setMode("edit");
  setTargetId(item.id);
  setName(item.name || "");

  if (tab === "glass") setPricePerM2(Number(item.pricePerM2 || 0));
  else if (tab === "accessories") {
    setAccUnit(item.unit || "pcs");
    setAccPrice(Number(item.price || 0));
  } else if (tab === "doorPanels") {
    setPanelPrice(Number(item.price || 0));
    setPanelFile(null);
    setPanelPreview("");
  } else {
    setPricePerM(Number(item.pricePerM || 0));
  }

  setEditOpen(true); // ✅ IMPORTANT
};


  const removeItem = async (id) => {
  if (!window.confirm("Ta fshij këtë item?")) return;

  try {
    const kind = tab === "glass" ? "glassTypes" : tab === "doorPanels" ? "doorPanels" : tab;
 // tab uses "glass", db expects "glassTypes"
    const next = await deleteMaterial(kind, id);
    setMaterials(next);
  } catch (e) {
    console.error(e);
    alert(e?.response?.data?.message || e?.message || "Delete failed");
  }
};


  const saveItem = async () => {
  if (!name.trim()) return;

const kind = tab === "glass" ? "glassTypes" : tab === "doorPanels" ? "doorPanels" : tab;

  const uiItem =
  tab === "glass"
    ? { name: name.trim(), pricePerM2: Number(pricePerM2) || 0 }
    : tab === "accessories"
    ? { name: name.trim(), unit: accUnit, price: Number(accPrice) || 0 }
    : tab === "doorPanels"
    ? { name: name.trim(), price: Number(panelPrice) || 0, file: panelFile } // IMPORTANT: file used by materialsDb -> FormData
    : { name: name.trim(), pricePerM: Number(pricePerM) || 0 };


  try {
    const next =
      mode === "edit"
        ? await updateMaterial(kind, targetId, uiItem)
        : await createMaterial(kind, uiItem);

    setMaterials(next);
    setEditOpen(false);
  } catch (e) {
    console.error(e);
    alert(e?.response?.data?.message || e?.message || "Save failed");
  }
};


  return (
    <div className="mmRoot">
      <style>{styles(UI)}</style>

      {/* Navbar */}
      <header className="mmNav">
        <div className="mmNavInner">
          <div className="mmNavLeft">
            <div className="mmLogoWrap" title="Logo">
              {logoSrc ? <img src={logoSrc} alt="Logo" className="mmLogoImg" /> : <div className="mmLogoFallback">PVC</div>}
            </div>

            <nav className="mmLinks" aria-label="Navigation">
              <button className="mmLink" type="button" onClick={onBack} title="Kthehu te Dashboard">
                <span className="mmLinkIcon">
                  <IconArrowLeft />
                </span>
                Dashboard
              </button>

              <button className="mmLink mmActive" type="button">
                <span className="mmLinkIcon">
                  <IconSliders />
                </span>
                Materialet
              </button>
            </nav>
          </div>

          <div className="mmNavRight">
            <button className="mmUserBtn" type="button" title={userLabel} aria-label="User">
              <span className="mmUserIcon">
                <IconUser />
              </span>
            </button>
          </div>
        </div>
      </header>

      {/* Main */}
      <main className="mmMain">
        <div className="mmFull">
          {/* Header row */}
          <section className="mmHeader">
            <div className="mmHeaderLeft">
              <div className="mmTitle">Materialet & Çmimet</div>
              <div className="mmSub">Menaxho profile, armaturë, xham dhe aksesorë (UI gati për backend)</div>
            </div>
            <div className="mmHeaderRight">
              <Btn variant="primary" onClick={openCreate} style={{ borderRadius: 12, padding: "10px 14px" }}>
                <span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>
                  <IconPlus /> {addLabel}
                </span>
              </Btn>
            </div>
          </section>

          {/* Tabs */}
          <section className="mmTabs">
            <TabChip active={tab === "profiles"} onClick={() => setTab("profiles")} label={`Profile (${counts.prof})`} icon={<IconLayers />} />
            <TabChip active={tab === "irons"} onClick={() => setTab("irons")} label={`Armaturë (${counts.iron})`} icon={<IconBolt />} />
            <TabChip active={tab === "glass"} onClick={() => setTab("glass")} label={`Xham (${counts.glass})`} icon={<IconSquare />} />
            <TabChip active={tab === "accessories"} onClick={() => setTab("accessories")} label={`Aksesorë (${counts.acc})`} icon={<IconTool />} />
          <TabChip active={tab === "doorPanels"} onClick={() => setTab("doorPanels")} label={`Panele Dyer (${counts.panels})`} icon={<IconImage />} />

          </section>

          {/* Controls */}
          <section className="mmControls">
            <div className="mmControlsLeft">
              <div className="mmSearch">
                <span className="mmSearchIcon">
                  <IconSearch />
                </span>
                <TextInput
                  value={q}
                  onChange={(e) => setQ(e.target.value)}
                  placeholder={`Kërko në ${tabLabel.toLowerCase()}…`}
                  style={{ border: "none", background: "transparent", height: 40, padding: "0 8px" }}
                />
              </div>

              <div className="mmSort">
                <span className="mmSortLabel">Renditja</span>
                <Select value={sort} onChange={(e) => setSort(e.target.value)} style={{ height: 40 }}>
                  <option value="name_asc">Emri (A–Z)</option>
                  <option value="name_desc">Emri (Z–A)</option>
                  <option value="price_desc">Çmimi (më i lartë)</option>
                  <option value="price_asc">Çmimi (më i lirë)</option>
                </Select>
              </div>
            </div>

            <div className="mmControlsRight">
              <Pill tone="blue">{tabLabel}</Pill>
              <Pill tone="soft">{list.length} item(e)</Pill>
            </div>
          </section>

          {/* List */}
          <section className="mmList">
            <div className="mmListHead">
              <div className="mmListTitle">{tabLabel}</div>
              <div className="mmListMeta" style={{ color: UI.muted, fontSize: 12 }}>
                {tab === "glass" ? "Çmimi është €/m²" : tab === "accessories" ? "Çmimi varet nga njësia" : "Çmimi është €/m"}
              </div>
            </div>

            {list.length === 0 ? (
              <div className="mmEmpty">
                <div className="mmEmptyIcon">
                  <IconSearchBig />
                </div>
                <div className="mmEmptyTitle">Bosh</div>
                <div className="mmEmptySub">{addLabel} për të filluar.</div>
              </div>
            ) : (
              <>
                {/* Desktop table */}
                <div className="mmTableWrap">
                  <table className="mmTable">
                    <thead>
                      <tr>
                        <th>Emri</th>
                          {tab === "doorPanels" ? <th>Foto</th> : null}
                        <th>{tabUnitLabel}</th>
                        {tab === "accessories" ? <th>Njësia</th> : null}
                        <th className="mmThRight">Veprime</th>
                      </tr>
                    </thead>
                    <tbody>
                      {list.map((x) => (
                        <tr key={x.id} className="mmRow">
                          <td className="mmName">{x.name}</td>
{tab === "doorPanels" ? (
  <td>
    {(() => {
      const raw = getPanelImgRaw(x);
      const src = resolveImg(raw);
      return src ? (
        <img
          src={src}
          alt={x.name}
          style={{ width: 70, height: 44, objectFit: "contain", display: "block", background: "transparent" }}
          onError={(e) => {
            console.log("PANEL IMG ERROR", { raw, src, x });
            e.currentTarget.style.display = "none";
          }}
        />
      ) : (
        <span style={{ fontSize: 12, opacity: 0.6 }}>—</span>
      );
    })()}
  </td>
) : null}


                          <td className="mmPrice">
                            {tab === "glass"
  ? money(x.pricePerM2)
  : tab === "accessories"
  ? money(x.price)
  : tab === "doorPanels"
  ? money(x.price)
  : money(x.pricePerM)}
                          </td>

                          {tab === "accessories" ? <td className="mmUnit">{x.unit}</td> : null}

                          <td className="mmTdRight">
                            <div className="mmActions">
                              <Btn variant="soft" onClick={() => openEdit(x)} style={{ borderRadius: 10, padding: "9px 12px" }}>
                                <span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>
                                  <IconEdit /> Ndrysho
                                </span>
                              </Btn>
                              <Btn variant="danger" onClick={() => removeItem(x.id)} style={{ borderRadius: 10, padding: "9px 12px" }}>
                                <span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>
                                  <IconTrash /> Fshij
                                </span>
                              </Btn>
                            </div>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>

                {/* Mobile cards */}
                <div className="mmCards">
                  {list.map((x) => (
                    <div key={x.id} className="mmCard">
                      <div className="mmCardTop">
                        <div>
                          <div className="mmCardName">{x.name}</div>
                          <div className="mmCardHint">
                            {tabUnitLabel}:{" "}
                            <b>
                              {tab === "glass"
  ? money(x.pricePerM2)
  : tab === "accessories"
  ? money(x.price)
  : tab === "doorPanels"
  ? money(x.price)
  : money(x.pricePerM)}
                            </b>
                            {tab === "accessories" ? ` • Njësia: ${x.unit}` : ""}
                          </div>
                        </div>
                        <div className="mmCardBadge">{tabLabel}</div>
                      </div>

                      <div className="mmCardActions">
                        <Btn variant="soft" onClick={() => openEdit(x)} style={{ borderRadius: 10, padding: "9px 12px" }}>
                          <span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>
                            <IconEdit /> Ndrysho
                          </span>
                        </Btn>
                        <Btn variant="danger" onClick={() => removeItem(x.id)} style={{ borderRadius: 10, padding: "9px 12px" }}>
                          <span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>
                            <IconTrash /> Fshij
                          </span>
                        </Btn>
                      </div>
                    </div>
                  ))}
                </div>
              </>
            )}
          </section>
        </div>

        {/* Modal */}
        <Modal
          open={editOpen}
          title={`${mode === "create" ? "Shto" : "Ndrysho"} ${
  tab === "profiles"
    ? "Profil"
    : tab === "irons"
    ? "Armaturë"
    : tab === "glass"
    ? "Xham"
    : tab === "accessories"
    ? "Aksesor"
    : "Panel Dyer"
}`}
          onClose={() => setEditOpen(false)}
          footer={
            <div style={{ display: "flex", justifyContent: "space-between", gap: 10 }}>
              <Btn onClick={() => setEditOpen(false)} style={{ borderRadius: 12 }}>
                Anulo
              </Btn>
              <Btn variant="primary" onClick={saveItem} disabled={!name.trim()} style={{ borderRadius: 12 }}>
                Ruaj
              </Btn>
            </div>
          }
        >
          <div style={{ display: "grid", gap: 12 }}>
            <Field label="Emri">
              <TextInput value={name} onChange={(e) => setName(e.target.value)} placeholder={`p.sh. ${tab === "glass" ? "Stopsol 4-16-4" : "Profine 88MD"}`} />
            </Field>

            {tab === "glass" ? (
  <Field label="Çmimi (€/m²)">
    <TextInput type="number" value={pricePerM2} onChange={(e) => setPricePerM2(Number(e.target.value) || 0)} />
  </Field>
) : tab === "accessories" ? (
  <>
    <Field label="Njësia">
      <Select value={accUnit} onChange={(e) => setAccUnit(e.target.value)}>
        <option value="pcs">copë</option>
        <option value="m">m</option>
        <option value="m2">m²</option>
      </Select>
    </Field>
    <Field label={`Çmimi (€/ ${accUnit})`}>
      <TextInput type="number" value={accPrice} onChange={(e) => setAccPrice(Number(e.target.value) || 0)} />
    </Field>
  </>
) : tab === "doorPanels" ? (
  <>
    <Field label="Çmimi extra (€)">
      <TextInput type="number" value={panelPrice} onChange={(e) => setPanelPrice(Number(e.target.value) || 0)} />
    </Field>

    <Field label="Foto (PNG)">
      <input
        type="file"
        accept="image/png,image/jpeg,image/webp"
        onChange={(e) => setPanelFile(e.target.files?.[0] || null)}
      />
      <div style={{ fontSize: 12, color: UI.muted, marginTop: 6 }}>
        Kjo foto shfaqet “pure” në editor.
      </div>
    </Field>

    {/* preview: local file OR existing DB image */}
    <div style={{ marginTop: 8 }}>
      {panelPreview ? (
        <img
          src={panelPreview}
          alt="panel preview"
          style={{ width: "100%", maxHeight: 220, objectFit: "contain", display: "block", background: "transparent" }}
        />
      ) : mode === "edit" ? (() => {
  const item = rawList.find((z) => z.id === targetId);
  const raw = getPanelImgRaw(item);
  const src = resolveImg(raw);
  return src ? (
    <img
      src={src}
      alt="panel preview"
      style={{ width: "100%", maxHeight: 220, objectFit: "contain", display: "block", background: "transparent" }}
      onError={() => console.log("MODAL PREVIEW ERROR", { raw, src, item })}
    />
  ) : null;
})() : null}

    </div>
  </>
) : (
  <Field label="Çmimi (€/m)">
    <TextInput type="number" value={pricePerM} onChange={(e) => setPricePerM(Number(e.target.value) || 0)} />
  </Field>
)}


            <div style={{ fontSize: 12, color: UI.muted, lineHeight: 1.45 }}>
  Ruajtja bëhet përmes API (Laravel). Për “Panele Dyer” përdoret upload (multipart).
</div>
          </div>
        </Modal>
      </main>
    </div>
  );
}

/* ---------------- Small UI ---------------- */

function TabChip({ active, onClick, label, icon }) {
  return (
    <button type="button" className={`mmTab ${active ? "mmTabActive" : ""}`} onClick={onClick}>
      <span className="mmTabIcon">{icon}</span>
      <span className="mmTabLabel">{label}</span>
    </button>
  );
}

/* ---------------- Styles ---------------- */

function styles(UI) {
  const primary = UI.primary || "#2563eb";
  const border = UI.border || "rgba(15,23,42,0.10)";
  const text = UI.text || "#0f172a";
  const muted = UI.muted || "rgba(15,23,42,0.60)";

  return `
  .mmRoot{
    min-height: 100vh;
    background: #f6f7fb;
    color: ${text};
    font-family: Inter, ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial;
  }

  .mmNav{
    position: sticky;
    top: 0;
    z-index: 30;
    background: rgba(255,255,255,0.92);
    backdrop-filter: blur(10px);
    border-bottom: 1px solid ${border};
  }
  .mmNavInner{
    width: 100%;
    padding: 12px 18px;
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap: 12px;
  }
  .mmNavLeft{
    display:flex;
    align-items:center;
    gap: 14px;
    min-width:0;
  }

  /* Logo no border */
  .mmLogoWrap{
    width: 44px;
    height: 44px;
    border-radius: 14px;
    overflow: hidden;
    background: transparent;
    border: none;
    box-shadow: none;
    display:grid;
    place-items:center;
    flex: 0 0 auto;
  }
  .mmLogoImg{ width: 44px; height: 44px; object-fit: contain; }
  .mmLogoFallback{
    width: 44px;
    height: 44px;
    border-radius: 14px;
    display:grid;
    place-items:center;
    font-size: 12px;
    letter-spacing: .3px;
    color: ${text};
    background: rgba(37,99,235,0.10);
  }

  .mmLinks{ display:flex; align-items:center; gap: 8px; min-width:0; }
  .mmLink{
    display:flex; align-items:center; gap: 10px;
    padding: 10px 12px;
    border-radius: 14px;
    border: 1px solid transparent;
    background: transparent;
    color: ${text};
    cursor:pointer;
    font-size: 13px;
    font-weight: 500;
    transition: background .12s ease, border-color .12s ease, transform .12s ease;
    text-align:left;
  }
  .mmLink:hover{
    background: rgba(37,99,235,0.07);
    border-color: rgba(37,99,235,0.14);
    transform: translateY(-1px);
  }
  .mmActive{
    background: rgba(37,99,235,0.10);
    border-color: rgba(37,99,235,0.18);
  }
  .mmLinkIcon{
    width: 34px; height: 34px;
    border-radius: 12px;
    display:grid; place-items:center;
    background: rgba(15,23,42,0.04);
    border: 1px solid ${border};
    color: ${primary};
    flex: 0 0 auto;
  }

  .mmNavRight{ display:flex; align-items:center; gap: 10px; }
  .mmUserBtn{
    width: 44px; height: 44px;
    border-radius: 14px;
    border: 1px solid ${border};
    background: #fff;
    box-shadow: 0 8px 18px rgba(15,23,42,0.06);
    cursor:pointer;
    display:grid; place-items:center;
    transition: transform .12s ease, background .12s ease;
  }
  .mmUserBtn:hover{ transform: translateY(-1px); background: rgba(15,23,42,0.02); }
  .mmUserIcon{ color: rgba(15,23,42,0.75); display:grid; place-items:center; }

  .mmMain{ padding: 18px; }
  .mmFull{ width: 100%; display:grid; gap: 14px; }

  .mmHeader{
    display:flex; align-items:flex-end; justify-content:space-between;
    gap: 12px;
  }
  .mmTitle{ font-size: 16px; font-weight: 650; letter-spacing: .1px; }
  .mmSub{ font-size: 12px; color: ${muted}; margin-top: 4px; }

  .mmTabs{ display:flex; gap: 10px; flex-wrap: wrap; }
  .mmTab{
    display:flex; align-items:center; gap: 10px;
    padding: 10px 12px;
    border-radius: 999px;
    border: 1px solid ${border};
    background: #fff;
    cursor:pointer;
    font-size: 13px;
    font-weight: 500;
    transition: transform .12s ease, border-color .12s ease, background .12s ease;
  }
  .mmTab:hover{ transform: translateY(-1px); background: rgba(37,99,235,0.05); }
  .mmTabActive{
    border-color: rgba(37,99,235,0.22);
    background: rgba(37,99,235,0.10);
  }
  .mmTabIcon{
    width: 34px; height: 34px;
    border-radius: 999px;
    display:grid; place-items:center;
    border: 1px solid ${border};
    background: rgba(15,23,42,0.03);
    color: ${primary};
  }

  .mmControls{
    display:flex; align-items:center; justify-content:space-between;
    gap: 12px;
  }
  .mmControlsLeft{
    display:flex; align-items:center; gap: 12px;
    min-width:0;
  }
  .mmSearch{
    display:flex; align-items:center; gap: 10px;
    height: 42px;
    border-radius: 16px;
    border: 1px solid ${border};
    background: #fff;
    padding: 0 12px;
    box-shadow: 0 10px 20px rgba(15,23,42,0.05);
    min-width: 360px;
    max-width: 46vw;
  }
  .mmSearchIcon{ color: rgba(15,23,42,0.50); display:grid; place-items:center; }
  .mmSort{
    display:flex; align-items:center; gap: 10px;
    height: 42px;
    border-radius: 16px;
    border: 1px solid ${border};
    background: #fff;
    padding: 0 12px;
    box-shadow: 0 10px 20px rgba(15,23,42,0.05);
  }
  .mmSortLabel{ font-size: 12px; color: ${muted}; font-weight: 500; white-space: nowrap; }

  .mmList{
    background: #fff;
    border: 1px solid ${border};
    border-radius: 18px;
    box-shadow: 0 10px 22px rgba(15,23,42,0.06);
    overflow:hidden;
  }
  .mmListHead{
    padding: 14px;
    display:flex; align-items:center; justify-content:space-between;
    gap: 12px;
    border-bottom: 1px solid ${border};
    background: linear-gradient(180deg, rgba(15,23,42,0.02), rgba(15,23,42,0.00));
  }
  .mmListTitle{ font-size: 13px; font-weight: 600; }

  .mmTableWrap{ width:100%; overflow:auto; }
  .mmTable{ width:100%; border-collapse: separate; border-spacing: 0; min-width: 720px; }
  .mmTable thead th{
    font-size: 12px;
    color: ${muted};
    font-weight: 600;
    text-align:left;
    padding: 10px 14px;
    white-space: nowrap;
    border-bottom: 1px solid ${border};
    background: #fff;
    position: sticky;
    top: 0;
    z-index: 1;
  }
  .mmRow td{
    padding: 12px 14px;
    border-bottom: 1px solid rgba(15,23,42,0.06);
    font-size: 13px;
    vertical-align: middle;
  }
  .mmRow:hover{ background: rgba(37,99,235,0.05); }
  .mmName{ font-weight: 600; }
  .mmPrice{ font-weight: 600; white-space: nowrap; }
  .mmUnit{ color: ${muted}; }
  .mmThRight, .mmTdRight{ text-align:right; white-space: nowrap; }
  .mmActions{ display:inline-flex; gap: 8px; flex-wrap: wrap; justify-content:flex-end; }

  .mmCards{ display:none; padding: 12px; gap: 12px; }
  .mmCard{
    border: 1px solid rgba(15,23,42,0.08);
    border-radius: 16px;
    padding: 12px;
    background: #fff;
    box-shadow: 0 10px 20px rgba(15,23,42,0.05);
  }
  .mmCardTop{ display:flex; justify-content:space-between; gap: 12px; align-items:flex-start; }
  .mmCardName{ font-size: 13px; font-weight: 650; }
  .mmCardHint{ margin-top: 6px; font-size: 12px; color: ${muted}; }
  .mmCardBadge{
    font-size: 11px;
    padding: 6px 10px;
    border-radius: 999px;
    border: 1px solid rgba(37,99,235,0.20);
    background: rgba(37,99,235,0.10);
    color: ${primary};
    font-weight: 600;
  }
  .mmCardActions{ margin-top: 10px; display:flex; gap: 10px; flex-wrap: wrap; justify-content:flex-end; }

  .mmEmpty{ padding: 28px 14px; text-align:center; }
  .mmEmptyIcon{
    width: 52px; height: 52px; border-radius: 18px; margin: 0 auto;
    display:grid; place-items:center; border: 1px solid ${border}; background: rgba(15,23,42,0.02);
    color: rgba(15,23,42,0.55);
  }
  .mmEmptyTitle{ margin-top: 12px; font-weight: 600; }
  .mmEmptySub{ margin-top: 6px; font-size: 12px; color: ${muted}; }

  @media (max-width: 820px){
    .mmControls{ flex-direction: column; align-items: stretch; }
    .mmControlsLeft{ flex-direction: column; align-items: stretch; }
    .mmSearch{ min-width: 100%; max-width: 100%; }
    .mmSort{ width: 100%; }
  }
  @media (max-width: 720px){
    .mmTableWrap{ display:none; }
    .mmCards{ display:grid; }
  }
  `;
}

/* ---------------- Icons ---------------- */

function IconArrowLeft() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" aria-hidden="true">
      <path d="M15 18l-6-6 6-6" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}
function IconSliders() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" aria-hidden="true">
      <path d="M4 6h10M18 6h2" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
      <path d="M14 6a2 2 0 1 0 4 0a2 2 0 0 0-4 0Z" stroke="currentColor" strokeWidth="2" />
      <path d="M4 12h2M10 12h10" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
      <path d="M6 12a2 2 0 1 0 4 0a2 2 0 0 0-4 0Z" stroke="currentColor" strokeWidth="2" />
      <path d="M4 18h10M18 18h2" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
      <path d="M14 18a2 2 0 1 0 4 0a2 2 0 0 0-4 0Z" stroke="currentColor" strokeWidth="2" />
    </svg>
  );
}
function IconUser() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" aria-hidden="true">
      <path d="M20 21a8 8 0 0 0-16 0" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
      <path d="M12 12a4 4 0 1 0 0-8a4 4 0 0 0 0 8Z" stroke="currentColor" strokeWidth="2" />
    </svg>
  );
}
function IconPlus() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" aria-hidden="true">
      <path d="M12 5v14M5 12h14" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
    </svg>
  );
}
function IconSearch() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" aria-hidden="true">
      <path d="M10.5 18a7.5 7.5 0 1 1 0-15a7.5 7.5 0 0 1 0 15Z" stroke="currentColor" strokeWidth="2" />
      <path d="M16.5 16.5L21 21" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
    </svg>
  );
}
function IconSearchBig() {
  return (
    <svg width="26" height="26" viewBox="0 0 24 24" fill="none" aria-hidden="true">
      <path d="M10.5 18a7.5 7.5 0 1 1 0-15a7.5 7.5 0 0 1 0 15Z" stroke="currentColor" strokeWidth="2" />
      <path d="M16.5 16.5L21 21" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
    </svg>
  );
}
function IconEdit() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" aria-hidden="true">
      <path d="M12 20h9" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
      <path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4 12.5-12.5Z" stroke="currentColor" strokeWidth="2" strokeLinejoin="round" />
    </svg>
  );
}
function IconTrash() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" aria-hidden="true">
      <path d="M3 6h18" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
      <path d="M8 6V4h8v2" stroke="currentColor" strokeWidth="2" strokeLinejoin="round" />
      <path d="M19 6l-1 16H6L5 6" stroke="currentColor" strokeWidth="2" strokeLinejoin="round" />
      <path d="M10 11v6M14 11v6" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
    </svg>
  );
}
function IconLayers() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" aria-hidden="true">
      <path d="M12 2 2 7l10 5 10-5-10-5Z" stroke="currentColor" strokeWidth="2" strokeLinejoin="round" />
      <path d="M2 17l10 5 10-5" stroke="currentColor" strokeWidth="2" strokeLinejoin="round" />
      <path d="M2 12l10 5 10-5" stroke="currentColor" strokeWidth="2" strokeLinejoin="round" />
    </svg>
  );
}
function IconBolt() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" aria-hidden="true">
      <path d="M13 2 3 14h7l-1 8 10-12h-7l1-8Z" stroke="currentColor" strokeWidth="2" strokeLinejoin="round" />
    </svg>
  );
}
function IconSquare() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" aria-hidden="true">
      <path d="M4 4h16v16H4V4Z" stroke="currentColor" strokeWidth="2" />
    </svg>
  );
}
function IconTool() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" aria-hidden="true">
      <path
        d="M14.7 6.3a4 4 0 0 0-5.4 5.4L3 18l3 3 6.3-6.3a4 4 0 0 0 5.4-5.4l-2.2 2.2-2.6-2.6 2.2-2.6Z"
        stroke="currentColor"
        strokeWidth="2"
        strokeLinejoin="round"
      />
    </svg>
  );
}

function IconImage() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" aria-hidden="true">
      <path
        d="M4 6a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6Z"
        stroke="currentColor"
        strokeWidth="2"
      />
      <path
        d="M8 14l2.5-2.5L14 15l2-2 2 2"
        stroke="currentColor"
        strokeWidth="2"
        strokeLinejoin="round"
      />
      <path
        d="M9 9.5a1.2 1.2 0 1 0 0-2.4a1.2 1.2 0 0 0 0 2.4Z"
        stroke="currentColor"
        strokeWidth="2"
      />
    </svg>
  );
}

