// import React, { useEffect, useMemo, useRef, useState } from "react";

// /* =============================================================================
//    OFERTA PVC + EDITOR FULLSCREEN (single-file)
//    - Dashboard i bardhë me të gjitha ofertat
//    - Çdo ofertë ka pozicione
//    - Editor fullscreen (tools majtas, canvas qendër, panel djathtas)
//    - Materialet & çmimet (Profile / Armaturë / Xham / Aksesorë)
//    ========================================================================== */

// /* ================== STORAGE KEYS ================== */
// const OFFERS_KEY = "pvc_offers_v1";
// const MATERIALS_KEY = "pvc_materials_v1";

// /* ================== DEFAULT SEED (MATERIALS) ================== */
// const DEFAULT_MATERIALS = {
//   profiles: [{ id: "profile-1", name: "Profine 88MD", pricePerM: 11.5 }],
//   irons: [{ id: "iron-1", name: "V309 / V303", pricePerM: 4.2 }],
//   glassTypes: [
//     { id: "stopsol", name: "Stopsol 4-16-4", pricePerM2: 28.0 },
//     { id: "lowe", name: "Low-E 4-16-4", pricePerM2: 25.0 },
//     { id: "triplex", name: "Triplex 6-16-4", pricePerM2: 35.0 },
//   ],
//   accessories: [
//     // { id: "acc-1", name: "Dorezë standard", unit: "pcs", price: 3.5 }
//   ],
// };

// /* ================== FACTORY CONSTANTS ================== */
// // ndrysho sipas fabrikës
// const FRAME_WELD_ADD_MM = 6;
// const SASH_REDUCE_MM = 84;
// const BEAD_REDUCE_MM = 120;
// const IRON_REDUCE_MM = 110;

// /* ================== UI TOKENS ================== */
// const UI = {
//   bg: "#ffffff",
//   soft: "#f8fafc",
//   card: "#ffffff",
//   border: "#e2e8f0",
//   ink: "#0f172a",
//   muted: "#64748b",
//   shadow: "0 18px 45px rgba(15,23,42,.08)",
//   shadow2: "0 22px 70px rgba(15,23,42,.18)",
//   primary: "#0f172a",
//   green: "#16a34a",
//   orange: "#f97316",
//   blue: "#3b82f6",
// };

// function uid() {
//   return Math.random().toString(16).slice(2) + Date.now().toString(16);
// }
// function money(n) {
//   const v = Number(n || 0);
//   return v.toFixed(2);
// }

// /* ================== STORAGE ================== */
// function loadOffers() {
//   try {
//     const raw = localStorage.getItem(OFFERS_KEY);
//     if (!raw) return [];
//     const parsed = JSON.parse(raw);
//     return Array.isArray(parsed) ? parsed : [];
//   } catch {
//     return [];
//   }
// }
// function saveOffers(offers) {
//   try {
//     localStorage.setItem(OFFERS_KEY, JSON.stringify(offers));
//   } catch {}
// }

// function loadMaterials() {
//   try {
//     const raw = localStorage.getItem(MATERIALS_KEY);
//     if (!raw) return DEFAULT_MATERIALS;
//     const parsed = JSON.parse(raw);
//     return {
//       profiles: Array.isArray(parsed?.profiles) && parsed.profiles.length ? parsed.profiles : DEFAULT_MATERIALS.profiles,
//       irons: Array.isArray(parsed?.irons) && parsed.irons.length ? parsed.irons : DEFAULT_MATERIALS.irons,
//       glassTypes: Array.isArray(parsed?.glassTypes) && parsed.glassTypes.length ? parsed.glassTypes : DEFAULT_MATERIALS.glassTypes,
//       accessories: Array.isArray(parsed?.accessories) ? parsed.accessories : DEFAULT_MATERIALS.accessories,
//     };
//   } catch {
//     return DEFAULT_MATERIALS;
//   }
// }
// function saveMaterials(materials) {
//   try {
//     localStorage.setItem(MATERIALS_KEY, JSON.stringify(materials));
//   } catch {}
// }

// /* ================== SMALL MODAL ================== */
// function Modal({ open, title, onClose, children, footer }) {
//   if (!open) return null;
//   return (
//     <div
//       style={{
//         position: "fixed",
//         inset: 0,
//         background: "rgba(15,23,42,.45)",
//         display: "flex",
//         alignItems: "center",
//         justifyContent: "center",
//         zIndex: 9999,
//         padding: 14,
//       }}
//       onMouseDown={(e) => {
//         if (e.target === e.currentTarget) onClose?.();
//       }}
//     >
//       <div
//         style={{
//           background: "#fff",
//           width: "min(680px, 95vw)",
//           borderRadius: 14,
//           boxShadow: UI.shadow2,
//           border: `1px solid ${UI.border}`,
//           overflow: "hidden",
//         }}
//       >
//         <div style={{ padding: "14px 16px", borderBottom: `1px solid ${UI.border}` }}>
//           <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10 }}>
//             <h3 style={{ margin: 0, fontSize: 14, fontWeight: 750, color: UI.ink }}>{title}</h3>
//             <button
//               onClick={onClose}
//               style={{
//                 border: `1px solid ${UI.border}`,
//                 background: "#fff",
//                 borderRadius: 10,
//                 padding: "6px 10px",
//                 cursor: "pointer",
//                 fontSize: 12,
//               }}
//             >
//               ✕
//             </button>
//           </div>
//         </div>

//         <div style={{ padding: 16 }}>{children}</div>

//         <div style={{ padding: 12, borderTop: `1px solid ${UI.border}` }}>
//           {footer ? (
//             footer
//           ) : (
//             <div style={{ textAlign: "right" }}>
//               <button
//                 onClick={onClose}
//                 style={{
//                   background: "transparent",
//                   border: `1px solid ${UI.border}`,
//                   borderRadius: 10,
//                   padding: "8px 12px",
//                   fontSize: 12,
//                   cursor: "pointer",
//                 }}
//               >
//                 Mbyll
//               </button>
//             </div>
//           )}
//         </div>
//       </div>
//     </div>
//   );
// }

// /* ================== SMALL UI HELPERS ================== */
// function Pill({ children, tone = "soft" }) {
//   const map = {
//     soft: { bg: "#f1f5f9", bd: UI.border, fg: UI.ink },
//     blue: { bg: "#dbeafe", bd: "#bfdbfe", fg: "#1e3a8a" },
//     green: { bg: "#dcfce7", bd: "#bbf7d0", fg: "#14532d" },
//     orange: { bg: "#ffedd5", bd: "#fed7aa", fg: "#7c2d12" },
//   };
//   const t = map[tone] || map.soft;
//   return (
//     <span
//       style={{
//         display: "inline-flex",
//         alignItems: "center",
//         gap: 6,
//         padding: "4px 10px",
//         borderRadius: 999,
//         background: t.bg,
//         border: `1px solid ${t.bd}`,
//         color: t.fg,
//         fontSize: 12,
//         fontWeight: 650,
//         whiteSpace: "nowrap",
//       }}
//     >
//       {children}
//     </span>
//   );
// }

// function Btn({ children, onClick, variant = "ghost", disabled, style, title }) {
//   const base = {
//     borderRadius: 12,
//     padding: "10px 12px",
//     fontSize: 13,
//     fontWeight: 700,
//     cursor: disabled ? "not-allowed" : "pointer",
//     opacity: disabled ? 0.6 : 1,
//     border: `1px solid ${UI.border}`,
//     background: "#fff",
//     color: UI.ink,
//   };
//   const variants = {
//     ghost: { background: "#fff", border: `1px solid ${UI.border}`, color: UI.ink },
//     primary: { background: UI.primary, border: `1px solid ${UI.primary}`, color: "#fff" },
//     soft: { background: "#f1f5f9", border: `1px solid ${UI.border}`, color: UI.ink },
//     danger: { background: "#fee2e2", border: "1px solid #fecaca", color: "#b91c1c" },
//     success: { background: UI.green, border: `1px solid ${UI.green}`, color: "#fff" },
//   };
//   return (
//     <button
//       title={title}
//       disabled={disabled}
//       onClick={disabled ? undefined : onClick}
//       style={{ ...base, ...(variants[variant] || variants.ghost), ...style }}
//     >
//       {children}
//     </button>
//   );
// }

// function Field({ label, hint, children }) {
//   return (
//     <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
//       <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", gap: 10 }}>
//         <div style={{ fontSize: 12, fontWeight: 700, color: UI.ink }}>{label}</div>
//         {hint ? <div style={{ fontSize: 11, color: UI.muted }}>{hint}</div> : null}
//       </div>
//       {children}
//     </div>
//   );
// }

// function TextInput(props) {
//   return (
//     <input
//       {...props}
//       style={{
//         width: "100%",
//         border: `1px solid ${UI.border}`,
//         borderRadius: 12,
//         padding: "10px 12px",
//         fontSize: 13,
//         outline: "none",
//         ...props.style,
//       }}
//     />
//   );
// }

// function Select(props) {
//   return (
//     <select
//       {...props}
//       style={{
//         width: "100%",
//         border: `1px solid ${UI.border}`,
//         borderRadius: 12,
//         padding: "10px 12px",
//         fontSize: 13,
//         outline: "none",
//         background: "#fff",
//         ...props.style,
//       }}
//     />
//   );
// }

// /* ================== RESIZE HOOK ================== */
// function useMeasure() {
//   const ref = useRef(null);
//   const [rect, setRect] = useState({ width: 1100, height: 540 });

//   useEffect(() => {
//     const el = ref.current;
//     if (!el) return;
//     const ro = new ResizeObserver((entries) => {
//       const r = entries[0]?.contentRect;
//       if (!r) return;
//       setRect({ width: Math.max(300, r.width), height: Math.max(240, r.height) });
//     });
//     ro.observe(el);
//     return () => ro.disconnect();
//   }, []);

//   return [ref, rect];
// }

