import React, { useEffect, useMemo, useState } from "react";
import Modal from "../components/common/Modal";
import { Btn } from "../components/common/UI";
import { UI } from "../constants/pvc";
import { money } from "../utils/helpers";
import PVCEditor from "../features/editor/PVCEditor.jsx";

export default function OfferWorkspace({
  offer,
  materials,
  onBack,
  onOpenMaterials,
  onUpdateOffer,
  onDeleteOffer,
  logoSrc,
  userLabel = "User",
}) {
  const [view, setView] = useState("overview"); // overview | editor
  const [dangerOpen, setDangerOpen] = useState(false);
  const [posDeleteId, setPosDeleteId] = useState(null);

  // ✅ editor state (single source of truth)
  const [focusPosition, setFocusPosition] = useState(null); // position object (or DB row)
  const [editorMode, setEditorMode] = useState("create"); // "create" | "edit"

  // Offer details draft
  const [draft, setDraft] = useState({
    name: "",
    description: "", // ✅ NEW
    margin: 0,
    color: "[BB] Bardhë-Bardhë",
    profileId: "",
    ironId: "",
  });

  useEffect(() => {
    if (!offer) return;

    setDraft({
      name: offer.name || "",
      description: offer.description || "", // ✅ NEW
      margin: Number(offer.margin) || 0,
      color: offer.color || "[BB] Bardhë-Bardhë",
      profileId: offer.profileId || materials?.profiles?.[0]?.id || "",
      ironId: offer.ironId || materials?.irons?.[0]?.id || "",
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [offer?.id]);

  if (!offer) {
    return (
      <div style={{ padding: 24 }}>
        <Btn onClick={onBack}>← Kthehu</Btn>
        <div style={{ marginTop: 10, color: UI.muted }}>Oferta nuk u gjet.</div>
      </div>
    );
  }



  
const parseMaybeJson = (v) => {
  if (!v) return null;
  if (typeof v === "object") return v;           // already parsed
  if (typeof v !== "string") return null;
  try { return JSON.parse(v); } catch { return null; }
};

const normalizePositionRow = (row) => {
  // row is DB row OR already-flat position
  const parsed = parseMaybeJson(row?.data);

  // If it’s a DB row with data JSON, merge parsed into one object
  if (parsed) {
    return {
      ...parsed,
      id: row.id,                 // DB id
      qty: row.qty ?? parsed.qty ?? 1,
      total: row.total ?? parsed.total ?? 0,
      // keep raw if you want:
      __row: row,
    };
  }

  // Otherwise assume it’s already a position object
  return {
    ...row,
    qty: row?.qty ?? 1,
    total: row?.total ?? 0,
  };
};


  const positions = offer.positions || [];
const posKey = (p) => String(p?.id ?? p?._cid ?? p?.client_key ?? "");

  const offerTotal = useMemo(() => {
    return positions.reduce((sum, p) => {
      const qty = Math.max(1, Number(p.qty || 1));
      return sum + Number(p.total || 0) * qty;
    }, 0);
  }, [positions]);

  const isDirty =
    (draft.name || "") !== (offer.name || "") ||
    (draft.description || "") !== (offer.description || "") ||
    Number(draft.margin || 0) !== Number(offer.margin || 0) ||
    (draft.color || "") !== (offer.color || "") ||
    (draft.profileId || "") !== (offer.profileId || "") ||
    (draft.ironId || "") !== (offer.ironId || "");

  const saveOfferDetails = () => {
    onUpdateOffer({
      name: (draft.name || "").trim() || "Oferta",
      description: (draft.description || "").trim(), // ✅ NEW
      margin: Number(draft.margin) || 0,
      color: draft.color,
      profileId: draft.profileId,
      ironId: draft.ironId,
      updatedAt: new Date().toISOString(),
    });
  };

  const cancelOfferDetails = () => {
    setDraft({
      name: offer.name || "",
      description: offer.description || "",
      margin: Number(offer.margin) || 0,
      color: offer.color || "[BB] Bardhë-Bardhë",
      profileId: offer.profileId || materials?.profiles?.[0]?.id || "",
      ironId: offer.ironId || materials?.irons?.[0]?.id || "",
    });
  };

const updateQty = (key, nextQty) => {
  const qty = Math.max(1, Math.min(999, Number(nextQty) || 1));
  const nextPositions = positions.map((p) => (posKey(p) === String(key) ? { ...p, qty } : p));
  onUpdateOffer({ positions: nextPositions, updatedAt: new Date().toISOString() });
};

const deletePosition = (key) => {
  const nextPositions = positions.filter((p) => posKey(p) !== String(key));
  onUpdateOffer({ positions: nextPositions, updatedAt: new Date().toISOString() });
};

const openEditorForEdit = (id) => {
  const row = positions.find((p) => String(p?.id) === String(id));
  if (!row) return;
  setFocusPosition(normalizePositionRow(row)); // ✅ now PVCEditor gets real fields
  setEditorMode("edit");
  setView("editor");
};



  // ✅ OPEN EDITOR (NEW)
  const openEditorForNew = () => {
    setFocusPosition(null);
    setEditorMode("create");
    setView("editor");
  };

  // ✅ BACK TO OVERVIEW (IMPORTANT: clears editor state)
  const onBackToOverview = () => {
    setView("overview");
    setFocusPosition(null);
    setEditorMode("create");
  };

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

      {/* NAVBAR */}
      <header className="ow6Nav">
        <div className="ow6NavInner">
          <div className="ow6NavLeft">
            <div className="ow6LogoWrap" title="Logo">
              {logoSrc ? <img src={logoSrc} alt="Logo" className="ow6LogoImg" /> : <div className="ow6LogoFallback">PVC</div>}
            </div>

            <nav className="ow6Links" aria-label="Navigation">
              <button type="button" className="ow6Link" onClick={onBack} title="Dashboard">
                <span className="ow6LinkIcon">
                  <IconGrid />
                </span>
                Dashboard
              </button>

              <button type="button" className="ow6Link" onClick={onOpenMaterials} title="Materialet">
                <span className="ow6LinkIcon">
                  <IconSliders />
                </span>
                Materialet
              </button>
            </nav>
          </div>

          <button className="ow6UserBtn" type="button" title={userLabel} aria-label="User">
            <IconUser />
          </button>
        </div>
      </header>

      <main className="ow6Main">
        {view === "editor" ? (
          <section className="ow6EditorShell">
            <div className="ow6EditorTop">
              {/* ✅ IMPORTANT: use onBackToOverview (not just setView) */}
              <button className="ow6BackMini" type="button" onClick={onBackToOverview}>
                <IconArrowLeft /> Kthehu te Përmbledhja
              </button>

              <button className="ow6DangerMini" type="button" onClick={() => setDangerOpen(true)}>
                <IconTrash /> Fshij ofertën
              </button>
            </div>

            <div className="ow6EditorWrap">
              <PVCEditor
                offer={offer}
                materials={materials}
                onUpdateOffer={onUpdateOffer}
                onBackToOverview={onBackToOverview}
                focusPosition={focusPosition}
                setFocusPosition={setFocusPosition}
                editorMode={editorMode}
                setEditorMode={setEditorMode}
              />
            </div>
          </section>
        ) : (
          <section className="ow6Grid">
            {/* LEFT: POSITIONS */}
            <div className="card">
              <div className="cardHead">
                <div>
                  <div className="kicker">Pozicionet</div>
                  <div className="title">{positions.length} gjithsej</div>
                </div>

                <Btn variant="primary" onClick={openEditorForNew} style={{ borderRadius: 14, padding: "10px 14px" }}>
                  <span style={{ display: "inline-flex", alignItems: "center", gap: 10 }}>
                    <IconPlus /> Shto pozicion të ri
                  </span>
                </Btn>
              </div>

              {positions.length === 0 ? (
                <div className="emptyBox">
                  Ende pa pozicione. Kliko <b>Shto pozicion të ri</b> për të hapur editorin.
                </div>
              ) : (
                <div className="posTable">
                  <div className="posHeadRow">
                    <div className="th">Emri i pozicionit</div>
                    <div className="th">Tipi</div>
                    <div className="th">Masa</div>
                    <div className="th">Sasi</div>
                    <div className="th thRight">Totali</div>
                    <div className="th thRight">Veprime</div>
                  </div>

                  <div className="posBody">
                    {positions.map((p, idx) => {
                      const qty = Math.max(1, Number(p.qty || 1));

                      // support both formats: p OR p.data
                      const pos = p?.data ? { ...p.data, id: p.id, qty: p.qty ?? p.data.qty } : p;

                      const height = (pos.frameH || 0) + (pos.extraBottomProfile || 0) + (pos.hasRoll ? pos.rollHeight || 0 : 0);
                      const size = `${pos.frameW}×${height} mm`;
                      const lineTotal = Number(pos.total || 0) * qty;

                      return (
<div key={posKey(p)} className="posRow">
                          <div className="td tdStrong ellipsis">{pos.name || `Pozicioni ${idx + 1}`}</div>

                          <div className="td">
                            <span className="badge">{pos.isDoor ? "Derë" : "Dritare"}</span>
                          </div>

                          <div className="td mono ellipsis">{size}</div>

                          <div className="td">
                            <div className="qtyCtl">
                              <button type="button" className="qtyBtn" onClick={() => updateQty(p.id, qty - 1)} aria-label="Minus">
                                −
                              </button>
                              <input
                                className="qtyInput"
                                value={qty}
                                onChange={(e) => updateQty(p.id, e.target.value)}
                                inputMode="numeric"
                              />
                              <button type="button" className="qtyBtn" onClick={() => updateQty(p.id, qty + 1)} aria-label="Plus">
                                +
                              </button>
                            </div>
                          </div>

                          <div className="td tdRight tdStrong">€ {money(lineTotal)}</div>

                          <div className="td tdRight">
                            <div className="actions">
                              <button className="iconBtn" onClick={() => openEditorForEdit(p.id)} title="Edit" aria-label="Edit">
                                <IconEdit />
                              </button>
                              <button className="iconBtnDanger" onClick={() => setPosDeleteId(p.id)} title="Delete" aria-label="Delete">
                                <IconTrash />
                              </button>
                            </div>
                          </div>
                        </div>
                      );
                    })}
                  </div>

                  <div className="cards">
                    {positions.map((p, idx) => {
  const pos = normalizePositionRow(p);
  const qty = Math.max(1, Number(pos.qty || 1));

  const height = (pos.frameH || 0)
    + (pos.extraBottomProfile || 0)
    + (pos.hasRoll ? (pos.rollHeight || 0) : 0);

  const size = `${pos.frameW}×${height} mm`;
  const lineTotal = Number(pos.total || 0) * qty;

                      return (
                        <div key={String(pos.id ?? idx)} className="posRow">
                          <div className="pTop">
                            <div className="pLeft">
                              <div className="pName">{pos.name || `Pozicioni ${idx + 1}`}</div>
                              <div className="pSub">
                                <span className="badge">{pos.isDoor ? "Derë" : "Dritare"}</span>
                                <span className="dot">•</span>
                                <span className="mono">{size}</span>
                              </div>
                            </div>

                            <div className="pRight">
                              <div className="pTotal">€ {money(lineTotal)}</div>
                              <div className="actions">
                                <button className="iconBtn" onClick={() => openEditorForEdit(pos.id)} title="Edit" aria-label="Edit">
                                  <IconEdit />
                                </button>
                                <button className="iconBtnDanger" onClick={() => setPosDeleteId(p.id)} title="Delete" aria-label="Delete">
                                  <IconTrash />
                                </button>
                              </div>
                            </div>
                          </div>

                          <div className="pBottom">
                            <div className="pQtyLabel">Sasi</div>
                            <div className="qtyCtl qtyMobile">
                              <button type="button" className="qtyBtn" onClick={() => updateQty(p.id, qty - 1)} aria-label="Minus">
                                −
                              </button>
                              <input className="qtyInput" value={qty} onChange={(e) => updateQty(p.id, e.target.value)} inputMode="numeric" />
                              <button type="button" className="qtyBtn" onClick={() => updateQty(p.id, qty + 1)} aria-label="Plus">
                                +
                              </button>
                            </div>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                </div>
              )}
            </div>

            {/* RIGHT: DETAILS */}
            <div className="side">
              <div className="card">
                <div className="detailsHead">
                  <div>
                    <div className="kicker">Detajet e ofertës</div>
                    <div className="titleSmall">Ndrysho dhe ruaj</div>
                  </div>

                  <button className="dangerIconBtn" type="button" onClick={() => setDangerOpen(true)} title="Fshij ofertën" aria-label="Fshij ofertën">
                    <IconTrash />
                  </button>
                </div>

                <div className="formGrid">
                  <FieldBlock label="Emri i ofertës">
                    <input className="input" value={draft.name} onChange={(e) => setDraft((d) => ({ ...d, name: e.target.value }))} placeholder="p.sh. Oferta – Klienti X" />
                  </FieldBlock>

                  {/* ✅ NEW: Përshkrimi */}
                  <FieldBlock label="Përshkrimi (opsional)">
                    <textarea
                      className="input textarea"
                      value={draft.description}
                      onChange={(e) => setDraft((d) => ({ ...d, description: e.target.value }))}
                      placeholder="p.sh. Objekti X / Hyrja A"
                      rows={3}
                    />
                  </FieldBlock>

                  <div className="twoCol">
                    <FieldBlock label="Marzha (%)">
                      <input type="number" className="input" value={draft.margin} onChange={(e) => setDraft((d) => ({ ...d, margin: Number(e.target.value) || 0 }))} />
                    </FieldBlock>

                    <FieldBlock label="Ngjyra">
                      <select className="input" value={draft.color} onChange={(e) => setDraft((d) => ({ ...d, color: e.target.value }))}>
                        <option value="[BB] Bardhë-Bardhë">[BB] Bardhë-Bardhë</option>
                        <option value="Antracit">Antracit</option>
                        <option value="Golden Oak">Golden Oak</option>
                      </select>
                    </FieldBlock>
                  </div>

                  <FieldBlock label="Profili default">
                    <select className="input" value={draft.profileId} onChange={(e) => setDraft((d) => ({ ...d, profileId: e.target.value }))}>
                      {(materials?.profiles || []).map((p) => (
                        <option key={p.id} value={p.id}>
                          {p.name}
                        </option>
                      ))}
                    </select>
                  </FieldBlock>

                  <FieldBlock label="Armatura default">
                    <select className="input" value={draft.ironId} onChange={(e) => setDraft((d) => ({ ...d, ironId: e.target.value }))}>
                      {(materials?.irons || []).map((i) => (
                        <option key={i.id} value={i.id}>
                          {i.name}
                        </option>
                      ))}
                    </select>
                  </FieldBlock>
                </div>

                <div className="saveBar">
                  <button className="ghostBtn" type="button" onClick={cancelOfferDetails} disabled={!isDirty}>
                    Anulo
                  </button>
                  <button className="primaryBtn" type="button" onClick={saveOfferDetails} disabled={!isDirty}>
                    Ruaj
                  </button>
                </div>
              </div>

              <div className="card totalCard">
                <div className="kicker">Totali (me sasi)</div>
                <div className="totalValue">€ {money(offerTotal)}</div>
                <div className="miniRows">
                  <div className="miniRow">
                    <span>Pozicione</span>
                    <b>{positions.length}</b>
                  </div>
                  <div className="miniRow">
                    <span>Përditësuar</span>
                    <b>{offer.updatedAt ? new Date(offer.updatedAt).toLocaleString() : "—"}</b>
                  </div>
                </div>
              </div>
            </div>

            {/* Delete position confirm */}
            <Modal
              open={!!posDeleteId}
              title="Fshij pozicionin"
              onClose={() => setPosDeleteId(null)}
              footer={
                <div style={{ display: "flex", justifyContent: "space-between", gap: 10 }}>
                  <Btn onClick={() => setPosDeleteId(null)} style={{ borderRadius: 12 }}>
                    Anulo
                  </Btn>
                  <Btn
                    variant="danger"
                    onClick={() => {
                      const id = posDeleteId;
                      setPosDeleteId(null);
                      deletePosition(id);
                    }}
                    style={{ borderRadius: 12 }}
                  >
                    Fshij
                  </Btn>
                </div>
              }
            >
              <div style={{ fontSize: 13, color: UI.ink, lineHeight: 1.5 }}>A je i sigurt që dëshiron ta fshish këtë pozicion?</div>
            </Modal>
          </section>
        )}

        {/* Delete offer confirm */}
        <Modal
          open={dangerOpen}
          title="Fshij ofertën"
          onClose={() => setDangerOpen(false)}
          footer={
            <div style={{ display: "flex", justifyContent: "space-between", gap: 10 }}>
              <Btn onClick={() => setDangerOpen(false)} style={{ borderRadius: 12 }}>
                Anulo
              </Btn>
              <Btn
                variant="danger"
                onClick={() => {
                  setDangerOpen(false);
                  onDeleteOffer?.();
                }}
                style={{ borderRadius: 12 }}
              >
                Fshij përgjithmonë
              </Btn>
            </div>
          }
        >
          <div style={{ fontSize: 13, color: UI.ink, lineHeight: 1.5 }}>
            Kjo do ta fshijë përfundimisht <b>{offer.name}</b> dhe të gjitha pozicionet brenda saj.
          </div>
        </Modal>
      </main>
    </div>
  );
}

function FieldBlock({ label, children }) {
  return (
    <div>
      <div className="label">{label}</div>
      {children}
    </div>
  );
}

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 `
  .ow6Root{
    min-height:100vh;
    background:#f6f7fb;
    color:${text};
    font-family: Inter, ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial;
  }

  .ow6Nav{
    position:sticky; top:0; z-index:30;
    background: rgba(255,255,255,0.92);
    backdrop-filter: blur(10px);
    border-bottom:1px solid ${border};
  }
  .ow6NavInner{
    width:100%;
    padding:12px 18px;
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:12px;
  }
  .ow6NavLeft{ display:flex; align-items:center; gap:14px; min-width:0; }
  .ow6LogoWrap{
    width:44px; height:44px; border-radius:14px;
    overflow:hidden; background:transparent; border:none;
    display:grid; place-items:center; flex:0 0 auto;
  }
  .ow6LogoImg{ width:44px; height:44px; object-fit:contain; }
  .ow6LogoFallback{
    width:44px; height:44px; border-radius:14px;
    display:grid; place-items:center;
    background: rgba(37,99,235,0.10);
    color:${text}; font-size:12px; letter-spacing:.3px;
  }
  .ow6Links{ display:flex; align-items:center; gap:8px; min-width:0; }
  .ow6Link{
    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;
  }
  .ow6Link:hover{
    background: rgba(37,99,235,0.07);
    border-color: rgba(37,99,235,0.14);
    transform: translateY(-1px);
  }
  .ow6LinkIcon{
    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};
  }
  .ow6UserBtn{
    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;
    color: rgba(15,23,42,0.75);
  }
  .ow6UserBtn:hover{ transform: translateY(-1px); background: rgba(15,23,42,0.02); }

  .ow6Main{ padding:18px; }
  .ow6Grid{
    display:grid;
    grid-template-columns: 1.65fr 0.85fr;
    gap:14px;
    align-items:start;
  }
  .side{ display:grid; gap:14px; min-width:0; }

  .card{
    background:#fff;
    border:1px solid ${border};
    border-radius:18px;
    box-shadow: 0 10px 22px rgba(15,23,42,0.06);
    padding:14px;
    min-width:0;
  }
  .cardHead{
    display:flex;
    align-items:flex-end;
    justify-content:space-between;
    gap:12px;
    flex-wrap:wrap;
    padding-bottom:12px;
    border-bottom:1px solid ${border};
  }
  .kicker{ font-size:12px; color:${muted}; }
  .title{ margin-top:2px; font-size:14px; font-weight:650; }
  .titleSmall{ margin-top:2px; font-size:13px; font-weight:650; }

  .emptyBox{
    margin-top:12px;
    padding:14px;
    border-radius:14px;
    background: rgba(15,23,42,0.02);
    border: 1px dashed rgba(15,23,42,0.18);
    color:${muted};
    font-size:13px;
    line-height:1.5;
  }

  .posTable{
    margin-top:12px;
    border:1px solid rgba(15,23,42,0.08);
    border-radius:16px;
    overflow:hidden;
    background:#fff;
    --posCols: minmax(240px, 2.2fr) 0.9fr 1.1fr 1.3fr 140px 120px;
  }

  .posHeadRow{
    display:grid;
    grid-template-columns: var(--posCols);
    padding:12px 14px;
    background: rgba(15,23,42,0.02);
    border-bottom:1px solid rgba(15,23,42,0.08);
    font-size:12px;
    color:${muted};
    font-weight:700;
  }

  .posRow{
    display:grid;
    grid-template-columns: var(--posCols);
    align-items:center;
    padding:14px 14px;
    border-bottom:1px solid rgba(15,23,42,0.08);
    background:#fff;
  }
  .posRow:last-child{ border-bottom:none; }
  .posRow:hover{ background: rgba(37,99,235,0.04); }

  .thRight, .tdRight{ text-align:right; }
  .ellipsis{ white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
  .tdStrong{ font-weight:700; font-size:13px; }
  .mono{ font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size:12.5px; }

  .badge{
    display:inline-flex;
    align-items:center;
    padding:6px 10px;
    border-radius:999px;
    border: 1px solid rgba(37,99,235,0.18);
    background: rgba(37,99,235,0.10);
    color:${primary};
    font-weight:700;
    font-size:12px;
    white-space:nowrap;
  }

  .qtyCtl{
    display:inline-flex;
    align-items:center;
    gap:8px;
    border: 1px solid ${border};
    border-radius: 14px;
    padding: 8px;
    background:#fff;
    width: 170px;
    justify-content:space-between;
    box-shadow: 0 8px 18px rgba(15,23,42,0.05);
  }
  .qtyBtn{
    width:34px; height:34px;
    border-radius:12px;
    border: 1px solid ${border};
    background: rgba(15,23,42,0.02);
    cursor:pointer;
    font-size:18px;
    line-height:1;
    transition: transform .12s ease, background .12s ease;
  }
  .qtyBtn:hover{ transform: translateY(-1px); background: rgba(37,99,235,0.06); }
  .qtyInput{
    width: 48px;
    height:34px;
    border:none;
    outline:none;
    text-align:center;
    font-weight:800;
    background:transparent;
    font-size:13px;
  }

  .actions{ display:inline-flex; justify-content:flex-end; gap:10px; }
  .iconBtn{
    width:38px; height:38px;
    border-radius:14px;
    border:1px solid ${border};
    background:#fff;
    cursor:pointer;
    display:grid;
    place-items:center;
    color: rgba(15,23,42,0.75);
  }
  .iconBtn:hover{
    background: rgba(37,99,235,0.06);
    border-color: rgba(37,99,235,0.18);
    color:${primary};
  }
  .iconBtnDanger{
    width:38px; height:38px;
    border-radius:14px;
    border:1px solid rgba(239,68,68,0.22);
    background: rgba(239,68,68,0.08);
    cursor:pointer;
    display:grid;
    place-items:center;
    color: rgba(239,68,68,0.95);
  }
  .iconBtnDanger:hover{ background: rgba(239,68,68,0.12); }

  .cards{ display:none; padding:12px; gap:12px; }
  .pCard{
    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);
  }
  .pTop{ display:flex; justify-content:space-between; gap:12px; align-items:flex-start; }
  .pLeft{ min-width:0; }
  .pName{ font-size:13px; font-weight:700; }
  .pSub{ margin-top:6px; display:flex; gap:8px; align-items:center; flex-wrap:wrap; color:${muted}; font-size:12px; }
  .dot{ opacity:.6; }
  .pRight{ display:flex; flex-direction:column; align-items:flex-end; gap:8px; }
  .pTotal{ font-weight:800; white-space:nowrap; }
  .pBottom{ margin-top:10px; display:flex; justify-content:space-between; gap:12px; align-items:center; }
  .pQtyLabel{ font-size:12px; color:${muted}; font-weight:700; }
  .qtyMobile{ width: 190px; }

  .detailsHead{
    display:flex;
    justify-content:space-between;
    gap:12px;
    align-items:flex-start;
    padding-bottom:12px;
    border-bottom: 1px solid ${border};
  }
  .dangerIconBtn{
    width:40px; height:40px;
    border-radius:12px;
    border:1px solid rgba(239,68,68,0.22);
    background: rgba(239,68,68,0.08);
    cursor:pointer;
    display:grid; place-items:center;
    color: rgba(239,68,68,0.95);
  }

  .formGrid{ margin-top:12px; display:grid; gap:12px; }
  .twoCol{ display:grid; grid-template-columns: 1fr 1fr; gap:12px; }
  .label{ font-size:12px; color:${text}; font-weight:700; margin-bottom:6px; }
  .input{
    width:100%;
    height:42px;
    border:1px solid ${border};
    border-radius:12px;
    padding: 0 12px;
    font-size:13px;
    outline:none;
    background:#fff;
    transition: box-shadow .12s ease, border-color .12s ease;
    box-sizing:border-box;
  }
  .input:focus{
    border-color: rgba(37,99,235,0.30);
    box-shadow: 0 0 0 4px rgba(37,99,235,0.10);
  }
  .textarea{
    height:auto;
    padding:10px 12px;
    resize:vertical;
    line-height:1.4;
  }

  .saveBar{
    margin-top:14px;
    padding-top:12px;
    border-top: 1px solid ${border};
    display:flex;
    gap:10px;
    justify-content:flex-end;
  }
  .ghostBtn{
    height:40px;
    padding:0 12px;
    border-radius:12px;
    border:1px solid ${border};
    background:#fff;
    cursor:pointer;
    font-weight:700;
    font-size:13px;
  }
  .ghostBtn:disabled{ opacity:.45; cursor:not-allowed; }
  .primaryBtn{
    height:40px;
    padding:0 14px;
    border-radius:12px;
    border:1px solid rgba(37,99,235,0.20);
    background: rgba(37,99,235,0.92);
    color:#fff;
    cursor:pointer;
    font-weight:800;
    font-size:13px;
    box-shadow: 0 10px 22px rgba(37,99,235,0.18);
  }
  .primaryBtn:disabled{ opacity:.45; cursor:not-allowed; box-shadow:none; }

  .totalCard{ padding:14px; }
  .totalValue{ margin-top:6px; font-size:28px; font-weight:900; }
  .miniRows{ margin-top:12px; display:grid; gap:8px; font-size:12px; color:${muted}; }
  .miniRow{ display:flex; justify-content:space-between; gap:10px; }
  .miniRow b{ color:${text}; font-weight:700; }

  .ow6EditorShell{ display:grid; gap:12px; }
  .ow6EditorTop{
    display:flex; justify-content:space-between; align-items:center; gap:12px;
    background:#fff;
    border:1px solid ${border};
    border-radius:18px;
    box-shadow: 0 10px 22px rgba(15,23,42,0.06);
    padding: 10px 12px;
  }
  .ow6BackMini{
    display:inline-flex; align-items:center; gap:8px;
    border:none;
    background: transparent;
    cursor:pointer;
    padding:10px 10px;
    border-radius:12px;
    color:${text};
    font-weight:700;
  }
  .ow6BackMini:hover{ background: rgba(37,99,235,0.06); }
  .ow6DangerMini{
    display:inline-flex; align-items:center; gap:8px;
    border:1px solid rgba(239,68,68,0.22);
    background: rgba(239,68,68,0.08);
    color: rgba(239,68,68,0.95);
    cursor:pointer;
    padding:10px 12px;
    border-radius:12px;
    font-weight:800;
  }
  .ow6EditorWrap{
    background:#fff;
    border:1px solid ${border};
    border-radius:18px;
    box-shadow: 0 10px 22px rgba(15,23,42,0.06);
    overflow:hidden;
  }

  @media (max-width: 1040px){
    .ow6Grid{ grid-template-columns: 1fr; }
    .twoCol{ grid-template-columns: 1fr; }
  }
  @media (max-width: 900px){
    .posHeadRow, .posBody{ display:none; }
    .cards{ display:grid; }
  }
  `;
}

/* Icons (same style) */
const ICON_PROPS = { stroke: "currentColor", strokeWidth: 2, strokeLinecap: "round", strokeLinejoin: "round", fill: "none" };

function IconGrid() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" aria-hidden="true">
      <path d="M4 4h7v7H4z" {...ICON_PROPS} />
      <path d="M13 4h7v7h-7z" {...ICON_PROPS} />
      <path d="M4 13h7v7H4z" {...ICON_PROPS} />
      <path d="M13 13h7v7h-7z" {...ICON_PROPS} />
    </svg>
  );
}
function IconSliders() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" aria-hidden="true">
      <path d="M4 6h10" {...ICON_PROPS} />
      <path d="M18 6h2" {...ICON_PROPS} />
      <path d="M14 6a2 2 0 1 0 4 0a2 2 0 0 0-4 0Z" {...ICON_PROPS} />
      <path d="M4 12h2" {...ICON_PROPS} />
      <path d="M10 12h10" {...ICON_PROPS} />
      <path d="M6 12a2 2 0 1 0 4 0a2 2 0 0 0-4 0Z" {...ICON_PROPS} />
      <path d="M4 18h10" {...ICON_PROPS} />
      <path d="M18 18h2" {...ICON_PROPS} />
      <path d="M14 18a2 2 0 1 0 4 0a2 2 0 0 0-4 0Z" {...ICON_PROPS} />
    </svg>
  );
}
function IconUser() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" aria-hidden="true">
      <path d="M20 21a8 8 0 0 0-16 0" {...ICON_PROPS} />
      <path d="M12 12a4 4 0 1 0 0-8a4 4 0 0 0 0 8Z" {...ICON_PROPS} />
    </svg>
  );
}
function IconPlus() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" aria-hidden="true">
      <path d="M12 5v14" {...ICON_PROPS} />
      <path d="M5 12h14" {...ICON_PROPS} />
    </svg>
  );
}
function IconEdit() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" aria-hidden="true">
      <path d="M12 20h9" {...ICON_PROPS} />
      <path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4 12.5-12.5Z" {...ICON_PROPS} />
    </svg>
  );
}
function IconTrash() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" aria-hidden="true">
      <path d="M3 6h18" {...ICON_PROPS} />
      <path d="M8 6V4h8v2" {...ICON_PROPS} />
      <path d="M19 6l-1 16H6L5 6" {...ICON_PROPS} />
      <path d="M10 11v6" {...ICON_PROPS} />
      <path d="M14 11v6" {...ICON_PROPS} />
    </svg>
  );
}
function IconArrowLeft() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" aria-hidden="true">
      <path d="M15 18l-6-6 6-6" {...ICON_PROPS} />
    </svg>
  );
}
