// PVCEditor - Position Page ONLY (no sidebar, pro layout, resizable split, compact right-click menu,
// inline live dimension edit, save button only on top row)

import React, { useEffect, useMemo, useRef, useState } from "react";
import Modal from "../../components/common/Modal";
import useMeasure from "../../hooks/useMeasure";
import { Btn, Field, Select, TextInput } from "../../components/common/UI";
import { UI, FRAME_WELD_ADD_MM, SASH_REDUCE_MM, BEAD_REDUCE_MM, IRON_REDUCE_MM } from "../../constants/pvc";
import { money, uid } from "../../utils/helpers";
import {
  IconFrame,
  IconGlass,
  IconGlassType,
  IconIrregular,
  IconRoll,
  IconSash,
  IconSplit,
  IconStaticGlass,
  IconT,
  renderOpening,
} from "../../components/icons/Icons";

export default function PVCEditor({ offer, materials, onUpdateOffer, onBackToOverview, focusPosition }) {
  // ===================== CONSTANTS =====================
  const WORKSPACE_TOP = 78;

  // ===================== DATA =====================
  const margin = Number(offer?.margin || 0);

  const profile = useMemo(() => {
    return materials?.profiles?.find((p) => p.id === offer.profileId) || materials?.profiles?.[0] || null;
  }, [materials?.profiles, offer?.profileId]);

  const iron = useMemo(() => {
    return materials?.irons?.find((i) => i.id === offer.ironId) || materials?.irons?.[0] || null;
  }, [materials?.irons, offer?.ironId]);

  const [glassTypeId, setGlassTypeId] = useState(materials?.glassTypes?.[0]?.id || "stopsol");
  const [glassModal, setGlassModal] = useState(false);

  useEffect(() => {
    if (!materials?.glassTypes?.length) return;
    if (!materials.glassTypes.find((g) => g.id === glassTypeId)) setGlassTypeId(materials.glassTypes[0].id);
    // eslint-disable-next-line
  }, [materials?.glassTypes]);

  const currentGlass = useMemo(() => {
    return materials?.glassTypes?.find((g) => g.id === glassTypeId) || materials?.glassTypes?.[0] || null;
  }, [materials?.glassTypes, glassTypeId]);

  // ===================== EDITOR STATE =====================
  const [frameModal, setFrameModal] = useState(false);
  const [frameW, setFrameW] = useState(2000);
  const [frameH, setFrameH] = useState(1400);
  const [frameExists, setFrameExists] = useState(false);
  const [isDoor, setIsDoor] = useState(false);
  const [doorPanelId, setDoorPanelId] = useState(null);
const [doorModal, setDoorModal] = useState(false);

  const [extraBottomProfile, setExtraBottomProfile] = useState(0);
const tDragRef = useRef({ dragging: false, id: null, orientation: null, startX: 0, startY: 0, startPosMm: 0 });

  const [shapeType, setShapeType] = useState("rect"); // rect | sloped
  const [topLeftOffset, setTopLeftOffset] = useState(0);
  const [topRightOffset, setTopRightOffset] = useState(0);
  const [shapeModal, setShapeModal] = useState(false);

const [doorImgOk, setDoorImgOk] = useState(true);
const [doorImgErr, setDoorImgErr] = useState("");




  const [dimOverlay, setDimOverlay] = useState({ open: false, left: 0, top: 0, kind: "", value: "" });
const dimInputRef = useRef(null);

useEffect(() => {
  if (dimOverlay.open) setTimeout(() => dimInputRef.current?.focus?.(), 0);
}, [dimOverlay.open]);

  const [hasRoll, setHasRoll] = useState(false);
  const [rollHeight, setRollHeight] = useState(180);

  const [tProfiles, setTProfiles] = useState([]);
  const [tModal, setTModal] = useState(false);
  const [tOrientation, setTOrientation] = useState("vertical");
  const [tSide, setTSide] = useState("middle");
  const [tOffsetMm, setTOffsetMm] = useState(0);

  const [activeSeg, setActiveSeg] = useState({ col: 0, row: 0 });
  const [segmentsGlass, setSegmentsGlass] = useState({});
  const [sashes, setSashes] = useState([]);
  const [selectedSashId, setSelectedSashId] = useState(null);

  const [panelModal, setPanelModal] = useState(false);
  const [panelOpening, setPanelOpening] = useState("turn-right+tilt-top");

  // Inline live edit (NO modal)
  const [dimEditOpen, setDimEditOpen] = useState(false);

  // ===================== MEASURE CANVAS =====================
  const [canvasWrapRef, canvasRect] = useMeasure();
  const editorW = Math.floor(canvasRect.width || 0);
  const editorH = Math.floor(canvasRect.height || 0);

  const [ready, setReady] = useState(false);
  useEffect(() => {
    if (canvasRect.width > 20 && canvasRect.height > 20) setReady(true);
  }, [canvasRect.width, canvasRect.height]);

  // ===================== RESIZABLE SPLIT =====================
  const layoutRef = useRef(null);
  const [rightW, setRightW] = useState(380);
  const dragRef = useRef({ dragging: false });

  useEffect(() => {
    const onMove = (e) => {
      if (!dragRef.current.dragging) return;
      const el = layoutRef.current;
      if (!el) return;
      const rect = el.getBoundingClientRect();

      let newW = rect.right - e.clientX;
      const minRight = 320;
      const maxRight = Math.max(360, rect.width - 460);
      newW = Math.max(minRight, Math.min(maxRight, newW));

      setRightW(Math.round(newW));
    };

    const onUp = () => {
      dragRef.current.dragging = false;
    };

    window.addEventListener("mousemove", onMove);
    window.addEventListener("mouseup", onUp);
    return () => {
      window.removeEventListener("mousemove", onMove);
      window.removeEventListener("mouseup", onUp);
    };
  }, []);





  // ===================== CONTEXT MENU (COMPACT) =====================
  const [ctx, setCtx] = useState({ open: false, x: 0, y: 0 });
  const closeCtx = () => setCtx({ open: false, x: 0, y: 0 });

  // Close context menu on ESC
  useEffect(() => {
    const onKey = (e) => {
      if (e.key === "Escape") closeCtx();
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);



  


  

  // ===================== DERIVED =====================
  const irregular = shapeType === "sloped";

  const irregularAngleDeg = useMemo(() => {
    if (!irregular || frameW <= 0) return 0;
    const delta = (topRightOffset || 0) - (topLeftOffset || 0);
    const rad = Math.atan(delta / frameW);
    return Math.round((rad * 180) / Math.PI);
  }, [irregular, topLeftOffset, topRightOffset, frameW]);

  const anyGlass = frameExists && (sashes.some((s) => s.hasGlass) || Object.keys(segmentsGlass).length > 0);
  const activeSegKey = `${activeSeg.col}-${activeSeg.row}`;
  const activeSegHasStaticGlass = !!segmentsGlass[activeSegKey];

  const perimeterM = useMemo(() => {
    if (!frameExists) return 0;
    return (2 * (frameW + frameH)) / 1000;
  }, [frameExists, frameW, frameH]);

  const extraBaseM = useMemo(() => {
    if (!frameExists || !extraBottomProfile) return 0;
    return frameW / 1000;
  }, [frameExists, frameW, extraBottomProfile]);

  const glassArea = useMemo(() => {
    if (!anyGlass) return 0;
    const gW = Math.max(frameW - 140, 0);
    const gH = Math.max(frameH - 140, 0);
    return (gW / 1000) * (gH / 1000);
  }, [anyGlass, frameW, frameH]);

  const profileCost = frameExists ? (perimeterM + extraBaseM) * Number(profile?.pricePerM || 0) : 0;
  const ironCost = frameExists ? perimeterM * Number(iron?.pricePerM || 0) : 0;
  const glassCost = anyGlass ? glassArea * Number(currentGlass?.pricePerM2 || 0) : 0;
const selectedDoorPanel = useMemo(() => {
  if (!isDoor || !doorPanelId) return null;
  return (materials?.doorPanels || []).find((p) => String(p.id) === String(doorPanelId)) || null;
}, [isDoor, doorPanelId, materials?.doorPanels]);

const doorPanelCost = isDoor ? Number(selectedDoorPanel?.price || 0) : 0;

const subtotal = profileCost + ironCost + glassCost + doorPanelCost;
  const profit = (subtotal * margin) / 100;
  const total = subtotal + profit;

  const fullHeightMm = frameH + (extraBottomProfile || 0) + (hasRoll ? rollHeight : 0);

  // ===================== HELPERS =====================
  const clampInt = (v, min, max) => {
    const n = Number(v);
    if (Number.isNaN(n)) return min;
    return Math.max(min, Math.min(max, Math.round(n)));
  };

  // ===================== HANDLERS =====================
  const handleSaveFrame = () => {
    const w = clampInt(frameW, 300, 8000);
    const h = clampInt(frameH, 300, 8000);
    setFrameW(w);
    setFrameH(h);

    setFrameExists(true);
    setSashes([]);
    setSelectedSashId(null);
    setTProfiles([]);
    setSegmentsGlass({});
    setActiveSeg({ col: 0, row: 0 });
    setShapeType("rect");
    setTopLeftOffset(0);
    setTopRightOffset(0);
    setFrameModal(false);
  };


  const drawPVCProfileVertical = (cx, y1, y2, thick = 16, gap = 6) => {
  const a = cx - thick / 2;
  const b = cx + thick / 2;




  // outer edges
  return (
    <g>
      <line x1={a} y1={y1} x2={a} y2={y2} stroke="#fff" strokeWidth={2} />
      <line x1={b} y1={y1} x2={b} y2={y2} stroke="#fff" strokeWidth={2} />
      {/* inner edges (PVC look) */}
      <line x1={a + gap} y1={y1} x2={a + gap} y2={y2} stroke="#fff" strokeWidth={1.2} opacity={0.9} />
      <line x1={b - gap} y1={y1} x2={b - gap} y2={y2} stroke="#fff" strokeWidth={1.2} opacity={0.9} />
    </g>
  );
};

const drawPVCProfileHorizontal = (cy, x1, x2, thick = 16, gap = 6) => {
  const a = cy - thick / 2;
  const b = cy + thick / 2;

  return (
    <g>
      <line x1={x1} y1={a} x2={x2} y2={a} stroke="#fff" strokeWidth={2} />
      <line x1={x1} y1={b} x2={x2} y2={b} stroke="#fff" strokeWidth={2} />
      <line x1={x1} y1={a + gap} x2={x2} y2={a + gap} stroke="#fff" strokeWidth={1.2} opacity={0.9} />
      <line x1={x1} y1={b - gap} x2={x2} y2={b - gap} stroke="#fff" strokeWidth={1.2} opacity={0.9} />
    </g>
  );
};


  const handleToggleRoll = () => {
    if (!frameExists) return alert("Së pari vendos kornizën.");
    setHasRoll((prev) => !prev);
  };

  const handleAddPanelClick = () => {
    if (!frameExists) return alert("Së pari vendos kornizën.");
    setPanelModal(true);
  };

  const handleConfirmPanel = () => {
    if (!frameExists) return;
    const segKey = `${activeSeg.col}-${activeSeg.row}`;

    if (selectedSashId != null) {
      setSashes((prev) => prev.map((s) => (s.id === selectedSashId ? { ...s, opening: panelOpening } : s)));
      setPanelModal(false);
      return;
    }

    const newId = sashes.length > 0 ? Math.max(...sashes.map((s) => s.id)) + 1 : 1;
    const newSash = { id: newId, opening: panelOpening, hasGlass: true, segmentKey: segKey };
    setSashes((prev) => [...prev, newSash]);
    setSelectedSashId(newId);

    setSegmentsGlass((prev) => {
      if (!prev[segKey]) return prev;
      const copy = { ...prev };
      delete copy[segKey];
      return copy;
    });

    setPanelModal(false);
  };

  const handleSplitVertical = () => {
    if (!frameExists) return alert("Së pari vendos kornizën.");
    const segKey = `${activeSeg.col}-${activeSeg.row}`;
    const segSashes = sashes.filter((s) => s.segmentKey === segKey);
    if (segSashes.length === 0) return alert("Së pari shto një krah (Z) në këtë pjesë.");
    if (segSashes.length >= 3) return;

    const newId = sashes.length > 0 ? Math.max(...sashes.map((s) => s.id)) + 1 : 1;
    const newSash = { id: newId, opening: panelOpening, hasGlass: true, segmentKey: segKey };
    setSashes((prev) => [...prev, newSash]);
    setSelectedSashId(newId);
  };

  const handleToggleGlassOnSash = () => {
    if (selectedSashId == null) return;
    setSashes((prev) => prev.map((s) => (s.id === selectedSashId ? { ...s, hasGlass: !s.hasGlass } : s)));
  };

  const handleStaticGlassToggle = () => {
    if (!frameExists) return alert("Së pari vendos kornizën.");
    const segKey = `${activeSeg.col}-${activeSeg.row}`;

    setSashes((prev) => prev.filter((s) => s.segmentKey !== segKey));
    setSelectedSashId(null);

    setSegmentsGlass((prev) => {
      const copy = { ...prev };
      if (copy[segKey]) delete copy[segKey];
      else copy[segKey] = true;
      return copy;
    });
  };

  const handleOpenTModal = () => {
    if (!frameExists) return alert("Së pari korniza.");
    setTOrientation("vertical");
    setTSide("middle");
    setTOffsetMm(0);
    setTModal(true);
  };

  const handleAddTProfile = () => {
  const nextId = tProfiles.length > 0 ? Math.max(...tProfiles.map((t) => t.id)) + 1 : 1;

  // default pos based on modal selection
  let posMm = 0;

  if (tOrientation === "vertical") {
    if (tSide === "middle") posMm = Math.round(frameW / 2);
    if (tSide === "left") posMm = clampInt(tOffsetMm, 1, frameW - 1);
    if (tSide === "right") posMm = clampInt(frameW - tOffsetMm, 1, frameW - 1);
  } else {
    // horizontal inside BODY only
    if (tSide === "middle") posMm = Math.round(frameH / 2);
    if (tSide === "top") posMm = clampInt(tOffsetMm, 1, frameH - 1);
    if (tSide === "bottom") posMm = clampInt(frameH - tOffsetMm, 1, frameH - 1);
  }

  const newT = { id: nextId, orientation: tOrientation, posMm };
  setTProfiles((prev) => [...prev, newT]);
  setTModal(false);
};


  const handleClearTs = () => {
    setTProfiles([]);
    setSegmentsGlass({});
    setActiveSeg({ col: 0, row: 0 });
    setTModal(false);
  };

  const resetEditorState = () => {
    setFrameExists(false);
    setSashes([]);
    setSegmentsGlass({});
    setSelectedSashId(null);
    setHasRoll(false);
    setRollHeight(180);
    setExtraBottomProfile(0);
    setIsDoor(false);
    setTProfiles([]);
    setActiveSeg({ col: 0, row: 0 });
    setShapeType("rect");
    setTopLeftOffset(0);
    setTopRightOffset(0);
    setGlassTypeId(materials?.glassTypes?.[0]?.id || "stopsol");
    setDimEditOpen(false);
  };


  // ===================== LOAD POSITION FOR EDIT =====================
useEffect(() => {
  if (!focusPosition) return;

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

  // focusPosition can be normalized already OR a DB row
  const p = parseMaybeJson(focusPosition.data) || focusPosition;

  setFrameExists(true);

  setFrameW(Number(p.frameW ?? 2000));
  setFrameH(Number(p.frameH ?? 1400));

  setExtraBottomProfile(Number(p.extraBottomProfile ?? 0));
  setIsDoor(!!p.isDoor);
  setDoorPanelId(p.doorPanelId ?? null);

  setHasRoll(!!p.hasRoll);
  setRollHeight(Number(p.rollHeight ?? 180));

  setShapeType(p.shapeType || "rect");
  setTopLeftOffset(Number(p.topLeftOffsetMm ?? 0));
  setTopRightOffset(Number(p.topRightOffsetMm ?? 0));

  setTProfiles(Array.isArray(p.tProfiles) ? JSON.parse(JSON.stringify(p.tProfiles)) : []);
  setSashes(Array.isArray(p.sashes) ? JSON.parse(JSON.stringify(p.sashes)) : []);
  setSegmentsGlass(p.segmentsGlass && typeof p.segmentsGlass === "object" ? { ...p.segmentsGlass } : {});

  setSelectedSashId(null);
  setActiveSeg({ col: 0, row: 0 });

  setGlassTypeId(p.glassTypeId || materials?.glassTypes?.[0]?.id || "stopsol");
  setDimEditOpen(false);
}, [focusPosition, materials?.glassTypes]);


const posKey = (p) => String(p?.id ?? p?._cid ?? "");
const handleSavePosition = () => {
  if (!frameExists) return alert("Vendos kornizën.");

  const positions = offer?.positions || [];
  const editing = !!focusPosition?.id; // DB id exists => edit

  const payload = {
    name: (focusPosition?.name || "Pozicioni").trim(),
    frameW,
    frameH,
    extraBottomProfile,
    isDoor,
    doorPanelId,
    hasRoll,
    rollHeight,
    shapeType,
    topLeftOffsetMm: topLeftOffset,
    topRightOffsetMm: topRightOffset,
    tProfiles: JSON.parse(JSON.stringify(tProfiles)),
    sashes: JSON.parse(JSON.stringify(sashes)),
    segmentsGlass: { ...segmentsGlass },
    profileId: offer.profileId,
    ironId: offer.ironId,
    color: offer.color || "[BB] Bardhë-Bardhë",
    view: "PAMJA NË MRENDI",
    glassTypeId,
  };

  const rowForApi = {
    ...(editing ? { id: focusPosition.id } : {}),     // ✅ keep DB id on edit
    qty: editing ? (focusPosition.qty ?? 1) : 1,      // ✅ keep qty on edit
    total,                                           // your computed total
    data: JSON.stringify(payload),                    // ✅ store JSON in DB column
  };

  const nextPositions = editing
    ? positions.map((r) => (String(r.id) === String(focusPosition.id) ? { ...r, ...rowForApi } : r))
    : [...positions, rowForApi];

  // ✅ ONLY ONE CALL
  onUpdateOffer({
    id: offer.id,
    positions: nextPositions,
    updatedAt: new Date().toISOString(),
  });

  resetEditorState();
  onBackToOverview?.();
};





  // ================== PREVIEW SVG (same logic) ==================
  const openingSvg = (type, x, y, w, h, stroke = "#111", sw = 1.2) => {
    const pad = 6;
    const top = y + pad;
    const bottom = y + h - pad;
    const left = x + pad;
    const right = x + w - pad;
    const midX = x + w / 2;
    const midY = y + h / 2;

    const line = (x1, y1, x2, y2, opacity = 1, width = sw) =>
      `<line x1="${x1}" y1="${y1}" x2="${x2}" y2="${y2}" stroke="${stroke}" stroke-width="${width}" opacity="${opacity}" />`;

    let s = "";
    if (type === "fixed") return s;

    if (type === "turn-right") {
      s += line(left, midY, right, top);
      s += line(left, midY, right, bottom);
    }
    if (type === "turn-left") {
      s += line(right, midY, left, top);
      s += line(right, midY, left, bottom);
    }
    if (type === "tilt-top") {
      s += line(left, bottom, midX, top);
      s += line(midX, top, right, bottom);

      const arrY = y + h * 0.5;
      const arrStart = midX + 18;
      const arrEnd = midX - 14;
      s += line(arrStart, arrY, arrEnd, arrY, 1, 1.0);
      s += `<polyline points="${arrEnd},${arrY} ${arrEnd + 6},${arrY - 4} ${arrEnd + 6},${arrY + 4}" fill="none" stroke="${stroke}" stroke-width="1.0" />`;
    }
    if (type === "tilt-top-center") {
      const apexY = top + 6;
      s += line(left, bottom, midX, apexY);
      s += line(midX, apexY, right, bottom);
    }
    if (type === "turn-right+tilt-top") {
      s += line(left, bottom, midX, top);
      s += line(midX, top, right, bottom);
      s += line(left, midY, right, top);
      s += line(left, midY, right, bottom);
    }
    return s;
  };


  const renderOpeningLocal = (type, x, y, w, h) => {
  const pad = 10;
  const top = y + pad;
  const bottom = y + h - pad;
  const left = x + pad;
  const right = x + w - pad;
  const midX = x + w / 2;
  const midY = y + h / 2;

  const stroke = "#fff";
  const sw = 1.25;

  const line = (x1, y1, x2, y2, opacity = 0.9, width = sw) => (
    <line x1={x1} y1={y1} x2={x2} y2={y2} stroke={stroke} strokeWidth={width} opacity={opacity} />
  );

  const arrowLeft = (yArrow) => (
    <g>
      {line(midX + 18, yArrow, midX - 14, yArrow, 1, 1.1)}
      <polyline
        points={`${midX - 14},${yArrow} ${midX - 8},${yArrow - 4} ${midX - 8},${yArrow + 4}`}
        fill="none"
        stroke={stroke}
        strokeWidth={1.1}
        opacity={0.95}
      />
    </g>
  );

  // FIXED: no opening lines
  if (type === "fixed") return null;

  // SLIDING (rails + arrows)
  if (type === "slide-left" || type === "slide-right" || type === "slide-both") {
    const railsOpacity = 0.55;

    const arrow = (x1, x2) => (
      <g>
        {line(x1, midY, x2, midY, 0.9, 1.2)}
        <polyline
          points={`${x2},${midY} ${x2 - 6},${midY - 4} ${x2 - 6},${midY + 4}`}
          fill="none"
          stroke={stroke}
          strokeWidth={1.2}
          opacity={0.9}
        />
      </g>
    );

    return (
      <g opacity={0.95}>
        {line(left, top, right, top, railsOpacity, 1)}
        {line(left, bottom, right, bottom, railsOpacity, 1)}

        {type === "slide-left" && arrow(right - 10, left + 10)}
        {type === "slide-right" && arrow(left + 10, right - 10)}
        {type === "slide-both" && (
          <g>
            {arrow(midX - 10, left + 10)}
            {arrow(midX + 10, right - 10)}
          </g>
        )}
      </g>
    );
  }

  // SWING (TURN)
  if (type === "turn-right") {
    // handle on LEFT, swing to right corners
    return (
      <g opacity={0.95}>
        {line(left, midY, right, top)}
        {line(left, midY, right, bottom)}
      </g>
    );
  }

  if (type === "turn-left") {
    // handle on RIGHT, swing to left corners
    return (
      <g opacity={0.95}>
        {line(right, midY, left, top)}
        {line(right, midY, left, bottom)}
      </g>
    );
  }

  // TILT (TOP)
  if (type === "tilt-top") {
    return (
      <g opacity={0.95}>
        {line(left, bottom, midX, top)}
        {line(midX, top, right, bottom)}
        {arrowLeft(midY)}
      </g>
    );
  }

  // TILT (TOP CENTER) — triangle only (like your diagrams)
  if (type === "tilt-top-center") {
    const apexY = top + 6;
    return (
      <g opacity={0.95}>
        {line(left, bottom, midX, apexY)}
        {line(midX, apexY, right, bottom)}
      </g>
    );
  }

  // TURN + TILT
  if (type === "turn-right+tilt-top") {
    return (
      <g opacity={0.95}>
        {/* tilt */}
        {line(left, bottom, midX, top)}
        {line(midX, top, right, bottom)}
        {/* turn */}
        {line(left, midY, right, top)}
        {line(left, midY, right, bottom)}
      </g>
    );
  }

  return null;
};


  const generatePreviewSVG = (pos, opts = {}) => {
    const w = Number(opts.w || 240);
    const h = Number(opts.h || 320);
    const showDims = opts.showDims !== false;

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

    const dimPadR = showDims ? 28 : 12;
    const dimPadB = showDims ? 26 : 12;
    const pad = 14;

    const availW = w - pad * 2 - dimPadR;
    const availH = h - pad * 2 - dimPadB;

    const s = Math.max(0.02, Math.min(availW / pos.frameW, availH / fullHeightMm));

    const outerW = pos.frameW * s;
    const rollH = pos.hasRoll ? (pos.rollHeight || 0) * s : 0;
    const bodyH = pos.frameH * s;
    const baseH = (pos.extraBottomProfile || 0) * s;
    const fullH = rollH + bodyH + baseH;

    const outerX = pad + (availW - outerW) / 2;
    const outerY = pad + (availH - fullH) / 2;

    const bodyY = outerY + rollH;
    const baseY = bodyY + bodyH;

    const innerOffset = Math.max(6, Math.round(12 * (w / 240)));
    const innerX = outerX + innerOffset;
    const innerY = bodyY + innerOffset;
    const innerW = outerW - innerOffset * 2;
    const innerBodyH = bodyH - innerOffset * 2;

    const innerTop = innerY;
    const innerBottom = innerY + innerBodyH;
    const innerLeft = innerX;
    const innerRight = innerX + innerW;

    const irregularPos = (pos.shapeType || "rect") === "sloped";
    const leftOffsetPx = irregularPos ? (pos.topLeftOffsetMm || 0) * s : 0;
    const rightOffsetPx = irregularPos ? (pos.topRightOffsetMm || 0) * s : 0;

    const topLineAtX = (x) => {
      if (!irregularPos || innerRight === innerLeft) return innerTop;
      const t = (x - innerLeft) / (innerRight - innerLeft);
      return innerTop + leftOffsetPx + t * (rightOffsetPx - leftOffsetPx);
    };

    const tThickness = Math.max(2.5, Math.round(4 * (w / 240)));
    const tVert = [];
    const tHoriz = [];
    const vBounds = [innerLeft, innerRight];
    const hBounds = [innerTop, innerBottom];

    (pos.tProfiles || []).forEach((t) => {
      if (t.orientation === "horizontal") {
        const offset = Number(t.offsetMm || 0);
        let cy;
        if (t.side === "top") cy = bodyY + offset * s;
        else if (t.side === "bottom") cy = bodyY + bodyH - offset * s;
        else cy = bodyY + bodyH / 2;

        const minCy = innerTop + tThickness;
        const maxCy = innerBottom - tThickness;
        cy = Math.max(minCy, Math.min(maxCy, cy));
        tHoriz.push({ id: t.id, cy });
        hBounds.push(cy);
      } else {
        const offset = Number(t.offsetMm || 0);
        let cx;
        if (t.side === "left") cx = outerX + offset * s;
        else if (t.side === "right") cx = outerX + outerW - offset * s;
        else cx = outerX + outerW / 2;

        const minCx = innerLeft + tThickness;
        const maxCx = innerRight - tThickness;
        cx = Math.max(minCx, Math.min(maxCx, cx));
        tVert.push({ id: t.id, cx });
        vBounds.push(cx);
      }
    });

    vBounds.sort((a, b) => a - b);
    hBounds.sort((a, b) => a - b);

    const cols = Math.max(1, vBounds.length - 1);
    const rows = Math.max(1, hBounds.length - 1);

    const glassFill = "rgba(59,130,246,0.14)";

    const rect = (x, y, ww, hh, stroke = "#111", sw = 1, fill = "none", rx = 0, opacity = 1) =>
      `<rect x="${x}" y="${y}" width="${ww}" height="${hh}" stroke="${stroke}" stroke-width="${sw}" fill="${fill}" rx="${rx}" opacity="${opacity}" />`;

    const line = (x1, y1, x2, y2, stroke = "#111", sw = 1, opacity = 1) =>
      `<line x1="${x1}" y1="${y1}" x2="${x2}" y2="${y2}" stroke="${stroke}" stroke-width="${sw}" opacity="${opacity}" />`;

    let svg = `<svg width="${w}" height="${h}" xmlns="http://www.w3.org/2000/svg" font-family="Arial" stroke-linecap="round">`;

    svg += rect(outerX, outerY, outerW, fullH, "#111", 1.3, "none");

    if (rollH > 0) svg += rect(outerX, outerY, outerW, rollH, "none", 0, "#e5e7eb", 0, 1);
    if (baseH > 0) svg += rect(outerX, baseY, outerW, baseH, "none", 0, "#e5e7eb", 0, 1);

    svg += rect(innerX, innerY, innerW, innerBodyH, "#111", 1.2, "none");

    if (irregularPos) {
      const t1Y = innerY + leftOffsetPx;
      const t2Y = innerY + rightOffsetPx;
      svg += `<path d="M ${innerX} ${t1Y} L ${innerX + innerW} ${t2Y} L ${innerX + innerW} ${innerY + innerBodyH} L ${innerX} ${innerY + innerBodyH} Z" fill="none" stroke="#111" stroke-width="1.2" />`;
    }

    for (let r = 0; r < rows; r++) {
      for (let c = 0; c < cols; c++) {
        const xl = vBounds[c];
        const xr = vBounds[c + 1];
        const yt = hBounds[r];
        const yb = hBounds[r + 1];
        const segKey = `${c}-${r}`;
        const segW = xr - xl;
        const segH = yb - yt;

        let blocked = false;
        if (irregularPos) {
          const topAtLeft = topLineAtX(xl);
          const topAtRight = topLineAtX(xr);
          const minTop = Math.min(topAtLeft, topAtRight);
          if (yb <= minTop) blocked = true;
        }
        if (blocked) continue;

        const segSashes = (pos.sashes || []).filter((s) => s.segmentKey === segKey).sort((a, b) => a.id - b.id);
        const count = segSashes.length;

        const isStatic = !!(pos.segmentsGlass && pos.segmentsGlass[segKey]) && count === 0;
        if (isStatic) {
          svg += rect(xl, yt, segW, segH, "#111", 0.8, glassFill);
        }

        if (count > 0) {
          const sashW = segW / count;
          for (let i = 0; i < count; i++) {
            const sObj = segSashes[i];
            const sx = xl + i * sashW;
            const sy = yt;

            svg += rect(sx, sy, sashW, segH, "#111", 1.0, sObj.hasGlass ? glassFill : "none");
            svg += openingSvg(sObj.opening, sx, sy, sashW, segH, "#111", 1.2);

            const handleDirRight =
              sObj.opening === "turn-right" || sObj.opening === "turn-right+tilt-top" || sObj.opening === "tilt-top";
            const isTiltCenter = sObj.opening === "tilt-top-center";

            let handleX = sx + sashW - 9;
            let handleY = sy + segH / 2 - 16;
            if (handleDirRight) handleX = sx + 5;
            if (isTiltCenter) {
              handleX = sx + sashW / 2 - 6;
              handleY = sy - 2;
            }

            svg += rect(handleX, handleY, isTiltCenter ? 12 : 4, isTiltCenter ? 12 : 32, "#111", 0.6, "#111", 1.5, 0.9);
          }
        }
      }
    }

    tVert.forEach((t) => {
      svg += rect(t.cx - tThickness / 2, innerTop, tThickness, innerBottom - innerTop, "none", 0, "#111");
    });
    tHoriz.forEach((t) => {
      svg += rect(innerLeft, t.cy - tThickness / 2, innerRight - innerLeft, tThickness, "none", 0, "#111");
    });

    if (showDims) {
      const dimX = outerX + outerW + 10;
      svg += line(dimX, outerY, dimX, outerY + fullH, "#111", 0.8);
      svg += `<text x="${dimX + 10}" y="${outerY + fullH / 2}" font-size="9" transform="rotate(90 ${dimX + 10} ${outerY + fullH / 2})">${fullHeightMm} mm</text>`;
      const dimY = outerY + fullH + 14;
      svg += line(outerX, dimY, outerX + outerW, dimY, "#111", 0.8);
      svg += `<text x="${outerX + outerW / 2}" y="${dimY + 12}" font-size="9" text-anchor="middle">${pos.frameW} mm</text>`;
    }

    svg += `</svg>`;
    return svg;
  };

  // ================== CUTTING LIST (unchanged) ==================
  const buildCuttingRows = (pos) => {
    const rows = [];
    let nr = 1;

    const frameVert = pos.frameH + FRAME_WELD_ADD_MM;
    const frameHor = pos.frameW + FRAME_WELD_ADD_MM;

    rows.push({ nr: nr++, code: "88171.BB [Strukturë]", length: frameVert, cut: "\\=/", pcs: 2, arm: "V309", armLen: frameVert - IRON_REDUCE_MM });
    rows.push({ nr: nr++, code: "88171.BB [Strukturë]", length: frameHor, cut: "\\=/", pcs: 2, arm: "V303", armLen: frameHor - IRON_REDUCE_MM });

    if (pos.hasRoll) rows.push({ nr: nr++, code: "ROLLBOX.BB [Roletë]", length: Math.round(pos.frameW), cut: "\\=/", pcs: 1, arm: "", armLen: 0 });

    if (pos.extraBottomProfile && pos.extraBottomProfile > 0) {
      rows.push({
        nr: nr++,
        code: pos.isDoor ? "THRESHOLD.BB [Prag dere]" : "BASE.BB [Profil poshtë]",
        length: Math.round(pos.frameW),
        cut: "\\=/",
        pcs: 1,
        arm: "",
        armLen: 0,
      });
    }

    if (pos.shapeType === "sloped") {
      rows.push({ nr: nr++, code: `IRREG SIPËR [majtas ${pos.topLeftOffsetMm || 0} / djathtas ${pos.topRightOffsetMm || 0} mm]`, length: "", cut: "", pcs: "", arm: "", armLen: 0 });
    }

    (pos.tProfiles || []).forEach((t) => {
      const len = t.orientation === "horizontal" ? pos.frameW + FRAME_WELD_ADD_MM : pos.frameH + FRAME_WELD_ADD_MM;
      rows.push({ nr: nr++, code: t.orientation === "horizontal" ? "T.BB [Horizontale]" : "T.BB [Vertikale]", length: len, cut: "\\=/", pcs: 1, arm: "", armLen: 0 });
    });

    if (pos.sashes && pos.sashes.length) {
      const sashCount = pos.sashes.length;
      const sashW = (pos.frameW - SASH_REDUCE_MM) / sashCount;
      const sashH = pos.frameH - SASH_REDUCE_MM;

      rows.push({ nr: nr++, code: "88270.BB [Profil Z]", length: Math.round(sashH), cut: "\\=/", pcs: 2 * sashCount, arm: "V303", armLen: Math.round(sashH - IRON_REDUCE_MM) });
      rows.push({ nr: nr++, code: "88270.BB [Profil Z]", length: Math.round(sashW), cut: "\\=/", pcs: 2 * sashCount, arm: "V303", armLen: Math.round(sashW - IRON_REDUCE_MM) });

      rows.push({ nr: nr++, code: "2451.BB [Llajsne]", length: Math.round(sashH - (BEAD_REDUCE_MM - 40)), cut: "/__/", pcs: 2 * sashCount, arm: "", armLen: 0 });
      rows.push({ nr: nr++, code: "2451.BB [Llajsne]", length: Math.round(sashW - (BEAD_REDUCE_MM - 40)), cut: "/__/", pcs: 2 * sashCount, arm: "", armLen: 0 });

      const hasAnyGlass = (pos.sashes || []).some((s) => s.hasGlass) || (pos.segmentsGlass && Object.keys(pos.segmentsGlass).length > 0);
      if (hasAnyGlass) {
        const glassW = Math.round(sashW - 8);
        const glassH = Math.round(sashH - 8);
        const glassCode = materials?.glassTypes?.find((g) => g.id === pos.glassTypeId)?.name || currentGlass?.name || "";
        rows.push({ nr: "X", code: glassCode, length: `${glassW}×${glassH}`, cut: "", pcs: sashCount, arm: "", armLen: 0 });
      }
    }

    return rows;
  };

  // ================== PRINT HELPERS (unchanged) ==================
  const openPrintWindow = (title, bodyHtml) => {
    const w = window.open("", "_blank");
    if (!w) return;
    w.document.write(`
      <html>
        <head>
          <title>${title}</title>
          <style>
            body{font-family:Arial,Helvetica,sans-serif;font-size:12px;margin:18px;color:#111;}
            h1,h2,h3,h4{margin:0 0 6px 0;}
            .small{font-size:10px;color:#555;}
            .muted{color:#555;}
            .page{page-break-after:always;margin-bottom:24px;}
            .headerRow{display:flex;justify-content:space-between;align-items:flex-start;gap:16px;}
            .thumbBox{flex:0 0 260px;max-width:260px;}
            .thumbBox svg{max-width:100%;height:auto;}
            .mainBox{flex:1;min-width:0;}
            .sketchBig{width:100%;display:flex;justify-content:center;}
            .sketchBig svg{width:92%;height:auto;}
            table{width:100%;border-collapse:collapse;margin-top:10px;}
            th,td{border:1px solid #666;padding:4px 6px;font-size:11px;vertical-align:top;}
            th{text-align:left;background:#f1f5f9;}
            .totals{margin-top:10px;font-size:12px;}
            @media print{ body{margin:12mm;} .page{page-break-after:always;} }
          </style>
        </head>
        <body>${bodyHtml}</body>
      </html>
    `);
    w.document.close();
    w.focus();
    w.print();
  };

  const buildPositionsForPrint = () => {
    const list = [...(offer.positions || [])];
    if (frameExists) {
      list.push({
        id: "__AKTIV__",
        name: "Pozicioni aktiv (jo i ruajtur)",
        frameW,
        frameH,
        extraBottomProfile,
        isDoor,
        hasRoll,
        rollHeight,
        shapeType,
        topLeftOffsetMm: topLeftOffset,
        topRightOffsetMm: topRightOffset,
        tProfiles: JSON.parse(JSON.stringify(tProfiles)),
        sashes: JSON.parse(JSON.stringify(sashes)),
        segmentsGlass: { ...segmentsGlass },
        subtotal,
        total,
        profileId: offer.profileId,
        ironId: offer.ironId,
        color: offer.color || "[BB] Bardhë-Bardhë",
        view: "PAMJA NË MRENDI",
        glassTypeId,
      });
    }
    return list;
  };



  const DOOR_THRESHOLD_MM = 20; // visual + cutting list. change if you want 30 etc.

const handleDoorClick = () => {
  if (!frameExists) return alert("Së pari vendos kornizën.");

  // If already door → clicking again can open modal to change panel
  setDoorModal(true);
};

const getSelectedDoorPanel = () => {
  if (!doorPanelId) return null;
  return (materials?.doorPanels || []).find((p) => String(p.id) === String(doorPanelId)) || null;
};

const handleSelectDoorPanel = (panel) => {
  setIsDoor(true);
  setDoorPanelId(panel?.id ?? null);
  setExtraBottomProfile((b) => (Number(b) > 0 ? b : DOOR_THRESHOLD_MM));
  setDoorModal(false);
};

const handleRemoveDoor = () => {
  setIsDoor(false);
  setDoorPanelId(null);
  setDoorModal(false);
};


  const handlePrintSketch = () => {
    const posList = buildPositionsForPrint();
    if (!posList.length) return alert("Nuk ka pozicione për print.");

    const html = posList
      .map((pos, idx) => {
        const svgBig = generatePreviewSVG(pos, { w: 560, h: 760, showDims: true });
        const fh = pos.frameH + (pos.extraBottomProfile || 0) + (pos.hasRoll ? pos.rollHeight || 0 : 0);
        return `
          <div class="page">
            <div class="small" style="text-align:right">${new Date().toLocaleDateString()}</div>
            <h3>Skicë (si në editor)</h3>
            <div class="muted">Oferta: <b>${offer.name}</b> — <b>${pos.name || `Pozicioni ${idx + 1}`}</b></div>
            <div class="muted">Dimensionet: <b>${pos.frameW} × ${fh} mm</b> • Pamja: <b>${pos.view || "PAMJA NË MRENDI"}</b></div>
            <div class="sketchBig" style="margin-top:10px">${svgBig}</div>
          </div>
        `;
      })
      .join("");

    openPrintWindow("Skicë", html);
  };

  const handlePrintOffer = () => {
    const posList = buildPositionsForPrint();
    if (!posList.length) return alert("Nuk ka pozicione për print.");

    const profName = materials?.profiles?.find((p) => p.id === offer.profileId)?.name || "";
    const ironName = materials?.irons?.find((i) => i.id === offer.ironId)?.name || "";

    const html = posList
      .map((pos, idx) => {
        const svgThumb = generatePreviewSVG(pos, { w: 260, h: 330, showDims: true });
        const rows = buildCuttingRows(pos);
        const fh = pos.frameH + (pos.extraBottomProfile || 0) + (pos.hasRoll ? pos.rollHeight || 0 : 0);
        const typeLabel = pos.isDoor ? "Derë" : "Dritare";
        const glassName = materials?.glassTypes?.find((g) => g.id === pos.glassTypeId)?.name || currentGlass?.name || "";

        return `
          <div class="page">
            <div class="small" style="text-align:right">${new Date().toLocaleDateString()}</div>
            <div class="headerRow">
              <div class="mainBox">
                <h3>OFERTË PVC</h3>
                <h4>${offer.name} — ${pos.name || `Pozicioni ${idx + 1}`}</h4>
                <div class="muted" style="line-height:1.45">
                  Tipi: <b>${typeLabel}</b><br/>
                  Profili: <b>${profName}</b><br/>
                  Armatura: <b>${ironName}</b><br/>
                  Ngjyra: <b>${pos.color}</b><br/>
                  Xhami: <b>${glassName}</b><br/>
                  Dimensionet: <b>${pos.frameW} × ${fh} mm</b><br/>
                  Pamja: <b>${pos.view || "PAMJA NË MRENDI"}</b>
                  ${pos.shapeType === "sloped" ? `<br/>Irreg: majtas ${pos.topLeftOffsetMm || 0} mm, djathtas ${pos.topRightOffsetMm || 0} mm` : ""}
                </div>
              </div>
              <div class="thumbBox">${svgThumb}</div>
            </div>

            <table>
              <thead>
                <tr>
                  <th>Nr</th>
                  <th>Kodi</th>
                  <th>Gjatësia</th>
                  <th>Preja</th>
                  <th>Copë</th>
                  <th>Armaturë</th>
                  <th>Gjatësia</th>
                </tr>
              </thead>
              <tbody>
                ${rows
                  .map(
                    (r) => `
                  <tr>
                    <td>${r.nr}</td>
                    <td>${r.code}</td>
                    <td>${r.length}</td>
                    <td>${r.cut}</td>
                    <td>${r.pcs}</td>
                    <td>${r.arm}</td>
                    <td>${r.armLen || ""}</td>
                  </tr>
                `
                  )
                  .join("")}
              </tbody>
            </table>

            <div class="totals"><strong>Totali i pozicionit:</strong> ${Number(pos.total || 0).toFixed(2)} €</div>
          </div>
        `;
      })
      .join("");

    openPrintWindow("Oferta", html);
  };

  const handlePrintInvoice = () => {
    const posList = buildPositionsForPrint();
    if (!posList.length) return alert("Nuk ka pozicione për faturë.");

    const sum = posList.reduce((s, p) => s + Number(p.total || 0), 0);

    const html = `
      <div style="display:flex;justify-content:space-between;gap:16px;align-items:flex-start;flex-wrap:wrap;">
        <div>
          <h3>Faturë / Invoice</h3>
          <div class="muted">Oferta: <b>${offer.name}</b><br/>Data: ${new Date().toLocaleDateString()}</div>
        </div>
        <div class="small" style="text-align:right">Gjeneruar nga PVC App</div>
      </div>

      <table>
        <thead>
          <tr>
            <th>Pozicioni</th>
            <th>Përshkrimi</th>
            <th>Sasia</th>
            <th>Çmimi</th>
            <th>Totali</th>
          </tr>
        </thead>
        <tbody>
          ${posList
            .map((p, i) => {
              const fh = p.frameH + (p.extraBottomProfile || 0) + (p.hasRoll ? p.rollHeight || 0 : 0);
              const label = p.isDoor ? "Derë" : "Dritare";
              const ir = p.shapeType === "sloped" ? ` (irreg majtas ${p.topLeftOffsetMm || 0} / djathtas ${p.topRightOffsetMm || 0} mm)` : "";
              return `
                <tr>
                  <td>${p.name || `Pozicioni ${i + 1}`}</td>
                  <td>${label} ${p.frameW}×${fh} mm${ir}</td>
                  <td>1</td>
                  <td>${Number(p.total || 0).toFixed(2)} €</td>
                  <td>${Number(p.total || 0).toFixed(2)} €</td>
                </tr>
              `;
            })
            .join("")}
        </tbody>
      </table>

      <div class="totals"><strong>Totali i faturës:</strong> ${sum.toFixed(2)} €</div>
    `;

    openPrintWindow("Faturë", html);
  };

  const handlePrintCutting = () => {
    const posList = buildPositionsForPrint();
    if (!posList.length) return alert("Nuk ka pozicione për listën e prerjeve.");

    const profName = materials?.profiles?.find((p) => p.id === offer.profileId)?.name || "";

    const html = posList
      .map((pos, idx) => {
        const svgThumb = generatePreviewSVG(pos, { w: 260, h: 330, showDims: true });
        const rows = buildCuttingRows(pos);
        return `
          <div class="page">
            <div class="headerRow">
              <div class="mainBox">
                <h3>Lista e prerjeve</h3>
                <div class="muted">Oferta: <b>${offer.name}</b> — <b>${pos.name || `Pozicioni ${idx + 1}`}</b></div>
                <div class="muted">Profili: <b>${profName}</b> • Ngjyra: <b>${pos.color}</b> • ${pos.view || "PAMJA NË MRENDI"}</div>
              </div>
              <div class="thumbBox">${svgThumb}</div>
            </div>

            <table>
              <thead>
                <tr>
                  <th>Nr</th>
                  <th>Kodi</th>
                  <th>Gjatësia</th>
                  <th>Preja</th>
                  <th>Copë</th>
                  <th>Armaturë</th>
                  <th>Gjatësia</th>
                </tr>
              </thead>
              <tbody>
                ${rows
                  .map(
                    (r) => `
                  <tr>
                    <td>${r.nr}</td>
                    <td>${r.code}</td>
                    <td>${r.length}</td>
                    <td>${r.cut}</td>
                    <td>${r.pcs}</td>
                    <td>${r.arm}</td>
                    <td>${r.armLen || ""}</td>
                  </tr>
                `
                  )
                  .join("")}
              </tbody>
            </table>
          </div>
        `;
      })
      .join("");

    openPrintWindow("Prerje", html);
  };

  // ================== RENDER SCALE (unchanged) ==================
  let scale = 1;
  if (frameExists && editorW > 0 && editorH > 0) {
    const sX = (editorW - 220) / frameW;
    const sY = (editorH - 180) / fullHeightMm;
    scale = Math.max(0.05, Math.min(sX, sY));
  }


  useEffect(() => {
  const onMove = (e) => {
    if (!tDragRef.current.dragging) return;

    const { id, orientation, startX, startY, startPosMm } = tDragRef.current;

    if (orientation === "vertical") {
      const deltaPx = e.clientX - startX;
      const deltaMm = deltaPx / scale;
      const nextPosMm = Math.round(startPosMm + deltaMm);

      setTProfiles((prev) =>
        prev.map((t) => (t.id === id ? { ...t, posMm: clampInt(nextPosMm, 1, frameW - 1) } : t))
      );
    } else {
      const deltaPx = e.clientY - startY;
      const deltaMm = deltaPx / scale;
      const nextPosMm = Math.round(startPosMm + deltaMm);

      setTProfiles((prev) =>
        prev.map((t) => (t.id === id ? { ...t, posMm: clampInt(nextPosMm, 1, frameH - 1) } : t))
      );
    }
  };

  const onUp = () => {
    if (!tDragRef.current.dragging) return;
    tDragRef.current.dragging = false;
  };

  window.addEventListener("pointermove", onMove);
  window.addEventListener("pointerup", onUp);
  return () => {
    window.removeEventListener("pointermove", onMove);
    window.removeEventListener("pointerup", onUp);
  };
}, [scale, frameW, frameH]);


  // ===================== TOOLS (Top Row + Context) =====================
  const tools = [
    { key: "frame", label: "Korniza", icon: <IconFrame />, onClick: () => setFrameModal(true), disabled: false },
    { key: "shape", label: "Forma", icon: <IconIrregular />, onClick: () => setShapeModal(true), disabled: !frameExists },
    { key: "panel", label: "Krah (Z)", icon: <IconSash />, onClick: handleAddPanelClick, disabled: !frameExists },
    { key: "split", label: "Nda", icon: <IconSplit />, onClick: handleSplitVertical, disabled: sashes.length === 0 },
    { key: "glass", label: "Xham ON/OFF", icon: <IconGlass />, onClick: handleToggleGlassOnSash, disabled: !selectedSashId },
    { key: "static", label: "Xham statik", icon: <IconStaticGlass />, onClick: handleStaticGlassToggle, disabled: !frameExists, active: frameExists && activeSegHasStaticGlass },
    { key: "roll", label: "Roletë", icon: <IconRoll />, onClick: handleToggleRoll, disabled: !frameExists, active: frameExists && hasRoll },
    { key: "t", label: "T-profile", icon: <IconT />, onClick: handleOpenTModal, disabled: !frameExists, active: frameExists && tProfiles.length > 0 },
    { key: "glassType", label: "Lloji i xhamit", icon: <IconGlassType />, onClick: () => setGlassModal(true), disabled: false },
  {
  key: "door",
  label: isDoor ? "Derë (Panel)" : "Derë",
  icon: <IconDoor />,
  onClick: handleDoorClick,
  disabled: !frameExists,
  active: frameExists && isDoor,
},

  ];

  // ===================== RENDER =====================
  return (
    <div style={{ width: "100%", padding: 12 }} className="pvc-editor">
      <style>{`
        .badge{
          display:inline-flex; align-items:center; gap:8px;
          padding:8px 10px; border-radius:999px;
          border:1px solid ${UI.border};
          background:#fff;
          font-size:12px;
          font-weight:800;
          color:${UI.ink};
          box-shadow: 0 10px 24px rgba(15,23,42,.04);
        }
        .toolBtn{
          display:inline-flex; align-items:center; gap:10px;
          padding:10px 12px;
          border-radius:14px;
          border:1px solid ${UI.border};
          background:#fff;
          cursor:pointer;
          font-size:12px;
          font-weight:800;
          user-select:none;
          box-shadow: 0 10px 24px rgba(15,23,42,.04);
        }
        .toolBtn:disabled{opacity:.55; cursor:not-allowed;}
        .toolBtnActive{background:rgba(219,234,254,.7); border-color: rgba(59,130,246,.6);}

        .layoutFlex{ display:flex; align-items:stretch; gap:0; margin-top:12px; }
        .leftPane{ flex:1; min-width: 460px; padding-right:12px; }
        .splitter{ width:10px; cursor:col-resize; user-select:none; position:relative; }
        .splitter:before{
          content:""; position:absolute; left:50%; top:12px; bottom:12px;
          width:2px; transform:translateX(-50%);
          background:${UI.border}; border-radius:2px; opacity:.85;
        }
        .rightPane{ width: var(--rightW); padding-left:12px; }

        @media (max-width: 980px){
          .layoutFlex{ display:block; }
          .leftPane{ min-width:0; padding-right:0; }
          .splitter{ display:none; }
          .rightPane{ width: 100% !important; padding-left:0; margin-top:12px; }
        }

        .ctxMenu{
          position:absolute;
          width: 240px;
          background:#fff;
          border:1px solid ${UI.border};
          border-radius:12px;
          box-shadow:0 18px 40px rgba(15,23,42,.18);
          padding:6px;
          z-index:99;
        }
        .ctxItem{
          width:100%;
          display:flex; align-items:center; gap:10px;
          padding:8px 10px;
          border-radius:10px;
          border:1px solid transparent;
          background:transparent;
          cursor:pointer;
          font-size:12px;
          font-weight:600;
          text-align:left;
          color:${UI.ink};
        }
        .ctxItem:hover{ background:#f8fafc; border-color:${UI.border}; }
        .ctxItem[disabled]{ opacity:.5; cursor:not-allowed; }

        .dimBlock{
          border:1px solid ${UI.border};
          border-radius:14px;
          padding:10px;
          background:#fff;
        }
      `}</style>

      {/* ================= TOP BAR ================= */}
      <div
        style={{
          background: "#fff",
          border: `1px solid ${UI.border}`,
          borderRadius: 18,
          boxShadow: UI.shadow,
          padding: 12,
          position: "sticky",
          top: 10,
          zIndex: 10,
        }}
      >


        {/* Row 2: Tools + Save button (moved DOWN) */}
        <div style={{ marginTop: 10, display: "flex", gap: 10, justifyContent: "space-between", alignItems: "center", flexWrap: "wrap" }}>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 8, alignItems: "center" }}>
            {tools.map((t) => (
              <button
                key={t.key}
                className={`toolBtn ${t.active ? "toolBtnActive" : ""}`}
                onClick={t.disabled ? undefined : t.onClick}
                disabled={t.disabled}
                title={t.label}
              >
                <span style={{ display: "grid", placeItems: "center" }}>{t.icon}</span>
                <span>{t.label}</span>
              </button>
            ))}
          </div>

          <Btn
            variant="success"
            onClick={handleSavePosition}
            style={{ borderRadius: 14, padding: "12px 14px", fontWeight: 1000 }}
            disabled={!frameExists}
            title={!frameExists ? "Së pari vendos kornizën" : "Ruaj pozicionin"}
          >
            {focusPosition ? "✔ Përditëso Pozicionin" : "✔ Ruaj Pozicionin"}
          </Btn>
        </div>

        <div style={{ marginTop: 6, fontSize: 11, color: UI.muted }}>
          Tip: Kliko me <b>mouse të djathtë</b> mbi editor për menunë e shpejtë.
        </div>
      </div>

      {/* ================= MAIN RESIZABLE LAYOUT ================= */}
      <div
        ref={layoutRef}
        className="layoutFlex"
        style={{ ["--rightW"]: `${rightW}px` }}
        onClick={() => ctx.open && closeCtx()}
      >
        {/* LEFT: CANVAS */}
        <div className="leftPane">
          <div
            style={{
              background: "#fff",
              border: `1px solid ${UI.border}`,
              borderRadius: 18,
              boxShadow: UI.shadow,
              padding: 12,
              overflow: "hidden",
            }}
          >
            <div
              ref={canvasWrapRef}
              style={{
                background: "#000",
                borderRadius: 14,
                overflow: "hidden",
                position: "relative",
                minHeight: 600,
                height: "calc(100vh - 220px)",
                maxHeight: 920,
              }}
              onContextMenu={(e) => {
                e.preventDefault();
                if (!ready) return;
                const bounds = e.currentTarget.getBoundingClientRect();
                const x = Math.max(10, Math.min(e.clientX - bounds.left, bounds.width - 250));
                const y = Math.max(10, Math.min(e.clientY - bounds.top, bounds.height - 280));
                setCtx({ open: true, x, y });
              }}
            >
              {ctx.open && (
                <div className="ctxMenu" style={{ left: ctx.x, top: ctx.y }} onClick={(e) => e.stopPropagation()}>
                  {tools.map((t) => (
                    <button
                      key={t.key}
                      className="ctxItem"
                      onClick={t.disabled ? undefined : () => (closeCtx(), t.onClick())}
                      disabled={t.disabled}
                      title={t.label}
                    >
                      <span style={{ display: "grid", placeItems: "center" }}>{t.icon}</span>
                      <span>{t.label}</span>
                    </button>
                  ))}
                </div>
              )}

              {dimOverlay.open && (
  <div
    style={{
      position: "absolute",
      left: dimOverlay.left,
      top: dimOverlay.top,
      zIndex: 120,
      background: "#0b1220",
      border: "1px solid rgba(255,255,255,.18)",
      borderRadius: 10,
      padding: 8,
      boxShadow: "0 18px 40px rgba(0,0,0,.35)",
    }}
    onClick={(e) => e.stopPropagation()}
  >
    <input
      ref={dimInputRef}
      type="number"
      value={dimOverlay.value}
      onChange={(e) => setDimOverlay((p) => ({ ...p, value: e.target.value }))}
      onKeyDown={(e) => {
        if (e.key === "Escape") setDimOverlay({ open: false, left: 0, top: 0, kind: "", value: "" });
        if (e.key === "Enter") {
          const v = Number(dimOverlay.value);
          if (Number.isNaN(v)) return;

          if (dimOverlay.kind === "frameW") setFrameW(clampInt(v, 300, 8000));
          if (dimOverlay.kind === "frameH") setFrameH(clampInt(v, 300, 8000));
          if (dimOverlay.kind === "rollHeight") setRollHeight(clampInt(v, 0, 1200));
          if (dimOverlay.kind === "base") setExtraBottomProfile(clampInt(v, 0, 2000));

          // kind: tV:<id> or tH:<id>
          if (dimOverlay.kind.startsWith("tV:")) {
            const id = Number(dimOverlay.kind.split(":")[1]);
            setTProfiles((prev) => prev.map((t) => (t.id === id ? { ...t, posMm: clampInt(v, 1, frameW - 1) } : t)));
          }
          if (dimOverlay.kind.startsWith("tH:")) {
            const id = Number(dimOverlay.kind.split(":")[1]);
            setTProfiles((prev) => prev.map((t) => (t.id === id ? { ...t, posMm: clampInt(v, 1, frameH - 1) } : t)));
          }

          setDimOverlay({ open: false, left: 0, top: 0, kind: "", value: "" });
        }
      }}
      style={{
        width: 120,
        background: "#0b1220",
        color: "#fff",
        border: "1px solid rgba(255,255,255,.22)",
        borderRadius: 8,
        padding: "8px 10px",
        outline: "none",
        fontWeight: 800,
      }}
    />
    <div style={{ fontSize: 11, color: "rgba(255,255,255,.7)", marginTop: 6 }}>Enter = ruaj, Esc = mbyll</div>
  </div>
)}

              {!ready ? (
                <div style={{ color: "#94a3b8", padding: 14, fontSize: 13 }}>Loading canvas…</div>
              ) : !frameExists ? (
                <svg width={editorW} height={editorH}>
                  <text x={editorW / 2} y={editorH / 2} fill="#64748b" fontSize="14" textAnchor="middle">
                    Kliko “Korniza” për të filluar.
                  </text>
                </svg>
              ) : (
                (() => {
                  const framePxW = frameW * scale;
                  const rollPx = hasRoll ? rollHeight * scale : 0;
                  const bodyPxH = frameH * scale;
                  const basePx = (extraBottomProfile || 0) * scale;
                  const fullHeightPx = rollPx + bodyPxH + basePx;

                  const originX = (editorW - framePxW) / 2;
                  const originY = (editorH - fullHeightPx) / 2;
                  const originBodyY = originY + rollPx;
                  const originBaseY = originBodyY + bodyPxH;

                  const innerOffset = 18;
                  const innerLeft = originX + innerOffset;
                  const innerRight = originX + framePxW - innerOffset;
                  const innerTop = originBodyY + innerOffset;
                  const innerBottom = originBodyY + bodyPxH - innerOffset;

                  const leftOffsetPx = irregular ? topLeftOffset * scale : 0;
                  const rightOffsetPx = irregular ? topRightOffset * scale : 0;

                  const topLineAtX = (x) => {
                    if (!irregular || innerRight === innerLeft) return innerTop;
                    const t = (x - innerLeft) / (innerRight - innerLeft);
                    return innerTop + leftOffsetPx + t * (rightOffsetPx - leftOffsetPx);
                  };

                  const tThickness = 8;
                  const tVert = [];
                  const tHoriz = [];

                  let vBounds = [innerLeft, innerRight];
                  let hBounds = [innerTop, innerBottom];

                  tProfiles.forEach((t) => {
  if (t.orientation === "horizontal") {
    // horizontal T inside BODY only: posMm is relative to BODY top
    let cy = originBodyY + Number(t.posMm || 0) * scale;

    const minCy = innerTop + tThickness;
    const maxCy = innerBottom - tThickness;
    cy = Math.max(minCy, Math.min(maxCy, cy));

    tHoriz.push({ id: t.id, cy });
    hBounds.push(cy);
  } else {
    // vertical T across BODY: posMm is relative to frame left
    let cx = originX + Number(t.posMm || 0) * scale;

    const minCx = innerLeft + tThickness;
    const maxCx = innerRight - tThickness;
    cx = Math.max(minCx, Math.min(maxCx, cx));

    tVert.push({ id: t.id, cx });
    vBounds.push(cx);
  }
});


                  vBounds.sort((a, b) => a - b);
                  hBounds.sort((a, b) => a - b);

                  const cols = vBounds.length - 1;
                  const rows = hBounds.length - 1;

                  const safeCol = Math.max(0, Math.min(activeSeg.col, cols - 1));
                  const safeRow = Math.max(0, Math.min(activeSeg.row, rows - 1));

                  return (
                    <svg width={editorW} height={editorH} style={{ background: "transparent" }}>
                      <text x={originX + framePxW / 2} y={originY - 24} fill="#fef08a" fontSize="12" textAnchor="middle">
                        PAMJA NË MRENDI
                      </text>

                      <rect x={originX} y={originY} width={framePxW} height={fullHeightPx} stroke="#ffffff" strokeWidth={1} fill="transparent" />

                      {hasRoll && <rect x={originX} y={originY} width={framePxW} height={rollPx} fill="rgba(148,163,184,.45)" stroke="none" />}

{basePx > 0 && (
  isDoor ? (
    <g>
      {/* threshold base */}
      <rect
        x={originX}
        y={originBaseY}
        width={framePxW}
        height={basePx}
        fill="rgba(253,224,71,.22)"          // yellow-ish hint
        stroke="rgba(253,224,71,.65)"
        strokeWidth={1}
      />
      {/* hatch lines for "metal threshold" look */}
      {Array.from({ length: Math.floor(framePxW / 14) }).map((_, i) => {
        const xx = originX + i * 14;
        return (
          <line
            key={`th-${i}`}
            x1={xx}
            y1={originBaseY + 2}
            x2={xx + 10}
            y2={originBaseY + basePx - 2}
            stroke="rgba(253,224,71,.35)"
            strokeWidth={1}
          />
        );
      })}
    </g>
  ) : (
    <rect
      x={originX}
      y={originBaseY}
      width={framePxW}
      height={basePx}
      fill="rgba(148,163,184,.35)"
      stroke="none"
    />
  )
)}

                      <rect x={innerLeft} y={innerTop} width={innerRight - innerLeft} height={innerBottom - innerTop} stroke="#ffffff" strokeWidth={1} fill="transparent" />
{/* DOOR PANEL IMAGE (pure uploaded PNG) */}
{/* DOOR PANEL IMAGE (debug + safe url + fallback) */}
{isDoor && selectedDoorPanel && (() => {
  const raw =
    selectedDoorPanel.imageUrl ||
    selectedDoorPanel.image_url ||
    selectedDoorPanel.url ||
    "";

  if (!raw) {
    return (
      <text x={innerLeft + 18} y={innerTop + 30} fill="#fca5a5" fontSize="12">
        Panel image missing (imageUrl / image_url is empty)
      </text>
    );
  }

  // IMPORTANT: ensure correct base url (no double slashes issues)
  const API_BASE = (import.meta.env.VITE_API_URL || "http://127.0.0.1:8010").replace(/\/+$/, "");
  const path = raw.startsWith("http") ? raw : `${API_BASE}/${String(raw).replace(/^\/+/, "")}`;
  const panelSrc = encodeURI(path);

  const doorInset = 26;
  const pxW = innerRight - innerLeft;
  const pxH = innerBottom - innerTop;

  const x = innerLeft + doorInset;
  const y = innerTop + doorInset;
  const w = Math.max(0, pxW - doorInset * 2);
  const h = Math.max(0, pxH - doorInset * 2);

  const clipId = `doorPanelClip-${offer?.id || "x"}-${doorPanelId || "p"}`;

  return (
    <>
      <defs>
        <clipPath id={clipId}>
          <rect x={x} y={y} width={w} height={h} rx={2} />
        </clipPath>
      </defs>

      {/* debug: show the URL you're trying to load */}
      <text x={innerLeft + 10} y={innerTop - 8} fill="#fef08a" fontSize="10">
        {panelSrc}
      </text>

      {doorImgOk ? (
        <image
          href={panelSrc}
          x={x}
          y={y}
          width={w}
          height={h}
          clipPath={`url(#${clipId})`}
          preserveAspectRatio="xMidYMid meet"
          onLoad={() => {
            setDoorImgOk(true);
            setDoorImgErr("");
          }}
          onError={() => {
            setDoorImgOk(false);
            setDoorImgErr("SVG <image> failed to load. Check URL / mixed content / server headers.");
          }}
        />
      ) : (
        <>
          <rect
            x={x}
            y={y}
            width={w}
            height={h}
            fill="rgba(255,255,255,.06)"
            stroke="rgba(255,255,255,.35)"
            strokeWidth={1}
            rx={6}
          />
          <text x={x + 10} y={y + 22} fill="#fca5a5" fontSize="12">
            Door image NOT loaded
          </text>
          <text x={x + 10} y={y + 42} fill="#fef08a" fontSize="10">
            {doorImgErr}
          </text>
        </>
      )}

      <rect
        x={x}
        y={y}
        width={w}
        height={h}
        fill="transparent"
        stroke="rgba(255,255,255,.25)"
        strokeWidth={1}
      />
    </>
  );
})()}




{/* Segments (skip when Door) */}
{!isDoor &&
  Array.from({ length: rows }).map((_, row) =>
    Array.from({ length: cols }).map((__, col) => {
      // ✅ KEEP YOUR EXISTING SEGMENT CODE HERE (no "...")
      const xl = vBounds[col];
      const xr = vBounds[col + 1];
      const yt = hBounds[row];
      const yb = hBounds[row + 1];
      const segKey = `${col}-${row}`;
      const segWidth = xr - xl;
      const segHeight = yb - yt;

      const segSashes = sashes.filter((s) => s.segmentKey === segKey).sort((a, b) => a.id - b.id);
      const count = segSashes.length;
      const isStaticGlass = segmentsGlass[segKey] && count === 0;

      let segmentBlocked = false;
      if (irregular) {
        const topAtLeft = topLineAtX(xl);
        const topAtRight = topLineAtX(xr);
        const minTop = Math.min(topAtLeft, topAtRight);
        if (yb <= minTop) segmentBlocked = true;
      }

      const sashW = count > 0 ? segWidth / count : 0;
      const sashH = segHeight;

      return (
        <g key={segKey}>
          {isStaticGlass && !segmentBlocked && (
            <rect
              x={xl}
              y={yt}
              width={segWidth}
              height={segHeight}
              fill="rgba(96,165,250,0.25)"
              stroke="#e5e7eb"
              strokeWidth={1}
            />
          )}

          {count > 0 &&
            !segmentBlocked &&
            segSashes.map((sash, index) => {
              const sx = xl + index * sashW;
              const sy = yt;

              const handleDirRight =
                sash.opening === "turn-right" ||
                sash.opening === "turn-right+tilt-top" ||
                sash.opening === "tilt-top";

              const isTiltCenter = sash.opening === "tilt-top-center";

              let handleX = sx + sashW - 8;
              let handleY = sy + sashH / 2 - 16;
              if (handleDirRight) handleX = sx + 4;
              if (isTiltCenter) {
                handleX = sx + sashW / 2 - 6;
                handleY = sy - 4;
              }

              return (
                <g
                  key={sash.id}
                  onClick={() => {
                    setActiveSeg({ col, row });
                    setSelectedSashId(sash.id);
                  }}
                  style={{ cursor: "pointer" }}
                >
                  <rect
                    x={sx}
                    y={sy}
                    width={sashW}
                    height={sashH}
                    stroke={sash.id === selectedSashId ? UI.orange : "#ffffff"}
                    strokeWidth={sash.id === selectedSashId ? 2 : 1}
                    fill={sash.hasGlass ? "rgba(191,219,254,.4)" : "transparent"}
                  />

                  {renderOpeningLocal(sash.opening, sx, sy, sashW, sashH)}

                  <rect
                    x={handleX}
                    y={handleY}
                    width={isTiltCenter ? 12 : 4}
                    height={isTiltCenter ? 12 : 32}
                    fill="#ffffff"
                    rx={1}
                  />
                </g>
              );
            })}

          {/* Segment click */}
          <rect
            x={xl}
            y={yt}
            width={segWidth}
            height={segHeight}
            fill="transparent"
            onClick={() => {
              setActiveSeg({ col, row });
              setSelectedSashId(null);
            }}
            style={{ cursor: "pointer" }}
          />
        </g>
      );
    })
  )}



                      {irregular && (
                        <path
                          d={`M ${innerLeft} ${innerTop + leftOffsetPx} L ${innerRight} ${innerTop + rightOffsetPx} L ${innerRight} ${innerBottom} L ${innerLeft} ${innerBottom} Z`}
                          fill="none"
                          stroke="#38bdf8"
                          strokeWidth={1.5}
                        />
                      )}

                      {/* Dims */}
{/* Dims (RIGHT) */}
{(() => {
  // --- style constants
  const DIM = "#fef08a";
  const GAP = 3;          // gap where tick meets dim line
  const EXT_GAP = 6;      // gap near object & near dim line (extension line)
  const TICK = 9;

  // rulers x positions
  const xSeg = originX + framePxW + 40; // near
  const xTot = xSeg + 26;               // outside

  // tick with a GAP at the dim line (does not cross the line)
  const tickHGap = (x, y) => (
    <g>
      <line x1={x - 8} y1={y - TICK} x2={x - 8} y2={y - GAP} stroke={DIM} strokeWidth={1} opacity={0.9} />
      <line x1={x - 8} y1={y + GAP} x2={x - 8} y2={y + TICK} stroke={DIM} strokeWidth={1} opacity={0.9} />
      <line x1={x + 8} y1={y - TICK} x2={x + 8} y2={y - GAP} stroke={DIM} strokeWidth={1} opacity={0.9} />
      <line x1={x + 8} y1={y + GAP} x2={x + 8} y2={y + TICK} stroke={DIM} strokeWidth={1} opacity={0.9} />
    </g>
  );

  // extension line from object edge to ruler, with gaps on both ends
  const extLineToRuler = (y) => {
    const xObj = originX + framePxW;
    return (
      <line
        x1={xObj + EXT_GAP}
        y1={y}
        x2={xSeg - EXT_GAP}
        y2={y}
        stroke={DIM}
        strokeWidth={1}
        opacity={0.45}
      />
    );
  };

  // main segments (roll/body/base)
  const segments = [];
  if (hasRoll && rollPx > 0) segments.push({ y1: originY,      y2: originY + rollPx,        label: rollHeight,          kind: "rollHeight" });
  segments.push({              y1: originBodyY, y2: originBodyY + bodyPxH,      label: frameH,              kind: "frameH" });
  if (basePx > 0) segments.push({ y1: originBaseY, y2: originBaseY + basePx,   label: extraBottomProfile,  kind: "base" });

  // detailed BODY row segments when horizontal T exists
  const bodyYs = [originBodyY, ...tHoriz.map((t) => t.cy).sort((a,b)=>a-b), originBodyY + bodyPxH];

  // total label placement (keep inside viewport)
  const totalLabelYDefault = originY + fullHeightPx + 26;
  const totalLabelY = totalLabelYDefault > editorH - 10 ? originY + fullHeightPx - 10 : totalLabelYDefault;

  return (
    <g>
      {/* extension lines (from object to near ruler) */}
      {tickHGap(xSeg, originY)}
      {tickHGap(xSeg, originY + fullHeightPx)}
      {extLineToRuler(originY)}
      {extLineToRuler(originY + fullHeightPx)}

      {/* NEAR (segments) ruler */}
      <line x1={xSeg} y1={originY} x2={xSeg} y2={originY + fullHeightPx} stroke={DIM} strokeWidth={1} opacity={0.75} />

      {segments.map((s, idx) => (
        <g key={`seg-${idx}`}>
          {tickHGap(xSeg, s.y1)}
          {tickHGap(xSeg, s.y2)}
          {extLineToRuler(s.y1)}
          {extLineToRuler(s.y2)}

          <text
            x={xSeg + 14}
            y={(s.y1 + s.y2) / 2 + 4}
            fill={DIM}
            fontSize="11"
            style={{ cursor: "pointer" }}
            onClick={() =>
              setDimOverlay({
                open: true,
                left: xSeg + 6,
                top: (s.y1 + s.y2) / 2 - 18,
                kind: s.kind,
                value: String(s.label || 0),
              })
            }
          >
            {s.label || 0}
          </text>
        </g>
      ))}

      {/* BODY row dims (only if horizontal T exists and actually creates >1 row) */}
      {bodyYs.length > 2 &&
        bodyYs.slice(0, -1).map((yA, i) => {
          const yB = bodyYs[i + 1];
          const segMm = Math.round((yB - yA) / scale);
          const cy = (yA + yB) / 2;

          return (
            <g key={`bodyRow-${i}`} opacity={0.9}>
              {tickHGap(xSeg, yA)}
              {tickHGap(xSeg, yB)}
              {/* subtle label for each row */}
              <text x={xSeg - 10} y={cy + 4} fill={DIM} fontSize="10" textAnchor="end" opacity={0.85}>
                {segMm}
              </text>
            </g>
          );
        })}

      {/* OUTSIDE (total) ruler */}
      <line x1={xTot} y1={originY} x2={xTot} y2={originY + fullHeightPx} stroke={DIM} strokeWidth={1} />
      {tickHGap(xTot, originY)}
      {tickHGap(xTot, originY + fullHeightPx)}

      {/* TOTAL label */}
      <text x={xTot} y={totalLabelY} fill={DIM} fontSize="12" textAnchor="middle">
        {fullHeightMm} mm
      </text>
    </g>
  );
})()}


{(() => {

const dimLabel = ({ x, y, text, fontSize = 11, anchor = "middle", padX = 8, padY = 5, onClick }) => {
  const s = String(text ?? "");
  const w = Math.max(22, s.length * (fontSize * 0.62) + padX * 2);
  const h = fontSize + padY * 2;

  let rx = x;
  if (anchor === "start") rx = x;
  if (anchor === "end") rx = x - w;
  if (anchor === "middle") rx = x - w / 2;

  const ry = y - h + 3;

  return (
    <g onClick={onClick} style={{ cursor: onClick ? "pointer" : "default" }}>
      {/* plate that hides the dimension line */}
      <rect x={rx} y={ry} width={w} height={h} rx={7} fill="rgba(0,0,0,.90)" />
      <text x={x} y={y} fill={DIM} fontSize={fontSize} textAnchor={anchor} fontWeight={800}>
        {s}
      </text>
    </g>
  );
};




  const DIM = "#fef08a";
  const GAP = 3;       // tick gap at dim line
  const EXT_GAP = 6;   // gaps for extension lines
  const TICK = 9;

  // how much space we need below the object for both rulers + labels
  const NEED = 120;

  const baseY = originY + fullHeightPx;
  const belowSpace = editorH - baseY;

  // default positions
  let ySeg = baseY + 48;
  let yTot = baseY + 92;

  // shift up if we don't have enough space
  if (belowSpace < NEED) {
    const maxTot = editorH - 30;
    const overflow = yTot - maxTot;
    if (overflow > 0) {
      ySeg -= overflow;
      yTot -= overflow;
    }
    // keep at least a small gap under the object
    const minYSeg = baseY + 18;
    if (ySeg < minYSeg) {
      const push = minYSeg - ySeg;
      ySeg += push;
      yTot += push;
    }
  }

  // collect vertical split positions (tVert) to compute width segments
  const tXs = tVert.map((t) => t.cx).sort((a, b) => a - b);
  const bounds = [originX, ...tXs, originX + framePxW];

  const tickVGap = (x, y) => (
    <g>
      <line x1={x} y1={y - TICK} x2={x} y2={y - GAP} stroke={DIM} strokeWidth={1} opacity={0.9} />
      <line x1={x} y1={y + GAP} x2={x} y2={y + TICK} stroke={DIM} strokeWidth={1} opacity={0.9} />
    </g>
  );

  // extension lines from object bottom to ruler, with gaps
  const extLineDown = (x, yLine) => (
    <line
      x1={x}
      y1={baseY + EXT_GAP}
      x2={x}
      y2={yLine - EXT_GAP}
      stroke={DIM}
      strokeWidth={1}
      opacity={0.45}
    />
  );

  // total label placement (inside if needed)
  const totalLabelBelow = yTot + 24;
  const totalLabelY = totalLabelBelow > editorH - 8 ? yTot - 12 : totalLabelBelow;

  return (
    <g>
      {/* SEGMENTS ruler (TOP) */}
      <line x1={bounds[0]} y1={ySeg} x2={bounds[bounds.length - 1]} y2={ySeg} stroke={DIM} strokeWidth={1} opacity={0.9} />

      {bounds.map((bx, i) => (
        <g key={`seg-tick-${i}`}>
          {tickVGap(bx, ySeg)}
          {extLineDown(bx, ySeg)}
        </g>
      ))}

      {/* segment labels */}
      {bounds.slice(0, -1).map((bx, i) => {
        const nx = bounds[i + 1];
        const segMm = Math.round((nx - bx) / scale);
        const cx = (bx + nx) / 2;

        return (
          <text
            key={`seg-mm-${i}`}
            x={cx}
            y={ySeg + 22}
            fill={DIM}
            fontSize="11"
            textAnchor="middle"
            opacity={0.95}
          >
            {segMm}
          </text>
        );
      })}

      {/* TOTAL ruler (BOTTOM) */}
      <line x1={originX} y1={yTot} x2={originX + framePxW} y2={yTot} stroke={DIM} strokeWidth={1} />
      {tickVGap(originX, yTot)}
      {tickVGap(originX + framePxW, yTot)}
      {extLineDown(originX, yTot)}
      {extLineDown(originX + framePxW, yTot)}

      {/* total label */}
      <text
        x={originX + framePxW / 2}
        y={totalLabelY}
        fill={DIM}
        fontSize="12"
        textAnchor="middle"
        style={{ cursor: "pointer" }}
        onClick={() => {
          setDimOverlay({
            open: true,
            left: originX + framePxW / 2 - 60,
            top: yTot + 4,
            kind: "frameW",
            value: String(frameW),
          });
        }}
      >
        {frameW} mm
      </text>
    </g>
  );
})()}




                      {/* Active segment highlight */}
                      {cols > 0 &&
                        rows > 0 &&
                        (() => {
                          const xl = vBounds[safeCol];
                          const xr = vBounds[safeCol + 1];
                          const yt = hBounds[safeRow];
                          const yb = hBounds[safeRow + 1];
                          return <rect x={xl} y={yt} width={xr - xl} height={yb - yt} fill="rgba(148,163,184,.12)" stroke="rgba(248,250,252,.25)" strokeWidth={1} />;
                        })()}

                      {/* Segments */}
                      
                    

                      {/* T profiles */}
                      {tVert.map((t) => (
  <g
    key={`tv-${t.id}`}
    style={{ cursor: "col-resize" }}
    onPointerDown={(e) => {
      e.preventDefault();
      e.stopPropagation();
      e.currentTarget.setPointerCapture?.(e.pointerId);

      // convert current cx -> posMm (relative to originX)
      const currentPosMm = Math.round((t.cx - originX) / scale);

      tDragRef.current = {
        dragging: true,
        id: t.id,
        orientation: "vertical",
        startX: e.clientX,
        startY: e.clientY,
        startPosMm: currentPosMm,
      };
    }}
  >
    {drawPVCProfileVertical(t.cx, innerTop, innerBottom, 18, 7)}
  </g>
))}
{tHoriz.map((t) => (
  <g
    key={`th-${t.id}`}
    style={{ cursor: "row-resize" }}
    onPointerDown={(e) => {
      e.preventDefault();
      e.stopPropagation();
      e.currentTarget.setPointerCapture?.(e.pointerId);

      // posMm is relative to originBodyY
      const currentPosMm = Math.round((t.cy - originBodyY) / scale);

      tDragRef.current = {
        dragging: true,
        id: t.id,
        orientation: "horizontal",
        startX: e.clientX,
        startY: e.clientY,
        startPosMm: currentPosMm,
      };
    }}
  >
    {drawPVCProfileHorizontal(t.cy, innerLeft, innerRight, 18, 7)}
  </g>
))}

                    </svg>
                  );
                })()
              )}
            </div>
          </div>
        </div>

        {/* SPLITTER (draggable) */}
        <div
          className="splitter"
          onMouseDown={(e) => {
            e.preventDefault();
            dragRef.current.dragging = true;
          }}
          title="Tërhiq për ta ndryshuar gjerësinë"
        />

        {/* RIGHT: DETAILS (NO SAVE BUTTON HERE) */}
        <div className="rightPane" style={{ ["--rightW"]: `${rightW}px` }}>
          <div
            style={{
              background: "#fff",
              border: `1px solid ${UI.border}`,
              borderRadius: 18,
              boxShadow: UI.shadow,
              padding: 14,
              position: "sticky",
              top: WORKSPACE_TOP,
              overflow: "auto",
              maxHeight: "calc(100vh - 110px)",
            }}
          >
            {/* OPTIONS */}
            <div style={{ display: "grid", gap: 10 }}>
              <div style={{ fontSize: 12, color: UI.muted, fontWeight: 900 }}>Opsionet</div>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
                <Btn onClick={handlePrintOffer} disabled={!frameExists}>📄 Oferta</Btn>
                <Btn onClick={handlePrintSketch} disabled={!frameExists}>🖼️ Skica</Btn>
                <Btn onClick={handlePrintCutting} disabled={!frameExists}>✂ Prerjet</Btn>
                <Btn onClick={handlePrintInvoice} disabled={!frameExists}>🧾 Faturë</Btn>
              </div>

              <div style={{ borderTop: `1px solid ${UI.border}`, marginTop: 2 }} />

              {/* OFFER DETAILS (only basics) */}
              <div>
                <div style={{ fontSize: 12, color: UI.muted }}>Detajet</div>
                <div style={{ fontWeight: 950, marginTop: 2 }}>{offer?.name || "—"}</div>

                <div style={{ fontSize: 12, color: UI.muted, marginTop: 6 }}>Marzha: {margin}%</div>
                <div style={{ fontSize: 12, color: UI.muted }}>
                  Profili: {profile?.name || "—"} — € {money(profile?.pricePerM || 0)}/m
                </div>
                <div style={{ fontSize: 12, color: UI.muted }}>
                  Armatura: {iron?.name || "—"} — € {money(iron?.pricePerM || 0)}/m
                </div>
                <div style={{ fontSize: 12, color: UI.muted }}>
                  Xhami: {currentGlass?.name || "—"} — € {money(currentGlass?.pricePerM2 || 0)}/m²
                </div>

                
              </div>

              <div style={{ borderTop: `1px solid ${UI.border}` }} />

              {/* ACTIVE POSITION (inline live edit) */}
              <div>
                <div style={{ fontSize: 12, color: UI.muted }}>Pozicioni aktiv</div>

                {!frameExists ? (
                  <div style={{ fontSize: 12, color: UI.muted, marginTop: 6 }}>Vendos kornizën për të filluar.</div>
                ) : (
                  <div className="dimBlock" style={{ marginTop: 8 }}>
                    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10 }}>
                      <div style={{ fontWeight: 950, fontSize: 13 }}>
                        {frameW} × {fullHeightMm} mm {isDoor ? "(Derë)" : "(Dritare)"}
                      </div>

                      <button
                        onClick={() => setDimEditOpen((p) => !p)}
                        style={{
                          border: `1px solid ${UI.border}`,
                          background: "#fff",
                          borderRadius: 12,
                          padding: "7px 10px",
                          fontSize: 12,
                          cursor: "pointer",
                          fontWeight: 800,
                        }}
                        title="Edito dimensionet (LIVE)"
                      >
                        {dimEditOpen ? "Mbyll" : "Edito"}
                      </button>
                    </div>

                    {dimEditOpen && (
                      <div style={{ display: "grid", gap: 10, marginTop: 10 }}>
                        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
                          <div>
                            <div style={{ fontSize: 11, color: UI.muted, marginBottom: 4 }}>Gjerësia (mm)</div>
                            <TextInput type="number" value={frameW} onChange={(e) => setFrameW(clampInt(e.target.value, 300, 8000))} />
                          </div>
                          <div>
                            <div style={{ fontSize: 11, color: UI.muted, marginBottom: 4 }}>Lartësia (mm)</div>
                            <TextInput type="number" value={frameH} onChange={(e) => setFrameH(clampInt(e.target.value, 300, 8000))} />
                          </div>
                        </div>

                        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
                          <div>
                            <div style={{ fontSize: 11, color: UI.muted, marginBottom: 4 }}>Profil poshtë (mm)</div>
                            <TextInput type="number" value={extraBottomProfile} onChange={(e) => setExtraBottomProfile(clampInt(e.target.value, 0, 2000))} />
                          </div>
                          <div>
                            <div style={{ fontSize: 11, color: UI.muted, marginBottom: 4 }}>Roletë (mm)</div>
                            <TextInput
                              type="number"
                              value={rollHeight}
                              onChange={(e) => setRollHeight(clampInt(e.target.value, 0, 1200))}
                              disabled={!hasRoll}
                              style={{ opacity: hasRoll ? 1 : 0.6 }}
                            />
                          </div>
                        </div>

                        <div style={{ display: "flex", gap: 14, flexWrap: "wrap" }}>
                          <label style={{ fontSize: 12, display: "flex", alignItems: "center", gap: 8 }}>
                            <input type="checkbox" checked={hasRoll} onChange={(e) => setHasRoll(e.target.checked)} />
                            Ka roletë
                          </label>

                          <label style={{ fontSize: 12, display: "flex", alignItems: "center", gap: 8 }}>
                            <input type="checkbox" checked={isDoor} onChange={(e) => setIsDoor(e.target.checked)} />
                            Është derë
                          </label>
                        </div>

                        {shapeType === "sloped" && (
                          <div style={{ fontSize: 12, color: UI.muted }}>
                            Irreg: majtas {topLeftOffset || 0} / djathtas {topRightOffset || 0} mm (≈ {irregularAngleDeg}°)
                          </div>
                        )}
                      </div>
                    )}

                    <div style={{ marginTop: 10, fontSize: 12, color: UI.muted }}>
                      Perimetri: {perimeterM.toFixed(2)} m • Xham: {glassArea.toFixed(3)} m²
                    </div>
                    {isDoor && (
  <div style={{ marginTop: 12 }}>
    <div style={{ fontSize: 12, fontWeight: 900 }}>Paneli i derës</div>

    {selectedDoorPanel?.imageUrl ? (
      <img
        src={selectedDoorPanel.imageUrl}
        alt={selectedDoorPanel?.name || "Panel"}
        style={{
          width: "100%",
          maxHeight: 220,
          objectFit: "contain",
          display: "block",
          marginTop: 8,
          background: "transparent",
        }}
      />
    ) : (
      <div style={{ fontSize: 12, color: UI.muted, marginTop: 6 }}>
        Nuk ka imageUrl (kontrollo API response: imageUrl / image_url).
      </div>
    )}

    <div style={{ display: "flex", gap: 8, marginTop: 8 }}>
      <Btn onClick={() => setDoorModal(true)}>Ndrysho panelin</Btn>
      <Btn variant="danger" onClick={handleRemoveDoor}>Hiq derën</Btn>
    </div>
  </div>
)}

                  </div>
                )}
              </div>

              <div style={{ borderTop: `1px solid ${UI.border}` }} />

              {/* COSTS (only for active position) */}
              <div style={{ display: "grid", gap: 8 }}>
                <Row label="Profil" value={`€ ${money(profileCost)}`} />
                <Row label="Armaturë" value={`€ ${money(ironCost)}`} />
                <Row label="Xham" value={`€ ${money(glassCost)}`} />
                {isDoor && (
  <Row label="Panel (extra)" value={`€ ${money(doorPanelCost)}`} />
)}
                <div style={{ height: 1, background: UI.border, margin: "6px 0" }} />
                <Row label="Nëntotali" value={`€ ${money(subtotal)}`} strong />
                <Row label={`+ Marzha (${margin}%)`} value={`€ ${money(profit)}`} />
                <Row label="Totali" value={`€ ${money(total)}`} strong big />
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* ================= MODALS ================= */}
      <Modal open={frameModal} title="Dimensionet e kornizës" onClose={() => setFrameModal(false)} footer={null}>
        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
          <Field label="Gjerësia (mm)">
            <TextInput type="number" value={frameW} onChange={(e) => setFrameW(clampInt(e.target.value, 300, 8000))} />
          </Field>
          <Field label="Lartësia (mm)">
            <TextInput type="number" value={frameH} onChange={(e) => setFrameH(clampInt(e.target.value, 300, 8000))} />
          </Field>
          <Field label="Profil poshtë shtesë (mm)">
            <TextInput type="number" value={extraBottomProfile} onChange={(e) => setExtraBottomProfile(clampInt(e.target.value, 0, 2000))} />
          </Field>

          <label style={{ fontSize: 12, display: "flex", alignItems: "center", gap: 8 }}>
            <input type="checkbox" checked={hasRoll} onChange={(e) => setHasRoll(e.target.checked)} />
            Ka roletë
          </label>

          <Field label="Lartësia e roletës (mm)">
            <TextInput
              type="number"
              value={rollHeight}
              onChange={(e) => setRollHeight(clampInt(e.target.value, 0, 1200))}
              disabled={!hasRoll}
              style={{ opacity: hasRoll ? 1 : 0.6 }}
            />
          </Field>

          <label style={{ fontSize: 12, display: "flex", alignItems: "center", gap: 8 }}>
            <input type="checkbox" checked={isDoor} onChange={(e) => setIsDoor(e.target.checked)} />
            Është derë (prag)
          </label>


          {isDoor && (
  <div style={{ marginTop: 10 }}>
    <div style={{ fontSize: 12, fontWeight: 900 }}>Paneli i derës</div>

    {selectedDoorPanel ? (
      <div style={{ marginTop: 8 }}>
        <div style={{ fontSize: 12, color: UI.muted }}>
          {selectedDoorPanel.name} — Extra € {money(selectedDoorPanel.price || 0)}
        </div>

        {!!selectedDoorPanel.imageUrl && (
          <img
            src={selectedDoorPanel.imageUrl}
            alt={selectedDoorPanel.name}
            style={{
              width: "100%",
              maxHeight: 220,
              objectFit: "contain",
              display: "block",
              marginTop: 8,
              background: "transparent",
            }}
          />
        )}

        <div style={{ marginTop: 8, display: "flex", gap: 8 }}>
          <Btn onClick={() => setDoorModal(true)}>Ndrysho panelin</Btn>
          <Btn variant="danger" onClick={handleRemoveDoor}>Hiq derën</Btn>
        </div>
      </div>
    ) : (
      <div style={{ marginTop: 8 }}>
        <div style={{ fontSize: 12, color: UI.muted }}>Nuk është zgjedhur panel.</div>
        <Btn style={{ marginTop: 8 }} onClick={() => setDoorModal(true)}>
          Zgjedh panel
        </Btn>
      </div>
    )}
  </div>
)}


          <div style={{ display: "flex", gap: 10, justifyContent: "flex-end", marginTop: 6 }}>
            <Btn onClick={() => setFrameModal(false)}>Anulo</Btn>
            <Btn variant="primary" onClick={handleSaveFrame}>
              OK
            </Btn>
          </div>
        </div>
      </Modal>

      <Modal open={shapeModal} title="Forma e dritares" onClose={() => setShapeModal(false)} footer={null}>
        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
          <Field label="Lloji i formës">
            <Select value={shapeType} onChange={(e) => setShapeType(e.target.value)}>
              <option value="rect">Drejtkëndësh (normal)</option>
              <option value="sloped">Irregulare – sipër e pjerrët</option>
            </Select>
          </Field>

          {shapeType === "sloped" && (
            <>
              <Field label="Offset sipër majtas (mm)">
                <TextInput type="number" value={topLeftOffset} onChange={(e) => setTopLeftOffset(clampInt(e.target.value, 0, 2000))} />
              </Field>
              <Field label="Offset sipër djathtas (mm)">
                <TextInput type="number" value={topRightOffset} onChange={(e) => setTopRightOffset(clampInt(e.target.value, 0, 2000))} />
              </Field>
              <div style={{ fontSize: 11, color: UI.muted, lineHeight: 1.5 }}>
                • Këndi afërsisht: <b>{irregularAngleDeg}°</b>
              </div>
            </>
          )}

          <div style={{ display: "flex", gap: 10, justifyContent: "flex-end", marginTop: 6 }}>
            <Btn onClick={() => setShapeModal(false)}>Mbyll</Btn>
            <Btn variant="primary" onClick={() => setShapeModal(false)}>
              OK
            </Btn>
          </div>
        </div>
      </Modal>

      <Modal open={panelModal} title="Lloji i hapjes" onClose={() => setPanelModal(false)} footer={null}>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
          {[
            ["fixed", "Fiks"],
            ["turn-left", "Hapje majtas"],
            ["turn-right", "Hapje djathtas"],
            ["tilt-top", "Anim sipër"],
            ["tilt-top-center", "Anim sipër (qendër)"],
            ["turn-right+tilt-top", "Hapje+Anim djathtas"],
            ["slide-left", "Rrëshqitëse majtas (Shinë)"],
["slide-right", "Rrëshqitëse djathtas (Shinë)"],
["slide-both", "Rrëshqitëse dy-krahësh"],
          ].map(([val, label]) => (
            <button
              key={val}
              onClick={() => setPanelOpening(val)}
              style={{
                padding: "8px 10px",
                border: panelOpening === val ? `2px solid ${UI.primary}` : `1px solid ${UI.border}`,
                borderRadius: 12,
                fontSize: 12,
                fontWeight: 700,
                background: "#fff",
                cursor: "pointer",
              }}
            >
              {label}
            </button>
          ))}
        </div>

        <div style={{ display: "flex", justifyContent: "flex-end", gap: 10, marginTop: 14 }}>
          <Btn onClick={() => setPanelModal(false)}>Anulo</Btn>
          <Btn variant="primary" onClick={handleConfirmPanel}>
            OK
          </Btn>
        </div>
      </Modal>

      <Modal open={tModal} title="T-profile" onClose={() => setTModal(false)} footer={null}>
        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
          <Field label="Orientimi">
            <Select value={tOrientation} onChange={(e) => setTOrientation(e.target.value)}>
              <option value="vertical">Vertikale</option>
              <option value="horizontal">Horizontale</option>
            </Select>
          </Field>

          <Field label="Pozicioni">
            <Select value={tSide} onChange={(e) => setTSide(e.target.value)}>
              {tOrientation === "vertical" ? (
                <>
                  <option value="left">Majtas (distanca nga majtas)</option>
                  <option value="middle">Mes</option>
                  <option value="right">Djathtas (distanca nga djathtas)</option>
                </>
              ) : (
                <>
                  <option value="top">Sipër (distanca nga sipër)</option>
                  <option value="middle">Mes</option>
                  <option value="bottom">Poshtë (distanca nga poshtë)</option>
                </>
              )}
            </Select>
          </Field>

          <Field label="Distanca (mm)" hint={tSide === "middle" ? 'Për "mes" s’duhet mm' : ""}>
            <TextInput
              type="number"
              value={tOffsetMm}
              onChange={(e) => setTOffsetMm(clampInt(e.target.value, 0, 8000))}
              disabled={tSide === "middle"}
              style={{ opacity: tSide === "middle" ? 0.6 : 1 }}
            />
          </Field>

          <div style={{ display: "flex", gap: 10, justifyContent: "space-between", marginTop: 6 }}>
            <Btn variant="danger" onClick={handleClearTs} disabled={tProfiles.length === 0}>
              Pastro
            </Btn>
            <Btn variant="primary" onClick={handleAddTProfile}>
              + Shto T
            </Btn>
          </div>
        </div>
      </Modal>

      <Modal open={glassModal} title="Lloji i xhamit" onClose={() => setGlassModal(false)} footer={null}>
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          {(materials?.glassTypes || []).map((g) => (
            <label
              key={g.id}
              style={{
                fontSize: 12,
                display: "flex",
                alignItems: "center",
                gap: 10,
                padding: "10px 10px",
                borderRadius: 14,
                border: glassTypeId === g.id ? `2px solid ${UI.primary}` : `1px solid ${UI.border}`,
                cursor: "pointer",
              }}
            >
              <input type="radio" checked={glassTypeId === g.id} onChange={() => setGlassTypeId(g.id)} />
              <span style={{ fontWeight: 800 }}>
                {g.name} – {money(g.pricePerM2)} €/m²
              </span>
            </label>
          ))}
        </div>
        <div style={{ display: "flex", justifyContent: "flex-end", marginTop: 10 }}>
          <Btn variant="primary" onClick={() => setGlassModal(false)}>
            Përfundo
          </Btn>
        </div>
      </Modal>


      <Modal open={doorModal} title="Zgjedh panelin e derës" onClose={() => setDoorModal(false)} footer={null}>
  <div style={{ display: "grid", gap: 12 }}>
    <div style={{ fontSize: 12, color: UI.muted, lineHeight: 1.4 }}>
      Zgjedh një panel të ngarkuar nga “Materials → Panele Dyer”.
      Paneli shtohet si <b>extra</b> në çmim, ndërsa korniza llogaritet nga profili (L).
    </div>

    <div
      style={{
        display: "grid",
        gridTemplateColumns: "repeat(2, minmax(0, 1fr))",
        gap: 12,
      }}
    >
      {(materials?.doorPanels || []).map((p) => {
        const active = String(p.id) === String(doorPanelId);

        return (
          <button
            key={p.id}
            onClick={() => handleSelectDoorPanel(p)}
            style={{
              border: active ? `2px solid ${UI.primary}` : `1px solid ${UI.border}`,
              borderRadius: 14,
              padding: 10,
              textAlign: "left",
              background: "#fff",
              cursor: "pointer",
              boxShadow: active ? "0 12px 28px rgba(59,130,246,.12)" : "none",
            }}
          >
            <div style={{ fontWeight: 950, fontSize: 13 }}>{p.name}</div>
            <div style={{ fontSize: 12, color: UI.muted, marginTop: 2 }}>
              Extra € {money(p.price || 0)}
            </div>

            <div style={{ marginTop: 10, background: "transparent" }}>
              {p.imageUrl ? (
                <img
                  src={p.imageUrl}
                  alt={p.name}
                  style={{
                    width: "100%",
                    height: 140,
                    objectFit: "contain",
                    display: "block",
                    background: "transparent",
                  }}
                />
              ) : (
                <div style={{ height: 140, display: "grid", placeItems: "center", color: UI.muted, fontSize: 12 }}>
                  No image
                </div>
              )}
            </div>
          </button>
        );
      })}
    </div>

    <div style={{ display: "flex", justifyContent: "space-between", gap: 10, marginTop: 8 }}>
      <Btn variant="danger" onClick={handleRemoveDoor} disabled={!isDoor}>
        Hiq derën
      </Btn>
      <div style={{ display: "flex", gap: 10 }}>
        <Btn onClick={() => setDoorModal(false)}>Mbyll</Btn>
      </div>
    </div>
  </div>
</Modal>

    </div>
  );
}

function Row({ label, value, strong, big }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", fontSize: big ? 14 : 12, fontWeight: strong ? 950 : 650 }}>
      <span style={{ color: UI.muted, fontWeight: 700 }}>{label}</span>
      <span style={{ color: UI.ink }}>{value}</span>
    </div>
  );
}

// simple door icon inline (or replace with your own IconDoor)
const IconDoor = () => (
  <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
    <path d="M7 3h10v18H7V3Z" stroke="currentColor" strokeWidth="2" />
    <path d="M10 12h1" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
  </svg>
);  