// /* ========================================================================
//    IKONAT (INLINE SVG) për butonat në sidebar
//    ======================================================================== */
// function Ico({ children }) {
//   return (
//     <span style={{ display: "inline-grid", placeItems: "center", width: 22, height: 22 }}>
//       {children}
//     </span>
//   );
// }
// function IconFrame() {
//   return (
//     <Ico>
//       <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
//         <rect x="4" y="4" width="16" height="16" stroke="#0f172a" strokeWidth="2" rx="3" />
//         <rect x="7.5" y="7.5" width="9" height="9" stroke="#64748b" strokeWidth="2" rx="2" />
//       </svg>
//     </Ico>
//   );
// }
// function IconIrregular() {
//   return (
//     <Ico>
//       <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
//         <path d="M5 18V6h14v12H5Z" stroke="#0f172a" strokeWidth="2" />
//         <path d="M5 9l14-3" stroke="#3b82f6" strokeWidth="2" strokeLinecap="round" />
//       </svg>
//     </Ico>
//   );
// }
// function IconSash() {
//   return (
//     <Ico>
//       <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
//         <rect x="5" y="4" width="14" height="16" rx="3" stroke="#0f172a" strokeWidth="2" />
//         <path d="M12 6v12" stroke="#64748b" strokeWidth="2" />
//         <circle cx="9" cy="12" r="1.2" fill="#0f172a" />
//       </svg>
//     </Ico>
//   );
// }
// function IconSplit() {
//   return (
//     <Ico>
//       <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
//         <rect x="5" y="4" width="14" height="16" rx="3" stroke="#0f172a" strokeWidth="2" />
//         <path d="M12 5v14" stroke="#0f172a" strokeWidth="2" strokeLinecap="round" />
//         <path d="M9 8h-2M9 12h-2M9 16h-2" stroke="#64748b" strokeWidth="2" strokeLinecap="round" />
//       </svg>
//     </Ico>
//   );
// }
// function IconGlass() {
//   return (
//     <Ico>
//       <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
//         <path d="M7 4h10l-1 16H8L7 4Z" stroke="#0f172a" strokeWidth="2" />
//         <path d="M9 9h6" stroke="#3b82f6" strokeWidth="2" strokeLinecap="round" />
//       </svg>
//     </Ico>
//   );
// }
// function IconStaticGlass() {
//   return (
//     <Ico>
//       <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
//         <rect x="5" y="4" width="14" height="16" rx="3" stroke="#0f172a" strokeWidth="2" />
//         <rect x="7.5" y="7" width="9" height="10" rx="2" fill="rgba(59,130,246,.25)" stroke="#3b82f6" strokeWidth="2" />
//       </svg>
//     </Ico>
//   );
// }
// function IconRoll() {
//   return (
//     <Ico>
//       <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
//         <rect x="5" y="4" width="14" height="5" rx="2" stroke="#0f172a" strokeWidth="2" />
//         <rect x="5" y="9" width="14" height="11" rx="3" stroke="#64748b" strokeWidth="2" />
//         <path d="M8 12h8M8 15h8M8 18h8" stroke="#64748b" strokeWidth="2" strokeLinecap="round" />
//       </svg>
//     </Ico>
//   );
// }
// function IconT() {
//   return (
//     <Ico>
//       <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
//         <path d="M6 6h12" stroke="#0f172a" strokeWidth="2" strokeLinecap="round" />
//         <path d="M12 6v14" stroke="#0f172a" strokeWidth="2" strokeLinecap="round" />
//         <path d="M9 20h6" stroke="#64748b" strokeWidth="2" strokeLinecap="round" />
//       </svg>
//     </Ico>
//   );
// }
// function IconGlassType() {
//   return (
//     <Ico>
//       <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
//         <path d="M7 4h10l-1 16H8L7 4Z" stroke="#0f172a" strokeWidth="2" />
//         <path d="M10 12h4" stroke="#0f172a" strokeWidth="2" strokeLinecap="round" />
//         <path d="M12 10v4" stroke="#3b82f6" strokeWidth="2" strokeLinecap="round" />
//       </svg>
//     </Ico>
//   );
// }

// /* ========================================================================
//    OPENING LINES INSIDE SASH (u rregulluan trekëndëshat)
//    ======================================================================== */
// function renderOpening(type, x, y, w, h) {
//   const c = "#ffffff";
//   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 els = [];

//   if (type === "fixed") return els;

//   if (type === "turn-right") {
//     els.push(<line key="tr1" x1={left} y1={midY} x2={right} y2={top} stroke={c} strokeWidth={1.2} />);
//     els.push(<line key="tr2" x1={left} y1={midY} x2={right} y2={bottom} stroke={c} strokeWidth={1.2} />);
//   }

//   if (type === "turn-left") {
//     els.push(<line key="tl1" x1={right} y1={midY} x2={left} y2={top} stroke={c} strokeWidth={1.2} />);
//     els.push(<line key="tl2" x1={right} y1={midY} x2={left} y2={bottom} stroke={c} strokeWidth={1.2} />);
//   }

//   if (type === "tilt-top") {
//     els.push(<line key="tt1" x1={left} y1={bottom} x2={midX} y2={top} stroke={c} strokeWidth={1.2} />);
//     els.push(<line key="tt2" x1={midX} y1={top} x2={right} y2={bottom} stroke={c} strokeWidth={1.2} />);

//     // els.push(<line key="tt3" x1={left} y1={top} x2={right} y2={bottom} stroke={c} strokeWidth={1.0} opacity={0.65} />);
//     // els.push(<line key="tt4" x1={right} y1={top} x2={left} y2={bottom} stroke={c} strokeWidth={1.0} opacity={0.65} />);

//     const arrY = y + h * 0.5;
//     const arrStart = midX + 18;
//     const arrEnd = midX - 14;
//     els.push(<line key="tta" x1={arrStart} y1={arrY} x2={arrEnd} y2={arrY} stroke={c} strokeWidth={1} />);
//     els.push(
//       <polyline
//         key="ttb"
//         points={`${arrEnd},${arrY} ${arrEnd + 6},${arrY - 4} ${arrEnd + 6},${arrY + 4}`}
//         fill="none"
//         stroke={c}
//         strokeWidth={1}
//       />
//     );
//   }

//   if (type === "tilt-top-center") {
//     const apexY = top + 6;
//     els.push(<line key="ttc1" x1={left} y1={bottom} x2={midX} y2={apexY} stroke={c} strokeWidth={1.2} />);
//     els.push(<line key="ttc2" x1={midX} y1={apexY} x2={right} y2={bottom} stroke={c} strokeWidth={1.2} />);
//     // els.push(<line key="ttc3" x1={left} y1={apexY} x2={right} y2={bottom} stroke={c} strokeWidth={1.0} opacity={0.65} />);
//     // els.push(<line key="ttc4" x1={right} y1={apexY} x2={left} y2={bottom} stroke={c} strokeWidth={1.0} opacity={0.65} />);
//   }

//   if (type === "turn-right+tilt-top") {
//     els.push(<line key="trtt1" x1={left} y1={bottom} x2={midX} y2={top} stroke={c} strokeWidth={1.2} />);
//     els.push(<line key="trtt2" x1={midX} y1={top} x2={right} y2={bottom} stroke={c} strokeWidth={1.2} />);

//     els.push(<line key="trtt3" x1={left} y1={midY} x2={right} y2={top} stroke={c} strokeWidth={1.2} />);
//     els.push(<line key="trtt4" x1={left} y1={midY} x2={right} y2={bottom} stroke={c} strokeWidth={1.2} />);

//     // els.push(<line key="trtt5" x1={left} y1={top} x2={right} y2={bottom} stroke={c} strokeWidth={1.0} opacity={0.55} />);
//   }

//   return els;
// }

// /* ================== MIGRATION HELPERS ================== */
// function migrateOffers(existingOffers, materials) {
//   const profileByName = new Map(materials.profiles.map((p) => [p.name, p.id]));
//   const ironByName = new Map(materials.irons.map((i) => [i.name, i.id]));
//   const defaultProfileId = materials.profiles[0]?.id || "profile-1";
//   const defaultIronId = materials.irons[0]?.id || "iron-1";

//   return (existingOffers || []).map((o) => {
//     const profileId = o.profileId || profileByName.get(o.profileName) || profileByName.get(o.profile) || defaultProfileId;
//     const ironId = o.ironId || ironByName.get(o.ironName) || ironByName.get(o.iron) || defaultIronId;

//     return {
//       ...o,
//       profileId,
//       ironId,
//       updatedAt: o.updatedAt || Date.now(),
//       createdAt: o.createdAt || Date.now(),
//       positions: Array.isArray(o.positions) ? o.positions : [],
//     };
//   });
// }

// /* ================== PARENT APP ================== */
// export default function App() {
//   const [materials, setMaterials] = useState(() => loadMaterials());

//   const [offers, setOffers] = useState(() => {
//     const existing = loadOffers();
//     if (existing.length) return migrateOffers(existing, loadMaterials());
//     return [
//       {
//         id: uid(),
//         name: "Oferta 01",
//         margin: 20,
//         color: "[BB] Bardhë-Bardhë",
//         profileId: loadMaterials().profiles[0]?.id || "profile-1",
//         ironId: loadMaterials().irons[0]?.id || "iron-1",
//         createdAt: Date.now(),
//         updatedAt: Date.now(),
//         positions: [],
//       },
//     ];
//   });

//   const [route, setRoute] = useState({ page: "dashboard", offerId: null });

//   useEffect(() => saveOffers(offers), [offers]);
//   useEffect(() => saveMaterials(materials), [materials]);

//   useEffect(() => {
//     const profIds = new Set(materials.profiles.map((p) => p.id));
//     const ironIds = new Set(materials.irons.map((i) => i.id));
//     const defP = materials.profiles[0]?.id;
//     const defI = materials.irons[0]?.id;
//     if (!defP || !defI) return;

//     setOffers((prev) =>
//       prev.map((o) => ({
//         ...o,
//         profileId: profIds.has(o.profileId) ? o.profileId : defP,
//         ironId: ironIds.has(o.ironId) ? o.ironId : defI,
//       }))
//     );
//   }, [materials.profiles, materials.irons]);

//   const selectedOffer = useMemo(() => offers.find((o) => o.id === route.offerId) || null, [offers, route.offerId]);

//   const upsertOffer = (offerId, patch) => {
//     setOffers((prev) => prev.map((o) => (o.id === offerId ? { ...o, ...patch, updatedAt: Date.now() } : o)));
//   };

//   const addOffer = (offer) => {
//     const defProfileId = materials.profiles[0]?.id || "profile-1";
//     const defIronId = materials.irons[0]?.id || "iron-1";

//     setOffers((prev) => [
//       {
//         ...offer,
//         id: uid(),
//         profileId: offer.profileId || defProfileId,
//         ironId: offer.ironId || defIronId,
//         createdAt: Date.now(),
//         updatedAt: Date.now(),
//         positions: [],
//       },
//       ...prev,
//     ]);
//   };

