/* Shared across both redesign directions: icons, roof canvas, editor hook. */
const { useState: uS, useRef: uR, useMemo: uM, useCallback: uCb, useEffect: uEf } = React;

/* ---- Lucide-style icons ------------------------------------------------ */
const IP = {
  cursor:'<path d="M4 3l7 17 2.5-6.5L20 11 4 3z"/>',
  polygon:'<path d="M12 3l8 5v8l-8 5-8-5V8z"/>',
  line:'<circle cx="5" cy="19" r="2"/><circle cx="19" cy="5" r="2"/><path d="M6.5 17.5l11-11"/>',
  point:'<circle cx="12" cy="12" r="3.2"/><path d="M12 3v3M12 18v3M3 12h3M18 12h3"/>',
  undo:'<path d="M9 14L4 9l5-5"/><path d="M4 9h10a6 6 0 0 1 0 12H8"/>',
  redo:'<path d="M15 14l5-5-5-5"/><path d="M20 9H10a6 6 0 0 0 0 12h6"/>',
  magnet:'<path d="M6 3v7a6 6 0 0 0 12 0V3"/><path d="M6 3h4v6H6zM14 3h4v6h-4z"/>',
  trace:'<path d="M3 17l6-6 4 4 8-8"/><circle cx="21" cy="7" r="1.6"/>',
  image:'<rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="9" cy="9" r="1.6"/><path d="M21 15l-5-5L5 21"/>',
  zoomIn:'<circle cx="11" cy="11" r="7"/><path d="M21 21l-4.3-4.3M11 8v6M8 11h6"/>',
  zoomOut:'<circle cx="11" cy="11" r="7"/><path d="M21 21l-4.3-4.3M8 11h6"/>',
  fit:'<path d="M8 3H5a2 2 0 0 0-2 2v3M16 3h3a2 2 0 0 1 2 2v3M21 16v3a2 2 0 0 1-2 2h-3M3 16v3a2 2 0 0 0 2 2h3"/>',
  trash:'<path d="M3 6h18M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/>',
  download:'<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 10l5 5 5-5M12 15V3"/>',
  arrowLeft:'<path d="M19 12H5M11 6l-6 6 6 6"/>',
  arrowRight:'<path d="M5 12h14M13 6l6 6-6 6"/>',
  check:'<path d="M20 6L9 17l-5-5"/>',
  alert:'<path d="M10.3 3.9 1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0z"/><path d="M12 9v4M12 17h.01"/>',
  x:'<path d="M18 6 6 18M6 6l12 12"/>',
  info:'<circle cx="12" cy="12" r="9"/><path d="M12 11v5M12 8h.01"/>',
  command:'<path d="M18 3a3 3 0 0 0-3 3v12a3 3 0 1 0 3-3H6a3 3 0 1 0 3 3V6a3 3 0 1 0-3 3h12a3 3 0 0 0 3-3z"/>',
  layers:'<path d="M12 3l9 5-9 5-9-5 9-5z"/><path d="M3 13l9 5 9-5"/>',
  ruler:'<path d="M3 15l6 6 12-12-6-6L3 15z"/><path d="M9 9l1.5 1.5M12 6l1.5 1.5M6 12l1.5 1.5"/>',
  chevron:'<path d="M9 6l6 6-6 6"/>',
  sun:'<circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"/>',
  route:'<circle cx="6" cy="19" r="2.5"/><circle cx="18" cy="5" r="2.5"/><path d="M8.5 18.5l7-11"/>',
  save:'<path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><path d="M17 21v-8H7v8M7 3v5h8"/>',
};
function Icon({ n, s = 18, style, cls }) {
  return React.createElement("svg", { width:s, height:s, viewBox:"0 0 24 24", fill:"none",
    stroke:"currentColor", strokeWidth:1.7, strokeLinecap:"round", strokeLinejoin:"round",
    style, className:cls, dangerouslySetInnerHTML:{ __html: IP[n]||"" } });
}

