// src/components/editor/SvgPreview.js

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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