//   const deleteOffer = (offerId) => {
//     setOffers((prev) => prev.filter((o) => o.id !== offerId));
//     setRoute({ page: "dashboard", offerId: null });
//   };

//   return (
//     <div style={{ minHeight: "100vh", background: UI.bg, color: UI.ink }}>
//       <style>{`
//         *{box-sizing:border-box}
//         .wrap{max-width:1240px;margin:0 auto;padding:18px}
//         .offersGrid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px}
//         @media (max-width: 1024px){.offersGrid{grid-template-columns:repeat(2,minmax(0,1fr))}}
//         @media (max-width: 640px){.offersGrid{grid-template-columns:1fr}}
//         .overviewGrid{display:grid;grid-template-columns:1.2fr .8fr;gap:12px;align-items:start}
//         @media (max-width: 980px){.overviewGrid{grid-template-columns:1fr}}
//         .stickyHeader{position:sticky;top:0;z-index:20;background:rgba(255,255,255,.9);backdrop-filter:blur(10px);border-bottom:1px solid ${UI.border};}
//         .editorGrid{display:grid;gap:12px;align-items:stretch;height:calc(100vh - var(--topH) - 24px);grid-template-columns:var(--leftW) 1fr var(--rightW);}
//         @media (max-width: 1100px){
//           .editorGrid{grid-template-columns:1fr;height:auto}
//           .leftTools{position:sticky;top:var(--topH);display:flex;flex-direction:row;gap:10px;align-items:center;overflow:auto;white-space:nowrap}
//           .rightPanel{position:static;height:auto}
//           .canvasCard{min-height:55vh}
//         }
//         @media (max-width: 560px){
//           .leftTools{gap:8px}
//         }
//       `}</style>

//       {route.page === "dashboard" ? (
//         <OffersDashboard
//           offers={offers}
//           materials={materials}
//           onOpenOffer={(id) => setRoute({ page: "offer", offerId: id })}
//           onCreateOffer={addOffer}
//           onOpenMaterials={() => setRoute({ page: "materials", offerId: null })}
//         />
//       ) : route.page === "materials" ? (
//         <MaterialsManager materials={materials} setMaterials={setMaterials} onBack={() => setRoute({ page: "dashboard", offerId: null })} />
//       ) : (
//         <OfferWorkspace
//           offer={selectedOffer}
//           materials={materials}
//           onBack={() => setRoute({ page: "dashboard", offerId: null })}
//           onOpenMaterials={() => setRoute({ page: "materials", offerId: null })}
//           onUpdateOffer={(patch) => selectedOffer && upsertOffer(selectedOffer.id, patch)}
//           onDeleteOffer={() => selectedOffer && deleteOffer(selectedOffer.id)}
//         />
//       )}
//     </div>
//   );
// }

// /* ================== DASHBOARD ================== */
// function OffersDashboard({ offers, materials, onOpenOffer, onCreateOffer, onOpenMaterials }) {
//   const [q, setQ] = useState("");
//   const [createOpen, setCreateOpen] = useState(false);

//   const [name, setName] = useState("");
//   const [margin, setMargin] = useState(20);
//   const [color, setColor] = useState("[BB] Bardhë-Bardhë");
//   const [profileId, setProfileId] = useState(materials.profiles[0]?.id || "");
//   const [ironId, setIronId] = useState(materials.irons[0]?.id || "");

//   useEffect(() => {
//     setProfileId((p) => p || materials.profiles[0]?.id || "");
//     setIronId((i) => i || materials.irons[0]?.id || "");
//   }, [materials.profiles, materials.irons]);

//   const filtered = useMemo(() => {
//     const s = q.trim().toLowerCase();
//     if (!s) return offers;
//     return offers.filter((o) => (o.name || "").toLowerCase().includes(s));
//   }, [offers, q]);

//   const totalAll = useMemo(() => offers.reduce((sum, o) => sum + (o.positions || []).reduce((s, p) => s + (p.total || 0), 0), 0), [offers]);

//   const profCount = materials.profiles.length;
//   const ironCount = materials.irons.length;
//   const glassCount = materials.glassTypes.length;
//   const accCount = materials.accessories.length;

//   return (
//     <div>
//       <div className="stickyHeader">
//         <div
//           style={{
//             maxWidth: 1240,
//             margin: "0 auto",
//             padding: "14px 18px",
//             display: "flex",
//             alignItems: "center",
//             justifyContent: "space-between",
//             gap: 12,
//           }}
//         >
//           <div style={{ display: "flex", alignItems: "center", gap: 10, minWidth: 0 }}>
//             <div
//               style={{
//                 width: 38,
//                 height: 38,
//                 borderRadius: 12,
//                 background: UI.primary,
//                 color: "#fff",
//                 display: "grid",
//                 placeItems: "center",
//                 fontWeight: 900,
//               }}
//             >
//               PVC
//             </div>
//             <div style={{ display: "flex", flexDirection: "column", lineHeight: 1.1, minWidth: 0 }}>
//               <div style={{ fontWeight: 900, fontSize: 14, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>Ofertat PVC</div>
//               <div style={{ fontSize: 12, color: UI.muted }}>Oferta • Pozicione • Print skicë</div>
//             </div>

//             <div style={{ marginLeft: 10, display: "flex", gap: 8, flexWrap: "wrap" }}>
//               <Pill tone="soft">Totali: € {money(totalAll)}</Pill>
//               <Btn
//                 variant="soft"
//                 onClick={onOpenMaterials}
//                 style={{ padding: "8px 10px", borderRadius: 999 }}
//                 title="Menaxho çmimet për profile, armaturë, xham, aksesorë"
//               >
//                 ⚙ Materialet
//               </Btn>
//               <Pill tone="blue">
//                 P:{profCount} • A:{ironCount} • X:{glassCount} • AK:{accCount}
//               </Pill>
//             </div>
//           </div>

//           <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
//             <div style={{ width: 320, maxWidth: "40vw" }}>
//               <TextInput value={q} onChange={(e) => setQ(e.target.value)} placeholder="Kërko ofertë…" style={{ background: UI.soft }} />
//             </div>
//             <Btn
//               variant="primary"
//               onClick={() => {
//                 setName("");
//                 setMargin(20);
//                 setColor("[BB] Bardhë-Bardhë");
//                 setProfileId(materials.profiles[0]?.id || "");
//                 setIronId(materials.irons[0]?.id || "");
//                 setCreateOpen(true);
//               }}
//             >
//               + Ofertë e re
//             </Btn>
//           </div>
//         </div>
//       </div>

//       <div className="wrap">
//         <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10, marginBottom: 10 }}>
//           <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
//             <Pill tone="blue">{filtered.length} ofertë(a)</Pill>
//             <Pill tone="soft">Print: e njejtë si editori</Pill>
//           </div>
//           <div style={{ fontSize: 12, color: UI.muted }}>Hape ofertën → Editori → 🖼️ Skicë (print vetëm dizajni).</div>
//         </div>

//         {filtered.length === 0 ? (
//           <div style={{ border: `1px dashed ${UI.border}`, borderRadius: 18, padding: 28, background: UI.soft, color: UI.muted }}>
//             Nuk u gjet asnjë ofertë.
//           </div>
//         ) : (
//           <div className="offersGrid">
//             {filtered.map((o) => (
//               <OfferCard key={o.id} offer={o} materials={materials} onOpen={() => onOpenOffer(o.id)} />
//             ))}
//           </div>
//         )}
//       </div>

//       <Modal
//         open={createOpen}
//         title="Krijo ofertë të re"
//         onClose={() => setCreateOpen(false)}
//         footer={
//           <div style={{ display: "flex", justifyContent: "space-between", gap: 10 }}>
//             <Btn variant="ghost" onClick={() => setCreateOpen(false)}>
//               Anulo
//             </Btn>
//             <Btn
//               variant="primary"
//               onClick={() => {
//                 if (!name.trim()) return;
//                 onCreateOffer({
//                   name: name.trim(),
//                   margin: Number(margin) || 0,
//                   color,
//                   profileId,
//                   ironId,
//                 });
//                 setCreateOpen(false);
//               }}
//               disabled={!name.trim() || !profileId || !ironId}
//             >
//               Krijo ofertën
//             </Btn>
//           </div>
//         }
//       >
//         <div style={{ display: "grid", gap: 12 }}>
//           <Field label="Emri i ofertës">
//             <TextInput value={name} onChange={(e) => setName(e.target.value)} placeholder="p.sh. Oferta – Klienti X" />
//           </Field>

//           <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
//             <Field label="Marzha (%)">
//               <TextInput type="number" value={margin} onChange={(e) => setMargin(Number(e.target.value) || 0)} placeholder="20" />
//             </Field>
//             <Field label="Ngjyra">
//               <Select value={color} onChange={(e) => setColor(e.target.value)}>
//                 <option value="[BB] Bardhë-Bardhë">[BB] Bardhë-Bardhë</option>
//                 <option value="Antracit">Antracit</option>
//                 <option value="Golden Oak">Golden Oak</option>
//               </Select>
//             </Field>
//           </div>

//           <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
//             <Field label="Profili default">
//               <Select value={profileId} onChange={(e) => setProfileId(e.target.value)}>
//                 {materials.profiles.map((p) => (
//                   <option key={p.id} value={p.id}>
//                     {p.name} — € {money(p.pricePerM)}/m
//                   </option>
//                 ))}
//               </Select>
//             </Field>
//             <Field label="Armatura default">
//               <Select value={ironId} onChange={(e) => setIronId(e.target.value)}>
//                 {materials.irons.map((i) => (
//                   <option key={i.id} value={i.id}>
//                     {i.name} — € {money(i.pricePerM)}/m
//                   </option>
//                 ))}
//               </Select>
//             </Field>
//           </div>

//           <div style={{ fontSize: 12, color: UI.muted }}>
//             Çmimet mund t’i menaxhosh në çdo kohë te <b>⚙ Materialet</b>.
//           </div>
//         </div>
//       </Modal>
//     </div>
//   );
// }

// function OfferCard({ offer, materials, onOpen }) {
//   const positions = offer.positions || [];
//   const sum = positions.reduce((s, p) => s + (p.total || 0), 0);

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