/* ---- editor logic hook (shared by both skins) -------------------------- */
function useEditor() {
  const [features, setFeatures] = uS(TK.FEATURES);
  const [tool, setTool] = uS({ mode:"select" });
  const [selId, setSelId] = uS("pl-main");
  const [snap, setSnap] = uS(true);
  const [trace, setTrace] = uS(false);
  const [globalPitch, setGlobalPitch] = uS(TK.GLOBAL_PITCH);
  const [waste, setWaste] = uS(TK.WASTE);
  const [route, setRoute] = uS("verify");
  const [tab, setTab] = uS("measure");

  const summary = uM(() => TK.buildSummary(features, globalPitch, waste), [features, globalPitch, waste]);
  const boq = uM(() => TK.buildBOQ(summary), [summary]);
  const selected = uM(() => features.find(f => f.id === selId) || null, [features, selId]);

  const reclass = (id, t) => setFeatures(fs => fs.map(f => f.id===id ? {...f, feature_type:t} : f));
  const patch = (id, p) => setFeatures(fs => fs.map(f => f.id===id ? {...f, ...p} : f));
  const del = (id) => { setFeatures(fs => fs.filter(f => f.id!==id)); setSelId(null); };

  return { features, tool, setTool, selId, setSelId, snap, setSnap, trace, setTrace,
    globalPitch, setGlobalPitch, waste, setWaste, route, setRoute, tab, setTab,
    summary, boq, selected, reclass, patch, del };
}

/* ---- roof canvas (themeable) ------------------------------------------- */
function path(pts, close) { return pts.map((p,i)=>(i?"L":"M")+p[0]+" "+p[1]).join(" ") + (close?" Z":""); }