//   return (
//     <div
//       style={{
//         border: `1px solid ${UI.border}`,
//         borderRadius: 18,
//         background: "#fff",
//         boxShadow: UI.shadow,
//         padding: 14,
//         display: "flex",
//         flexDirection: "column",
//         gap: 10,
//         minWidth: 0,
//       }}
//     >
//       <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 10 }}>
//         <div style={{ display: "flex", flexDirection: "column", gap: 6, minWidth: 0 }}>
//           <div style={{ fontSize: 12, color: UI.muted }}>Ofertë</div>
//           <div style={{ fontSize: 14, fontWeight: 900, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{offer.name}</div>
//           <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
//             <Pill tone="soft">Marzha: {offer.margin}%</Pill>
//             <Pill tone="soft">Pozicione: {positions.length}</Pill>
//             <Pill tone="soft">Profil: {profileName}</Pill>
//             <Pill tone="soft">Arm: {ironName}</Pill>
//           </div>
//         </div>
//         <div style={{ textAlign: "right" }}>
//           <div style={{ fontSize: 12, color: UI.muted }}>Totali</div>
//           <div style={{ fontSize: 18, fontWeight: 950 }}>€ {money(sum)}</div>
//         </div>
//       </div>

//       <div style={{ display: "flex", gap: 10, alignItems: "center", justifyContent: "space-between" }}>
//         <div style={{ fontSize: 12, color: UI.muted }}>Përditësuar: {offer.updatedAt ? new Date(offer.updatedAt).toLocaleString() : "—"}</div>
//         <Btn variant="primary" onClick={onOpen} style={{ padding: "10px 14px" }}>
//           Hape →
//         </Btn>
//       </div>
//     </div>
//   );
// }

// /* ================== MATERIALS MANAGER ================== */
// function MaterialsManager({ materials, setMaterials, onBack }) {
//   const [tab, setTab] = useState("profiles"); // profiles | irons | glass | accessories
//   const [editOpen, setEditOpen] = useState(false);
//   const [mode, setMode] = useState("create"); // create | edit
//   const [targetId, setTargetId] = useState(null);

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

//   const list =
//     tab === "profiles" ? materials.profiles : tab === "irons" ? materials.irons : tab === "glass" ? materials.glassTypes : materials.accessories;

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

//   const openEdit = (item) => {
//     setMode("edit");
//     setTargetId(item.id);
//     setName(item.name || "");
//     if (tab === "glass") setPricePerM2(Number(item.pricePerM2 || 0));
//     else if (tab === "accessories") {
//       setAccUnit(item.unit || "pcs");
//       setAccPrice(Number(item.price || 0));
//     } else setPricePerM(Number(item.pricePerM || 0));
//     setEditOpen(true);
//   };

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

//     setMaterials((prev) => {
//       const next = { ...prev };
//       if (tab === "profiles") next.profiles = prev.profiles.filter((x) => x.id !== id);
//       if (tab === "irons") next.irons = prev.irons.filter((x) => x.id !== id);
//       if (tab === "glass") next.glassTypes = prev.glassTypes.filter((x) => x.id !== id);
//       if (tab === "accessories") next.accessories = prev.accessories.filter((x) => x.id !== id);

//       if (next.profiles.length === 0) next.profiles = DEFAULT_MATERIALS.profiles;
//       if (next.irons.length === 0) next.irons = DEFAULT_MATERIALS.irons;
//       if (next.glassTypes.length === 0) next.glassTypes = DEFAULT_MATERIALS.glassTypes;

//       return next;
//     });
//   };

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

//     setMaterials((prev) => {
//       const next = { ...prev };
//       const id = mode === "edit" ? targetId : uid();

//       if (tab === "profiles") {
//         const item = { id, name: name.trim(), pricePerM: Number(pricePerM) || 0 };
//         next.profiles = mode === "edit" ? prev.profiles.map((x) => (x.id === id ? item : x)) : [item, ...prev.profiles];
//       }

//       if (tab === "irons") {
//         const item = { id, name: name.trim(), pricePerM: Number(pricePerM) || 0 };
//         next.irons = mode === "edit" ? prev.irons.map((x) => (x.id === id ? item : x)) : [item, ...prev.irons];
//       }

//       if (tab === "glass") {
//         const item = { id, name: name.trim(), pricePerM2: Number(pricePerM2) || 0 };
//         next.glassTypes = mode === "edit" ? prev.glassTypes.map((x) => (x.id === id ? item : x)) : [item, ...prev.glassTypes];
//       }

//       if (tab === "accessories") {
//         const item = { id, name: name.trim(), unit: accUnit, price: Number(accPrice) || 0 };
//         next.accessories = mode === "edit" ? prev.accessories.map((x) => (x.id === id ? item : x)) : [item, ...prev.accessories];
//       }

//       return next;
//     });

//     setEditOpen(false);
//   };

//   return (
//     <div>
//       <div className="stickyHeader">
//         <div
//           style={{
//             maxWidth: 1240,
//             margin: "0 auto",
//             padding: "14px 18px",
//             display: "flex",
//             alignItems: "center",
//             justifyContent: "space-between",
//             gap: 12,
//           }}
//         >
//           <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
//             <Btn variant="ghost" onClick={onBack}>
//               ← Dashboard
//             </Btn>
//             <div style={{ display: "flex", flexDirection: "column", lineHeight: 1.1 }}>
//               <div style={{ fontWeight: 950, fontSize: 14 }}>Materialet & Çmimet</div>
//               <div style={{ fontSize: 12, color: UI.muted }}>Profile • Armaturë • Xham • Aksesorë</div>
//             </div>
//           </div>

//           <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
//             <Pill tone="blue">Ruhet në localStorage</Pill>
//             <Btn variant="primary" onClick={openCreate}>
//               + Shto
//             </Btn>
//           </div>
//         </div>
//       </div>

//       <div className="wrap">
//         <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginBottom: 12 }}>
//           {[
//             ["profiles", `Profile (${materials.profiles.length})`],
//             ["irons", `Armaturë (${materials.irons.length})`],
//             ["glass", `Xham (${materials.glassTypes.length})`],
//             ["accessories", `Aksesorë (${materials.accessories.length})`],
//           ].map(([k, label]) => (
//             <button
//               key={k}
//               onClick={() => setTab(k)}
//               style={{
//                 border: tab === k ? `2px solid ${UI.primary}` : `1px solid ${UI.border}`,
//                 background: "#fff",
//                 borderRadius: 999,
//                 padding: "8px 12px",
//                 fontWeight: 900,
//                 fontSize: 12,
//                 cursor: "pointer",
//               }}
//             >
//               {label}
//             </button>
//           ))}
//         </div>

//         <div style={{ border: `1px solid ${UI.border}`, borderRadius: 18, background: "#fff", boxShadow: UI.shadow }}>
//           <div style={{ padding: 14, borderBottom: `1px solid ${UI.border}`, display: "flex", justifyContent: "space-between", gap: 10, flexWrap: "wrap" }}>
//             <div>
//               <div style={{ fontSize: 12, color: UI.muted }}>Menaxho</div>
//               <div style={{ fontSize: 14, fontWeight: 950 }}>
//                 {tab === "profiles" ? "Profile" : tab === "irons" ? "Armaturë" : tab === "glass" ? "Llojet e xhamit" : "Aksesorë"}
//               </div>
//             </div>
//             <div style={{ fontSize: 12, color: UI.muted, alignSelf: "flex-end" }}>UI gati për backend.</div>
//           </div>

//           <div style={{ padding: 14, overflow: "auto" }}>
//             {list.length === 0 ? (
//               <div style={{ padding: 14, borderRadius: 14, background: UI.soft, color: UI.muted, border: `1px dashed ${UI.border}` }}>Bosh.</div>
//             ) : (
//               <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13, minWidth: 520 }}>
//                 <thead>
//                   <tr>
//                     <th style={th}>Emri</th>
//                     <th style={th}>{tab === "glass" ? "€/m²" : tab === "accessories" ? "Çmimi" : "€/m"}</th>
//                     {tab === "accessories" ? <th style={th}>Njësia</th> : null}
//                     <th style={{ ...th, textAlign: "right" }}>Veprime</th>
//                   </tr>
//                 </thead>
//                 <tbody>
//                   {list.map((x) => (
//                     <tr key={x.id}>
//                       <td style={td}>{x.name}</td>
//                       <td style={td}>{tab === "glass" ? money(x.pricePerM2) : tab === "accessories" ? money(x.price) : money(x.pricePerM)}</td>
//                       {tab === "accessories" ? <td style={td}>{x.unit}</td> : null}
//                       <td style={{ ...td, textAlign: "right" }}>
//                         <div style={{ display: "inline-flex", gap: 8, flexWrap: "wrap", justifyContent: "flex-end" }}>
//                           <Btn variant="soft" onClick={() => openEdit(x)} style={{ padding: "8px 10px" }}>
//                             Ndrysho
//                           </Btn>
//                           <Btn variant="danger" onClick={() => removeItem(x.id)} style={{ padding: "8px 10px" }}>
//                             Fshij
//                           </Btn>
//                         </div>
//                       </td>
//                     </tr>
//                   ))}
//                 </tbody>
//               </table>
//             )}
//           </div>
//         </div>
//       </div>

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

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

//           <div style={{ fontSize: 12, color: UI.muted, lineHeight: 1.45 }}>
//             Më vonë e lidhim me Laravel API.
//           </div>
//         </div>
//       </Modal>
//     </div>
//   );
// }

// const th = { borderBottom: `1px solid ${UI.border}`, padding: "10px 8px", textAlign: "left", fontSize: 12, color: UI.muted };
// const td = { borderBottom: `1px solid ${UI.border}`, padding: "12px 8px" };

// /* ================== OFFER WORKSPACE ================== */
// function OfferWorkspace({ offer, materials, onBack, onOpenMaterials, onUpdateOffer, onDeleteOffer }) {
//   const [tab, setTab] = useState("overview"); // overview | editor
//   const [dangerOpen, setDangerOpen] = useState(false);

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

//   const positions = offer.positions || [];
//   const offerTotal = positions.reduce((s, p) => s + (p.total || 0), 0);

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

//   return (
//     <div style={{ minHeight: "100vh", background: UI.bg }}>
//       <div className="stickyHeader" style={{ zIndex: 25 }}>
//         <div style={{ padding: "12px 14px", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, flexWrap: "wrap" }}>
//           <div style={{ display: "flex", alignItems: "center", gap: 10, minWidth: 0, flexWrap: "wrap" }}>
//             <Btn variant="ghost" onClick={onBack} style={{ padding: "10px 12px" }}>
//               ← Dashboard
//             </Btn>
//             <Btn variant="soft" onClick={onOpenMaterials} style={{ padding: "10px 12px" }} title="Menaxho materialet/çmimet">
//               ⚙ Materialet
//             </Btn>

//             <div style={{ minWidth: 0 }}>
//               <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
//                 <div style={{ fontWeight: 950, fontSize: 14, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{offer.name}</div>
//                 <Pill tone="soft">Pozicione: {positions.length}</Pill>
//                 <Pill tone="green">€ {money(offerTotal)}</Pill>
//               </div>
//               <div style={{ fontSize: 12, color: UI.muted, marginTop: 2 }}>
//                 Profil: {profileName} • Armaturë: {ironName} • Ngjyra: {offer.color}
//               </div>
//             </div>
//           </div>

//           <div style={{ display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap" }}>
//             <div style={{ display: "flex", background: UI.soft, border: `1px solid ${UI.border}`, borderRadius: 14, padding: 4 }}>
//               <button
//                 onClick={() => setTab("overview")}
//                 style={{
//                   border: "none",
//                   background: tab === "overview" ? "#fff" : "transparent",
//                   borderRadius: 10,
//                   padding: "8px 10px",
//                   fontWeight: 900,
//                   fontSize: 12,
//                   cursor: "pointer",
//                   border: tab === "overview" ? `1px solid ${UI.border}` : "1px solid transparent",
//                 }}
//               >
//                 Përmbledhje
//               </button>
//               <button
//                 onClick={() => setTab("editor")}
//                 style={{
//                   border: "none",
//                   background: tab === "editor" ? "#fff" : "transparent",
//                   borderRadius: 10,
//                   padding: "8px 10px",
//                   fontWeight: 900,
//                   fontSize: 12,
//                   cursor: "pointer",
//                   border: tab === "editor" ? `1px solid ${UI.border}` : "1px solid transparent",
//                 }}
//               >
//                 Editori
//               </button>
//             </div>

//             <Btn variant="danger" onClick={() => setDangerOpen(true)}>
//               Fshij ofertën
//             </Btn>
//           </div>
//         </div>
//       </div>

//       {tab === "overview" ? (
//         <OfferOverview offer={offer} materials={materials} onUpdateOffer={onUpdateOffer} onOpenEditor={() => setTab("editor")} />
//       ) : (
//         <PVCEditor offer={offer} materials={materials} onUpdateOffer={onUpdateOffer} onBackToOverview={() => setTab("overview")} />
//       )}

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

// function OfferOverview({ offer, materials, onUpdateOffer, onOpenEditor }) {
//   const positions = offer.positions || [];
//   const offerTotal = positions.reduce((s, p) => s + (p.total || 0), 0);

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

//   return (
//     <div className="wrap">
//       <div className="overviewGrid">
//         <div style={{ border: `1px solid ${UI.border}`, borderRadius: 18, background: "#fff", boxShadow: UI.shadow, padding: 14, minWidth: 0 }}>
//           <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10, flexWrap: "wrap" }}>
//             <div>
//               <div style={{ fontSize: 12, color: UI.muted }}>Pozicionet</div>
//               <div style={{ fontSize: 14, fontWeight: 950 }}>{positions.length} gjithsej</div>
//             </div>
//             <Btn variant="primary" onClick={onOpenEditor}>
//               + Shto pozicion (hap editorin)
//             </Btn>
//           </div>

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

//           {positions.length === 0 ? (
//             <div style={{ marginTop: 12, padding: 14, borderRadius: 14, background: UI.soft, color: UI.muted, border: `1px dashed ${UI.border}` }}>
//               Ende pa pozicione. Hape Editorin dhe kliko <b>✔</b>.
//             </div>
//           ) : (
//             <div style={{ marginTop: 12, display: "grid", gap: 10 }}>
//               {positions.map((p, idx) => (
//                 <div
//                   key={p.id || idx}
//                   style={{
//                     border: `1px solid ${UI.border}`,
//                     borderRadius: 14,
//                     padding: 12,
//                     display: "flex",
//                     alignItems: "center",
//                     justifyContent: "space-between",
//                     gap: 12,
//                     flexWrap: "wrap",
//                   }}
//                 >
//                   <div style={{ minWidth: 0, flex: 1 }}>
//                     <div style={{ display: "flex", gap: 10, alignItems: "center", flexWrap: "wrap" }}>
//                       <div style={{ fontWeight: 950 }}>{p.name || `Pozicioni ${idx + 1}`}</div>
//                       <Pill tone="soft">{p.isDoor ? "Derë" : "Dritare"}</Pill>
//                       <Pill tone="soft">
//                         {p.frameW}×{(p.frameH || 0) + (p.extraBottomProfile || 0) + (p.hasRoll ? p.rollHeight || 0 : 0)} mm
//                       </Pill>
//                       <Pill tone="soft">Xhami: {p.glassTypeId}</Pill>
//                     </div>
//                     <div style={{ fontSize: 12, color: UI.muted, marginTop: 4 }}>
//                       Krahë: {p.sashes?.length || 0} • T-profile: {p.tProfiles?.length || 0}
//                       {p.shapeType === "sloped" ? ` • Irreg: M ${p.topLeftOffsetMm || 0} / D ${p.topRightOffsetMm || 0} mm` : ""}
//                     </div>
//                   </div>

//                   <div style={{ textAlign: "right", minWidth: 120 }}>
//                     <div style={{ fontSize: 12, color: UI.muted }}>Totali</div>
//                     <div style={{ fontSize: 16, fontWeight: 950 }}>€ {money(p.total)}</div>
//                   </div>
//                 </div>
//               ))}
//             </div>
//           )}
//         </div>

//         <div style={{ display: "grid", gap: 12, minWidth: 0 }}>
//           <div style={{ border: `1px solid ${UI.border}`, borderRadius: 18, background: "#fff", boxShadow: UI.shadow, padding: 14 }}>
//             <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10 }}>
//               <div>
//                 <div style={{ fontSize: 12, color: UI.muted }}>Parametrat e ofertës</div>
//                 <div style={{ fontSize: 14, fontWeight: 950 }}>Kontroll çmimi</div>
//               </div>
//               <Pill tone="blue">Live</Pill>
//             </div>

//             <div style={{ marginTop: 12, display: "grid", gap: 12 }}>
//               <Field label="Marzha (%)" hint="Përdoret nga editori për totalet">
//                 <TextInput type="number" value={offer.margin} onChange={(e) => onUpdateOffer({ margin: Number(e.target.value) || 0 })} />
//               </Field>

//               <Field label="Ngjyra">
//                 <Select value={offer.color} onChange={(e) => onUpdateOffer({ color: e.target.value })}>
//                   <option value="[BB] Bardhë-Bardhë">[BB] Bardhë-Bardhë</option>
//                   <option value="Antracit">Antracit</option>
//                   <option value="Golden Oak">Golden Oak</option>
//                 </Select>
//               </Field>

//               <Field label="Profili default">
//                 <Select value={offer.profileId} onChange={(e) => onUpdateOffer({ profileId: e.target.value })}>
//                   {materials.profiles.map((p) => (
//                     <option key={p.id} value={p.id}>
//                       {p.name} — € {money(p.pricePerM)}/m
//                     </option>
//                   ))}
//                 </Select>
//               </Field>

//               <Field label="Armatura default">
//                 <Select value={offer.ironId} onChange={(e) => onUpdateOffer({ ironId: e.target.value })}>
//                   {materials.irons.map((i) => (
//                     <option key={i.id} value={i.id}>
//                       {i.name} — € {money(i.pricePerM)}/m
//                     </option>
//                   ))}
//                 </Select>
//               </Field>

//               <div style={{ fontSize: 12, color: UI.muted, lineHeight: 1.45 }}>
//                 Default aktive: <b>{profileName}</b> • <b>{ironName}</b>
//               </div>
//             </div>
//           </div>

//           <div style={{ border: `1px solid ${UI.border}`, borderRadius: 18, background: "#fff", boxShadow: UI.shadow, padding: 14 }}>
//             <div style={{ fontSize: 12, color: UI.muted }}>Totali i ofertës</div>
//             <div style={{ fontSize: 28, fontWeight: 1000, marginTop: 2 }}>€ {money(offerTotal)}</div>
//             <div style={{ marginTop: 12, display: "grid", gap: 8 }}>
//               <div style={{ display: "flex", justifyContent: "space-between", fontSize: 13 }}>
//                 <span style={{ color: UI.muted }}>Pozicione</span>
//                 <span style={{ fontWeight: 900 }}>{positions.length}</span>
//               </div>
//               <div style={{ display: "flex", justifyContent: "space-between", fontSize: 13 }}>
//                 <span style={{ color: UI.muted }}>Përditësuar</span>
//                 <span style={{ fontWeight: 900 }}>{offer.updatedAt ? new Date(offer.updatedAt).toLocaleString() : "—"}</span>
//               </div>
//             </div>
//             <div style={{ marginTop: 12 }}>
//               <Btn variant="primary" onClick={onOpenEditor} style={{ width: "100%" }}>
//                 Hape editorin fullscreen →
//               </Btn>
//             </div>
//           </div>
//         </div>
//       </div>
//     </div>
//   );
// }

// /* ================== FULLSCREEN PVC EDITOR ================== */
// function PVCEditor({ offer, materials, onUpdateOffer, onBackToOverview }) {
//   const WORKSPACE_TOP = 78;
//   const LEFT_W = 76;
//   const RIGHT_W = 360;

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

//   const profile = useMemo(() => materials.profiles.find((p) => p.id === offer.profileId) || materials.profiles[0], [materials.profiles, offer.profileId]);
//   const iron = useMemo(() => materials.irons.find((i) => i.id === offer.ironId) || materials.irons[0], [materials.irons, offer.ironId]);

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

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

//   const currentGlass = useMemo(() => materials.glassTypes.find((g) => g.id === glassTypeId) || materials.glassTypes[0], [materials.glassTypes, glassTypeId]);

//   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 [extraBottomProfile, setExtraBottomProfile] = useState(0);

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

//   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");

//   const positions = offer.positions || [];

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

//   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 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 subtotal = profileCost + ironCost + glassCost;
//   const profit = (subtotal * margin) / 100;
//   const total = subtotal + profit;

//   const offerTotal = positions.reduce((s, p) => s + (p.total || 0), 0) + (frameExists ? total : 0);

//   const activeSegKey = `${activeSeg.col}-${activeSeg.row}`;
//   const activeSegHasStaticGlass = !!segmentsGlass[activeSegKey];