function RoofCanvas({ ed, theme }) {
  const dark = theme === "dark";
  const { features, selId, setSelId, tool, trace } = ed;
  const view = TK.VIEW;
  const lineW = trace ? 1.4 : 1;

  const planes = features.filter(f => f.geometry_type==="Polygon");
  const lines = features.filter(f => f.geometry_type==="LineString");
  const points = features.filter(f => f.geometry_type==="Point");
  const lc = (t) => dark ? (TK.LINE_META[t]?.onDark || "#ccc") : (TK.LINE_META[t]?.color || "#999");
  const pick = (id) => (e) => { if (tool.mode==="select"){ e.stopPropagation(); setSelId(id); } };

  return (
    <svg viewBox={`0 0 ${view.w} ${view.h}`} width="100%" height="100%" preserveAspectRatio="xMidYMid meet"
      style={{ display:"block", cursor: tool.mode==="select" ? "default":"crosshair" }}
      onClick={() => { if (tool.mode==="select") setSelId(null); }}>
      <defs>
        <linearGradient id={`tile-${theme}`} x1="0" y1="0" x2="1" y2="1">
          <stop offset="0" stopColor={dark?"#16352a":"#8d8478"}/><stop offset="1" stopColor={dark?"#0f2a20":"#6f675b"}/>
        </linearGradient>
        <linearGradient id={`metal-${theme}`} x1="0" y1="0" x2="1" y2="1">
          <stop offset="0" stopColor={dark?"#1b3d31":"#9aa09c"}/><stop offset="1" stopColor={dark?"#143025":"#7c837e"}/>
        </linearGradient>
        <filter id={`tex-${theme}`}><feTurbulence type="fractalNoise" baseFrequency="0.85" numOctaves="2" result="n"/>
          <feColorMatrix in="n" type="saturate" values="0"/><feComponentTransfer><feFuncA type="linear" slope={dark?"0.04":"0.07"}/></feComponentTransfer>
          <feComposite operator="over" in2="SourceGraphic"/></filter>
        <pattern id={`grid-${theme}`} width="40" height="40" patternUnits="userSpaceOnUse">
          <path d="M40 0H0V40" fill="none" stroke={dark?"rgba(255,255,255,0.05)":"rgba(26,42,34,0.05)"} strokeWidth="1"/>
        </pattern>
      </defs>

      {/* surface */}
      <rect x="0" y="0" width={view.w} height={view.h} fill={dark?"#0c231b":"#2c3b2f"}/>
      {!dark && <rect x="0" y="0" width={view.w} height={view.h} fill="#2a3a2d" filter={`url(#tex-${theme})`} opacity="0.7"/>}
      {dark && <rect x="0" y="0" width={view.w} height={view.h} fill={`url(#grid-${theme})`}/>}
      {!dark && (<g opacity="0.5">
        <rect x="40" y="40" width="150" height="90" rx="6" fill="#3a4636"/>
        <rect x="840" y="500" width="130" height="120" rx="6" fill="#36422f"/>
        <path d="M-20 640 Q 300 600 1020 660" stroke="#54503f" strokeWidth="22" fill="none" opacity="0.5"/>
      </g>)}

      {/* roof shadow */}
      <path d={path(TK.OUTLINE, true)} transform="translate(6,10)" fill="rgba(0,0,0,0.32)"/>

      {/* planes */}
      {planes.map(p => {
        const sel = p.id===selId;
        const metal = p.feature_type==="roof_plane";
        return <path key={p.id} d={path(p.geom, true)}
          fill={dark ? "rgba(244,185,66,0.045)" : `url(#${metal?"metal":"tile"}-${theme})`}
          stroke={sel ? "#FFB54C" : dark ? "rgba(244,185,66,0.28)" : "rgba(18,26,20,0.4)"}
          strokeWidth={sel ? 2.4 : 0.8} style={{ cursor: tool.mode==="select"?"pointer":"crosshair" }}
          onClick={pick(p.id)}/>;
      })}

      {/* lines */}
      {lines.map(l => {
        const m = TK.LINE_META[l.feature_type]; const sel = l.id===selId;
        return (
          <g key={l.id} onClick={pick(l.id)} style={{ cursor: tool.mode==="select"?"pointer":"crosshair" }}>
            <path d={path(l.geom)} stroke="rgba(8,20,14,0.5)" strokeWidth={(sel?5:3.4)*lineW} fill="none" strokeLinecap="round" strokeLinejoin="round"/>
            {sel && <path d={path(l.geom)} stroke="#FFB54C" strokeWidth={9*lineW} fill="none" strokeLinecap="round" opacity="0.34"/>}
            <path d={path(l.geom)} stroke={lc(l.feature_type)} strokeWidth={(sel?3:2.2)*lineW} fill="none"
              strokeLinecap="round" strokeLinejoin="round" strokeDasharray={m.dashed ? "7 4.5":undefined}/>
            {l.geom.map((v,i) => <circle key={i} cx={v[0]} cy={v[1]} r={(sel?3.4:2.2)*lineW} fill={sel?"#FFB54C":"#fff"} stroke={sel?"#1A2A22":"rgba(8,20,14,0.6)"} strokeWidth="0.9"/>)}
          </g>
        );
      })}

      {/* points */}
      {points.map(p => {
        const sel = p.id===selId; const g = TK.POINT_META[p.feature_type]?.glyph;
        return (
          <g key={p.id} transform={`translate(${p.geom[0]},${p.geom[1]})`} onClick={pick(p.id)} style={{ cursor: tool.mode==="select"?"pointer":"crosshair" }}>
            <rect x="-10" y="-10" width="20" height="20" rx="5" fill={sel?"#FFB54C":"rgba(8,20,14,0.8)"} stroke={sel?"#1A2A22":"rgba(255,255,255,0.85)"} strokeWidth="1.2"/>
            <g transform="translate(-6,-6) scale(0.5)" stroke={sel?"#1A2A22":"#fff"} strokeWidth="3" fill="none" strokeLinecap="round" strokeLinejoin="round"
               dangerouslySetInnerHTML={{ __html:
                 g==="chimney" ? '<path d="M3 21V10l9-6 9 6v11"/><path d="M9 21v-6h6v6"/>'
                 : g==="skylight" ? '<rect x="3" y="3" width="18" height="18" rx="2"/><path d="M3 12h18M12 3v18"/>'
                 : g==="solar" ? '<rect x="2" y="5" width="20" height="14" rx="1"/><path d="M2 10h20M2 14h20M9 5v14M15 5v14"/>'
                 : g==="fan" ? '<circle cx="12" cy="12" r="2"/><path d="M12 10V4M14 12h6M12 14v6M10 12H4"/>'
                 : g==="antenna" ? '<path d="M12 3v18M12 3l5 5M12 3l-5 5"/>'
                 : g==="flag" ? '<path d="M5 3v18M5 4h12l-3 4 3 4H5"/>'
                 : '<circle cx="12" cy="12" r="6"/>' }}/>
          </g>
        );
      })}
    </svg>
  );
}

/* shared measure fields list for rails */
function lineRows(summary) {
  return TK.LINE_ORDER.map(k => ({ k, label: TK.LINE_META[k].label, color: TK.LINE_META[k].color, dashed: TK.LINE_META[k].dashed, v: summary.lin[k] }))
    .filter(r => r.v > 0.4);
}
function fmt(n, d=1){ return Number(n).toLocaleString("en-AU",{minimumFractionDigits:d,maximumFractionDigits:d}); }

Object.assign(window, { Icon, useEditor, RoofCanvas, lineRows, fmt, svgPath: path });