//   // ================== HANDLERS ==================
//   const handleSaveFrame = () => {
//     if (frameW < 300 || frameH < 300) return;
//     setFrameExists(true);
//     setSashes([]);
//     setSelectedSashId(null);
//     setTProfiles([]);
//     setSegmentsGlass({});
//     setActiveSeg({ col: 0, row: 0 });
//     setShapeType("rect");
//     setTopLeftOffset(0);
//     setTopRightOffset(0);
//     setFrameModal(false);
//   };

//   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 = () => {
//     if (tSide !== "middle" && (!tOffsetMm || tOffsetMm <= 0)) return alert("Vendos distancën në mm.");
//     const nextId = tProfiles.length > 0 ? Math.max(...tProfiles.map((t) => t.id)) + 1 : 1;

//     const newT = {
//       id: nextId,
//       orientation: tOrientation,
//       side: tSide,
//       offsetMm: tSide === "middle" ? null : tOffsetMm,
//     };

//     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");
//   };

//   const handleFinishPosition = () => {
//     if (!frameExists) return alert("Vendos kornizën.");

//     const newPos = {
//       id: uid(),
//       name: `Pozicioni ${positions.length + 1}`,
//       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,
//       createdAt: Date.now(),
//     };

//     onUpdateOffer({ positions: [...positions, newPos] });
//     resetEditorState();
//   };

//   // ===== helper for print =====
//   const buildCurrentPositionObject = () => {
//     if (!frameExists) return null;
//     return {
//       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,
//     };
//   };

//   // ===============================
//   // ✅ UPDATED: PREVIEW SVG = SAME AS EDITOR DESIGN
//   // ===============================
//   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);
//       // s += line(left, top, right, bottom, 0.55, 1.0);
//       // s += line(right, top, left, bottom, 0.55, 1.0);

//       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);
//       // s += line(left, apexY, right, bottom, 0.55, 1.0);
//       // s += line(right, apexY, left, bottom, 0.55, 1.0);
//     }

//     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);
//       // s += line(left, top, right, bottom, 0.5, 1.0);
//     }

//     return s;
//   };

//   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);
//     };

//     // T profiles -> bounds
//     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">`;

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

//     // roll + base
//     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);

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

//     // irregular top polygon
//     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" />`;
//     }

//     // segments + sashes/static glass
//     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;

//         // blocked if fully above sloped line
//         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);

//             // handle placement similar to canvas
//             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);
//           }
//         }
//       }
//     }

//     // T profiles (draw as thick bars)
//     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");
//     });

//     // dims
//     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 (kept, but you can ignore if you only print sketch) =====
//   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 ================== */
//   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 || [])];
//     const current = buildCurrentPositionObject();
//     if (current) list.push(current);
//     return list;
//   };

//   // ✅ NEW: Print only sketch (same as editor)
//   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 fullHeightMm = 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} × ${fullHeightMm} 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 fullHeightMm = 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} × ${fullHeightMm} 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 fullHeightMm = 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}×${fullHeightMm} 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 ==================
//   let scale = 1;
//   if (frameExists) {
//     const fullHeightMm = frameH + (extraBottomProfile || 0) + (hasRoll ? rollHeight : 0);
//     const sX = (editorW - 220) / frameW;
//     const sY = (editorH - 180) / fullHeightMm;
//     scale = Math.max(0.05, Math.min(sX, sY));
//   }

//   return (
//     <div style={{ width: "100%", padding: 12 }}>
//       <div
//         className="editorGrid"
//         style={{
//           ["--leftW"]: `${LEFT_W}px`,
//           ["--rightW"]: `${RIGHT_W}px`,
//           ["--topH"]: `${WORKSPACE_TOP}px`,
//         }}
//       >
//         {/* LEFT TOOLS */}
//         <div
//           className="leftTools"
//           style={{
//             background: "#fff",
//             border: `1px solid ${UI.border}`,
//             borderRadius: 18,
//             boxShadow: UI.shadow,
//             padding: 10,
//             display: "flex",
//             flexDirection: "column",
//             gap: 8,
//             alignItems: "center",
//             height: "100%",
//             position: "sticky",
//             top: WORKSPACE_TOP,
//           }}
//         >
//           <ToolBtn title="Korniza" onClick={() => setFrameModal(true)}>
//             <IconFrame />
//           </ToolBtn>

//           <ToolBtn title="Forma (irregulare)" onClick={() => frameExists && setShapeModal(true)} disabled={!frameExists}>
//             <IconIrregular />
//           </ToolBtn>

//           <ToolBtn title="Shto krah (Z)" onClick={handleAddPanelClick} disabled={!frameExists}>
//             <IconSash />
//           </ToolBtn>

//           <ToolBtn title="Nda vertikalisht (brenda pjesës)" onClick={handleSplitVertical} disabled={sashes.length === 0}>
//             <IconSplit />
//           </ToolBtn>

//           <ToolBtn title="Xhami ON/OFF në krahun e zgjedhur" onClick={handleToggleGlassOnSash} disabled={!selectedSashId}>
//             <IconGlass />
//           </ToolBtn>

//           <ToolBtn title="Xham statik në pjesën aktive" onClick={handleStaticGlassToggle} disabled={!frameExists} active={frameExists && activeSegHasStaticGlass}>
//             <IconStaticGlass />
//           </ToolBtn>

//           <ToolBtn title="Roletë" onClick={handleToggleRoll} disabled={!frameExists} active={frameExists && hasRoll}>
//             <IconRoll />
//           </ToolBtn>

//           <ToolBtn title="T-profile (vertikale / horizontale)" onClick={handleOpenTModal} disabled={!frameExists} active={frameExists && tProfiles.length > 0}>
//             <IconT />
//           </ToolBtn>

//           <ToolBtn title="Lloji i xhamit" onClick={() => setGlassModal(true)}>
//             <IconGlassType />
//           </ToolBtn>

//           <div style={{ marginTop: 6, width: "100%" }}>
//             <Btn variant="success" onClick={handleFinishPosition} style={{ width: "100%", borderRadius: 14, padding: "12px 10px" }}>
//               ✔
//             </Btn>
//           </div>

//           <div style={{ marginTop: "auto", width: "100%", display: "grid", gap: 8 }}>
//             <Btn variant="soft" onClick={onBackToOverview} style={{ width: "100%" }}>
//               ←
//             </Btn>
//           </div>
//         </div>

//         {/* CENTER CANVAS */}
//         <div
//           className="canvasCard"
//           style={{
//             background: "#fff",
//             border: `1px solid ${UI.border}`,
//             borderRadius: 18,
//             boxShadow: UI.shadow,
//             padding: 12,
//             height: "100%",
//             overflow: "hidden",
//             display: "flex",
//             flexDirection: "column",
//             gap: 10,
//             minWidth: 0,
//           }}
//         >
//           <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10, flexWrap: "wrap" }}>
//             <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap", minWidth: 0 }}>
//               <div style={{ fontWeight: 1000 }}>Editor PVC</div>
//               <Pill tone="soft">{offer.name}</Pill>
//               <Pill tone="blue">Marzha {margin}%</Pill>
//               <Pill tone="soft">Profil: {profile?.name}</Pill>
//               <Pill tone="soft">Arm: {iron?.name}</Pill>
//               <Pill tone="soft">Xham: {currentGlass?.name}</Pill>
//             </div>

//             <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
//               <Btn onClick={handlePrintSketch} style={{ padding: "10px 12px" }}>
//                 🖼️ Skicë
//               </Btn>
//               <Btn onClick={handlePrintOffer} style={{ padding: "10px 12px" }}>
//                 📄 Ofertë
//               </Btn>
//               <Btn onClick={handlePrintInvoice} style={{ padding: "10px 12px" }}>
//                 🧾 Faturë
//               </Btn>
//               <Btn onClick={handlePrintCutting} style={{ padding: "10px 12px" }}>
//                 ✂ Prerje
//               </Btn>
//             </div>
//           </div>

//           <div ref={canvasWrapRef} style={{ flex: 1, background: "#000", borderRadius: 14, overflow: "hidden", position: "relative" }}>
//             {!frameExists ? (
//               <svg width={editorW} height={editorH}>
//                 <text x={editorW / 2} y={editorH / 2} fill="#64748b" fontSize="14" textAnchor="middle">
//                   Kliko ▢ për të vendosur kornizën.
//                 </text>
//               </svg>
//             ) : (
//               (() => {
//                 const fullHeightMm = frameH + (extraBottomProfile || 0) + (hasRoll ? rollHeight : 0);
//                 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") {
//                     const offset = t.offsetMm || 0;
//                     let cy;
//                     if (t.side === "top") cy = originBodyY + offset * scale;
//                     else if (t.side === "bottom") cy = originBodyY + bodyPxH - offset * scale;
//                     else cy = originBodyY + bodyPxH / 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 = t.offsetMm || 0;
//                     let cx;
//                     if (t.side === "left") cx = originX + offset * scale;
//                     else if (t.side === "right") cx = originX + framePxW - offset * scale;
//                     else cx = originX + framePxW / 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 = 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 && <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" />

//                     {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}
//                       />
//                     )}

//                     <line x1={originX + framePxW + 40} y1={originY} x2={originX + framePxW + 40} y2={originY + fullHeightPx} stroke="#fef08a" strokeWidth={1} />
//                     <text x={originX + framePxW + 55} y={originY + fullHeightPx / 2} fill="#fef08a" fontSize="12">
//                       {fullHeightMm} mm
//                     </text>

//                     <line x1={originX} y1={originY + fullHeightPx + 40} x2={originX + framePxW} y2={originY + fullHeightPx + 40} stroke="#fef08a" strokeWidth={1} />
//                     <text x={originX + framePxW / 2} y={originY + fullHeightPx + 60} fill="#fef08a" fontSize="12" textAnchor="middle">
//                       {frameW} mm
//                     </text>

//                     {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} />;
//                       })()}

//                     {Array.from({ length: rows }).map((_, row) =>
//                       Array.from({ length: cols }).map((__, col) => {
//                         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"}
//                                     />
//                                     {renderOpening(sash.opening, sx, sy, sashW, sashH)}
//                                     <rect x={handleX} y={handleY} width={isTiltCenter ? 12 : 4} height={isTiltCenter ? 12 : 32} fill="#ffffff" rx={1} />
//                                   </g>
//                                 );
//                               })}

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

//                     {tVert.map((t) => {
//                       const half = tThickness / 2;
//                       return (
//                         <g key={`tv-${t.id}`}>
//                           <line x1={t.cx - half} y1={innerTop} x2={t.cx - half} y2={innerBottom} stroke="#ffffff" strokeWidth={2} />
//                           <line x1={t.cx + half} y1={innerTop} x2={t.cx + half} y2={innerBottom} stroke="#ffffff" strokeWidth={2} />
//                         </g>
//                       );
//                     })}

//                     {tHoriz.map((t) => {
//                       const half = tThickness / 2;
//                       return (
//                         <g key={`th-${t.id}`}>
//                           <line x1={innerLeft} y1={t.cy - half} x2={innerRight} y2={t.cy - half} stroke="#ffffff" strokeWidth={2} />
//                           <line x1={innerLeft} y1={t.cy + half} x2={innerRight} y2={t.cy + half} stroke="#ffffff" strokeWidth={2} />
//                         </g>
//                       );
//                     })}
//                   </svg>
//                 );
//               })()
//             )}
//           </div>
//         </div>

//         {/* RIGHT PANEL */}
//         <div
//           className="rightPanel"
//           style={{
//             background: "#fff",
//             border: `1px solid ${UI.border}`,
//             borderRadius: 18,
//             boxShadow: UI.shadow,
//             padding: 14,
//             height: "100%",
//             position: "sticky",
//             top: WORKSPACE_TOP,
//             overflow: "auto",
//             minWidth: 0,
//           }}
//         >
//           <div style={{ display: "grid", gap: 12 }}>
//             <div>
//               <div style={{ fontSize: 12, color: UI.muted }}>Oferta</div>
//               <div style={{ fontWeight: 950 }}>{offer.name}</div>
//               <div style={{ fontSize: 12, color: UI.muted, marginTop: 4 }}>Marzha: {margin}%</div>
//               <div style={{ fontSize: 12, color: UI.muted }}>
//                 Profili: {profile?.name} — € {money(profile?.pricePerM)}/m
//               </div>
//               <div style={{ fontSize: 12, color: UI.muted }}>
//                 Armatura: {iron?.name} — € {money(iron?.pricePerM)}/m
//               </div>
//               <div style={{ fontSize: 12, color: UI.muted }}>
//                 Xhami: {currentGlass?.name} — € {money(currentGlass?.pricePerM2)}/m²
//               </div>
//             </div>

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

//             <div>
//               <div style={{ fontSize: 12, color: UI.muted }}>Pozicionet ({positions.length})</div>
//               {positions.length === 0 ? (
//                 <div style={{ fontSize: 12, color: UI.muted }}>Ende pa pozicione të ruajtura.</div>
//               ) : (
//                 positions.map((p, i) => (
//                   <div key={p.id} style={{ border: `1px solid ${UI.border}`, borderRadius: 14, padding: 10, marginTop: 8, fontSize: 12 }}>
//                     <div style={{ fontWeight: 900 }}>{p.name || `Pozicioni ${i + 1}`}</div>
//                     <div style={{ color: UI.muted, marginTop: 2 }}>
//                       {p.frameW} × {(p.frameH || 0) + (p.extraBottomProfile || 0) + (p.hasRoll ? p.rollHeight || 0 : 0)} mm {p.isDoor ? "(Derë)" : "(Dritare)"}
//                     </div>
//                     {p.shapeType === "sloped" && (
//                       <div style={{ fontSize: 11, color: UI.muted, marginTop: 2 }}>
//                         Irreg: majtas {p.topLeftOffsetMm || 0} / djathtas {p.topRightOffsetMm || 0} mm
//                       </div>
//                     )}
//                     <div style={{ marginTop: 6, display: "flex", alignItems: "center", justifyContent: "space-between" }}>
//                       <span style={{ color: UI.muted }}>Totali</span>
//                       <b>€ {money(p.total)}</b>
//                     </div>
//                   </div>
//                 ))
//               )}
//             </div>

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

//             <div>
//               <div style={{ fontSize: 12, color: UI.muted }}>Pozicioni aktiv</div>
//               {frameExists ? (
//                 <>
//                   <div style={{ fontSize: 13, marginTop: 4 }}>
//                     {frameW} × {frameH + (extraBottomProfile || 0) + (hasRoll ? rollHeight : 0)} mm {isDoor ? "(Derë)" : "(Dritare)"}
//                   </div>
//                   {shapeType === "sloped" && (
//                     <div style={{ fontSize: 12, color: UI.muted, marginTop: 2 }}>
//                       Irreg: majtas {topLeftOffset || 0} / djathtas {topRightOffset || 0} mm (≈ {irregularAngleDeg}°)
//                     </div>
//                   )}
//                   {hasRoll && <div style={{ fontSize: 12, color: UI.muted }}>Roleta: {rollHeight} mm</div>}
//                   {extraBottomProfile > 0 && <div style={{ fontSize: 12, color: UI.muted }}>Profil poshtë: {extraBottomProfile} mm</div>}
//                   {tProfiles.length > 0 && <div style={{ fontSize: 12, color: UI.muted }}>T: {tProfiles.map((t) => `${t.orientation[0]}-${t.side}`).join(", ")}</div>}
//                   <div style={{ fontSize: 12, color: UI.muted }}>Perimetri: {perimeterM.toFixed(2)} m</div>
//                   <div style={{ fontSize: 12, color: UI.muted }}>Xham: {glassArea.toFixed(3)} m²</div>
//                 </>
//               ) : (
//                 <div style={{ fontSize: 12, color: UI.muted }}>Vendos kornizën për të filluar</div>
//               )}
//             </div>

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

//             <div style={{ display: "grid", gap: 8 }}>
//               <Row label="Profil" value={`€ ${money(profileCost)}`} />
//               <Row label="Armaturë" value={`€ ${money(ironCost)}`} />
//               <Row label="Xham" value={`€ ${money(glassCost)}`} />
//               <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 style={{ borderTop: `1px solid ${UI.border}` }} />

//             <div>
//               <div style={{ fontSize: 12, color: UI.muted }}>Totali i ofertës</div>
//               <div style={{ fontSize: 18, fontWeight: 1000, marginTop: 4 }}>€ {money(offerTotal)}</div>
//               <div style={{ fontSize: 12, color: UI.muted }}>(përfshin pozicionin aktiv)</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(Number(e.target.value) || 0)} />
//             </Field>
//             <Field label="Lartësia (mm)">
//               <TextInput type="number" value={frameH} onChange={(e) => setFrameH(Number(e.target.value) || 0)} />
//             </Field>
//             <Field label="Profil poshtë shtesë (mm)">
//               <TextInput type="number" value={extraBottomProfile} onChange={(e) => setExtraBottomProfile(Number(e.target.value) || 0)} />
//             </Field>
//             <Field label="Lartësia e roletës (mm)">
//               <TextInput type="number" value={rollHeight} onChange={(e) => setRollHeight(Number(e.target.value) || 0)} />
//             </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>

//             <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>

//             <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(Number(e.target.value) || 0)} />
//                 </Field>
//                 <Field label="Offset sipër djathtas (mm)">
//                   <TextInput type="number" value={topRightOffset} onChange={(e) => setTopRightOffset(Number(e.target.value) || 0)} />
//                 </Field>
//                 <div style={{ fontSize: 11, color: UI.muted, lineHeight: 1.5 }}>
//                   • Më shumë mm = pika e sipërme zbret më poshtë.
//                   <br />• Diferenca majtas / djathtas krijon këndin.
//                   <br />• 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"],
//             ].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: 800,
//                   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(Number(e.target.value) || 0)}
//                 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: 900 }}>
//                   {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>
//       </div>
//     </div>
//   );
// }

// /* ================== Tool Button ================== */
// function ToolBtn({ children, onClick, disabled, active, title }) {
//   return (
//     <button
//       title={title}
//       onClick={disabled ? undefined : onClick}
//       style={{
//         width: 50,
//         height: 50,
//         borderRadius: 14,
//         border: `1px solid ${UI.border}`,
//         background: disabled ? "#f1f5f9" : active ? "#dbeafe" : "#fff",
//         cursor: disabled ? "not-allowed" : "pointer",
//         fontSize: 16,
//         fontWeight: 900,
//         color: UI.ink,
//         display: "grid",
//         placeItems: "center",
//         boxShadow: active ? "0 10px 24px rgba(59,130,246,.18)" : "none",
//       }}
//     >
//       {children}
//     </button>
//   );
// }

// /* ================== Right panel rows ================== */
// 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>
//   );
// }






















// import React, { useEffect, useMemo, useState } from "react";
// import { loadMaterials, loadOffers, migrateOffers, saveMaterials, saveOffers } from "./utils/storage.js";
// import { uid } from "./utils/helpers.js";
// import { UI } from "./constants/pvc.js";

// import OffersDashboard from "./pages/OffersDashboard.jsx";
// import MaterialsManager from "./pages/MaterialsManager.jsx";
// import OfferWorkspace from "./pages/OfferWorkspace.jsx";

// export default function App() {
//   const [materials, setMaterials] = useState(() => loadMaterials());

//   const [offers, setOffers] = useState(() => {
//     const existing = loadOffers();
//     if (existing.length) return migrateOffers(existing, loadMaterials());
//     return [
//       {
//         id: uid(),
//         name: "Oferta 01",
//         margin: 20,
//         color: "[BB] Bardhë-Bardhë",
//         profileId: loadMaterials().profiles[0]?.id || "profile-1",
//         ironId: loadMaterials().irons[0]?.id || "iron-1",
//         createdAt: Date.now(),
//         updatedAt: Date.now(),
//         positions: [],
//       },
//     ];
//   });

//   const [route, setRoute] = useState({ page: "dashboard", offerId: null });

//   useEffect(() => saveOffers(offers), [offers]);
//   useEffect(() => saveMaterials(materials), [materials]);

//   // keep default profile/iron valid if removed from materials
//   useEffect(() => {
//     const profIds = new Set(materials.profiles.map((p) => p.id));
//     const ironIds = new Set(materials.irons.map((i) => i.id));
//     const defP = materials.profiles[0]?.id;
//     const defI = materials.irons[0]?.id;
//     if (!defP || !defI) return;

//     setOffers((prev) =>
//       prev.map((o) => ({
//         ...o,
//         profileId: profIds.has(o.profileId) ? o.profileId : defP,
//         ironId: ironIds.has(o.ironId) ? o.ironId : defI,
//       }))
//     );
//   }, [materials.profiles, materials.irons]);

//   const selectedOffer = useMemo(() => offers.find((o) => o.id === route.offerId) || null, [offers, route.offerId]);

//   const upsertOffer = (offerId, patch) => {
//     setOffers((prev) => prev.map((o) => (o.id === offerId ? { ...o, ...patch, updatedAt: Date.now() } : o)));
//   };

//   const addOffer = (offer) => {
//     const defProfileId = materials.profiles[0]?.id || "profile-1";
//     const defIronId = materials.irons[0]?.id || "iron-1";

//     setOffers((prev) => [
//       {
//         ...offer,
//         id: uid(),
//         profileId: offer.profileId || defProfileId,
//         ironId: offer.ironId || defIronId,
//         createdAt: Date.now(),
//         updatedAt: Date.now(),
//         positions: [],
//       },
//       ...prev,
//     ]);
//   };

//   const deleteOffer = (offerId) => {
//     setOffers((prev) => prev.filter((o) => o.id !== offerId));
//     setRoute({ page: "dashboard", offerId: null });
//   };

//   return (
//     <div style={{ minHeight: "100vh", background: UI.bg, color: UI.ink }}>
//       {/* global CSS that used to live inside the single file */}
//       <style>{`
//         *{box-sizing:border-box}
//         .wrap{max-width:1240px;margin:0 auto;padding:18px}
//         .offersGrid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px}
//         @media (max-width: 1024px){.offersGrid{grid-template-columns:repeat(2,minmax(0,1fr))}}
//         @media (max-width: 640px){.offersGrid{grid-template-columns:1fr}}
//         .overviewGrid{display:grid;grid-template-columns:1.2fr .8fr;gap:12px;align-items:start}
//         @media (max-width: 980px){.overviewGrid{grid-template-columns:1fr}}
//         .stickyHeader{position:sticky;top:0;z-index:20;background:rgba(255,255,255,.9);backdrop-filter:blur(10px);border-bottom:1px solid ${UI.border};}
//         .editorGrid{display:grid;gap:12px;align-items:stretch;height:calc(100vh - var(--topH) - 24px);grid-template-columns:var(--leftW) 1fr var(--rightW);}
//         @media (max-width: 1100px){
//           .editorGrid{grid-template-columns:1fr;height:auto}
//           .leftTools{position:sticky;top:var(--topH);display:flex;flex-direction:row;gap:10px;align-items:center;overflow:auto;white-space:nowrap}
//           .rightPanel{position:static;height:auto}
//           .canvasCard{min-height:55vh}
//         }
//         @media (max-width: 560px){
//           .leftTools{gap:8px}
//         }
//       `}</style>

//       {route.page === "dashboard" ? (
//         <OffersDashboard
//           offers={offers}
//           materials={materials}
//           onOpenOffer={(id) => setRoute({ page: "offer", offerId: id })}
//           onCreateOffer={addOffer}
//           onOpenMaterials={() => setRoute({ page: "materials", offerId: null })}
//         />
//       ) : route.page === "materials" ? (
//         <MaterialsManager
//           materials={materials}
//           setMaterials={setMaterials}
//           onBack={() => setRoute({ page: "dashboard", offerId: null })}
//         />
//       ) : (
//         <OfferWorkspace
//           offer={selectedOffer}
//           materials={materials}
//           onBack={() => setRoute({ page: "dashboard", offerId: null })}
//           onOpenMaterials={() => setRoute({ page: "materials", offerId: null })}
//           onUpdateOffer={(patch) => selectedOffer && upsertOffer(selectedOffer.id, patch)}
//           onDeleteOffer={() => selectedOffer && deleteOffer(selectedOffer.id)}
//         />
//       )}
//     </div>
//   );
// }













import React, { useEffect, useMemo, useRef, useState } from "react";
import { uid } from "./utils/helpers.js";
import { UI } from "./constants/pvc.js";

import OffersDashboard from "./pages/OffersDashboard.jsx";
import MaterialsManager from "./pages/MaterialsManager.jsx";
import OfferWorkspace from "./pages/OfferWorkspace.jsx";

import { fetchAllMaterials, ensureSeedMaterials } from "./utils/materialsDb.js";
import { createOffer as dbCreateOffer, deleteOffer as dbDeleteOffer, fetchOffers, updateOffer as dbUpdateOffer } from "./utils/offersDb.js";

/**
 * DB-backed version of the app:
 * - Loads materials + offers from Laravel API (/api/*)
 * - Seeds DEFAULT_MATERIALS into DB if tables are empty
 * - Persists offer changes to DB (debounced)
 */
export default function App() {
  const [route, setRoute] = useState({ page: "dashboard", offerId: null }); // dashboard | materials | workspace
  const [loading, setLoading] = useState(true);
  const [err, setErr] = useState(null);

const [materials, setMaterials] = useState({
  profiles: [],
  irons: [],
  glassTypes: [],
  accessories: [],
  doorPanels: [],
});


  const [offers, setOffers] = useState([]);

  // Debounce map per offer id
  const saveTimersRef = useRef(new Map());

  // ---------- Initial load ----------
  useEffect(() => {
    let mounted = true;
    (async () => {
      try {
        setLoading(true);
        setErr(null);

        // 1) materials
        const mats0 = await fetchAllMaterials();
        const mats = await ensureSeedMaterials(mats0); // seeds defaults if empty
        if (!mounted) return;
        setMaterials(mats);

        // 2) offers
        const list = await fetchOffers();
        if (!mounted) return;

        // If no offers in DB, create one default so the UI isn't empty
        if (!list.length) {
          const first = await dbCreateOffer({
            id: uid(),
            name: "Oferta 01",
            description: "",
            margin: 20,
            color: "[BB] Bardhë-Bardhë",
            profileId: mats.profiles[0]?.id || "",
            ironId: mats.irons[0]?.id || "",
            updatedAt: new Date().toISOString(),
            positions: [],
          });
          setOffers([first]);
        } else {
          setOffers(list);
        }
      } catch (e) {
        console.error(e);
        if (mounted) setErr(e?.message || "Failed to load data");
      } finally {
        if (mounted) setLoading(false);
      }
    })();
    return () => {
      mounted = false;
    };
  }, []);

  // ---------- Helpers ----------
  const selectedOffer = useMemo(() => {
    if (route.page !== "workspace") return null;
    return offers.find((o) => String(o.id) === String(route.offerId)) || null;
  }, [offers, route]);

  const persistOfferDebounced = (offer) => {
    const id = String(offer.id);

    // Clear existing timer
    const timers = saveTimersRef.current;
    if (timers.has(id)) clearTimeout(timers.get(id));

    const t = setTimeout(async () => {
      try {
const fresh = await dbUpdateOffer(offer);
        setOffers((prev) => prev.map((x) => (String(x.id) === id ? fresh : x)));
      } catch (e) {
        console.error("Offer save failed:", e);
        // keep UI responsive; optionally show a toast later
      }
    }, 450);

    timers.set(id, t);
  };

  const upsertOffer = (offerId, patch) => {
    setOffers((prev) => {
      const next = prev.map((o) => {
        if (String(o.id) !== String(offerId)) return o;
        const merged = { ...o, ...patch, updatedAt: new Date().toISOString() };
        // If patch includes positions, keep them
        if (patch?.positions) merged.positions = patch.positions;
        // Persist after state update
        persistOfferDebounced(merged);
        return merged;
      });
      return next;
    });
  };

  const createOffer = async (draft) => {
    const uiDraft = {
      id: uid(),
      positions: [],
      ...draft,
    };

    try {
      const created = await dbCreateOffer(uiDraft);
      setOffers((prev) => [created, ...prev]);
      setRoute({ page: "workspace", offerId: created.id });
    } catch (e) {
      console.error(e);
      setErr(e?.message || "Create offer failed");
    }
  };

  const deleteOffer = async (offerId) => {
    const id = String(offerId);
    try {
      await dbDeleteOffer(id);
      setOffers((prev) => prev.filter((o) => String(o.id) !== id));
      setRoute({ page: "dashboard", offerId: null });
    } catch (e) {
      console.error(e);
      setErr(e?.message || "Delete failed");
    }
  };

  // ---------- UI ----------
  const shell = (children) => (
    <div style={{ minHeight: "100vh", background: "#fff" }}>
      {children}
    </div>
  );

  if (loading) {
    return shell(
      <div style={{ padding: 24, fontFamily: "Inter, system-ui, Arial" }}>
        <div style={{ fontWeight: 800, color: UI.ink, fontSize: 18 }}>Loading…</div>
        <div style={{ color: UI.muted, marginTop: 6 }}>Fetching data from DB.</div>
      </div>
    );
  }

  if (err) {
    return shell(
      <div style={{ padding: 24, fontFamily: "Inter, system-ui, Arial" }}>
        <div style={{ fontWeight: 800, color: "#b91c1c", fontSize: 18 }}>Error</div>
        <div style={{ color: UI.ink, marginTop: 8 }}>{err}</div>
        <button
          onClick={() => window.location.reload()}
          style={{
            marginTop: 16,
            padding: "10px 12px",
            borderRadius: 12,
            border: `1px solid ${UI.border}`,
            background: "#fff",
            cursor: "pointer",
            fontWeight: 700,
          }}
        >
          Reload
        </button>
      </div>
    );
  }

  return (
    <div>
      {route.page === "dashboard" ? (
        <OffersDashboard
          offers={offers}
          materials={materials}
          onOpenOffer={(id) => setRoute({ page: "workspace", offerId: id })}
          onCreateOffer={createOffer}
          onOpenMaterials={() => setRoute({ page: "materials", offerId: null })}
          logoSrc="/logo.png"
          userLabel="User"
        />
      ) : route.page === "materials" ? (
        <MaterialsManager
          materials={materials}
          setMaterials={setMaterials}
          onBack={() => setRoute({ page: "dashboard", offerId: null })}
          logoSrc="/logo.png"
          userLabel="User"
        />
      ) : (
        <OfferWorkspace
          offer={selectedOffer}
          materials={materials}
          onBack={() => setRoute({ page: "dashboard", offerId: null })}
          onOpenMaterials={() => setRoute({ page: "materials", offerId: null })}
          onUpdateOffer={(patch) => selectedOffer && upsertOffer(selectedOffer.id, patch)}
          onDeleteOffer={() => selectedOffer && deleteOffer(selectedOffer.id)}
        />
      )}
    </div>
  );
}
