/* Movement Cube — uses the actual logo with clickable hotspots over the diamonds.
   Each hotspot is a free-form quad: 4 corner points (top, right, bottom, left)
   in % of the logo image. Drag any corner independently, or drag the body to
   move the whole shape. */

const { useState, useEffect, useRef } = React;

// Corners are stored as: <id>_t = [x,y] for top, _r right, _b bottom, _l left.
// Defaults form rough diamond shapes around each logo diamond.
const DEFAULT_HOTSPOTS = /*EDITMODE-BEGIN*/{
  "showOutlines": false,
  "reset_t":  [37, 14], "reset_r":  [41.5, 18], "reset_b":  [37, 22], "reset_l":  [32.5, 18],
  "rebuild_t":[50, 3.5],"rebuild_r":[53, 7.5], "rebuild_b":[50, 11.5],"rebuild_l":[47, 7.5],
  "restore_t":[63, 14], "restore_r":[67.5, 18],"restore_b":[63, 22], "restore_l":[58.5, 18],
  "prolozone_t":[50, 22],"prolozone_r":[54.5, 27],"prolozone_b":[50, 32],"prolozone_l":[45.5, 27]
}/*EDITMODE-END*/;

const CORNERS = ["t", "r", "b", "l"]; // top, right, bottom, left

function LogoCube({ onSelect, focused, focusId, tweaks, setTweak }) {
  const [hover, setHover] = useState(null);
  const [selected, setSelected] = useState(null);
  const wrapRef = useRef(null);
  const [drag, setDrag] = useState(null);

  // Edit mode locked off — clicks trigger transition
  const editMode = false;

  const HOTSPOTS = [
    { id: "reset",     label: "Reset",     num: "01", color: "#3aa0e0" },
    { id: "rebuild",   label: "Rebuild",   num: "02", color: "#e63a52" },
    { id: "restore",   label: "Restore",   num: "03", color: "#3aa0e0" },
    { id: "prolozone", label: "Prolozone", num: "04", color: "#a855f7" },
  ].map(h => ({
    ...h,
    pts: { t: tweaks[`${h.id}_t`], r: tweaks[`${h.id}_r`],
           b: tweaks[`${h.id}_b`], l: tweaks[`${h.id}_l`] },
  }));

  function rectPct() {
    const r = wrapRef.current?.getBoundingClientRect();
    return r ? { wPx: r.width, hPx: r.height, left: r.left, top: r.top } : null;
  }

  useEffect(() => {
    if (!drag) return;
    function onMove(e) {
      const rect = rectPct();
      if (!rect) return;
      const dxPct = ((e.clientX - drag.startX) / rect.wPx) * 100;
      const dyPct = ((e.clientY - drag.startY) / rect.hPx) * 100;
      if (drag.mode === "move-corner") {
        const np = [round(drag.origPt[0] + dxPct), round(drag.origPt[1] + dyPct)];
        setTweak({ [`${drag.id}_${drag.corner}`]: np });
      } else if (drag.mode === "move-all") {
        const edits = {};
        for (const c of CORNERS) {
          const op = drag.origPts[c];
          edits[`${drag.id}_${c}`] = [round(op[0] + dxPct), round(op[1] + dyPct)];
        }
        setTweak(edits);
      }
    }
    function onUp() { setDrag(null); }
    window.addEventListener('mousemove', onMove);
    window.addEventListener('mouseup', onUp);
    return () => {
      window.removeEventListener('mousemove', onMove);
      window.removeEventListener('mouseup', onUp);
    };
  }, [drag]);

  function round(n) { return Math.round(n * 10) / 10; }

  function startMoveAll(e, h) {
    if (!editMode) return;
    if (e.target.classList.contains('hot-corner')) return;
    e.preventDefault(); e.stopPropagation();
    setSelected(h.id);
    setDrag({
      mode: "move-all", id: h.id,
      startX: e.clientX, startY: e.clientY,
      origPts: { t: [...h.pts.t], r: [...h.pts.r], b: [...h.pts.b], l: [...h.pts.l] },
    });
  }

  function startMoveCorner(e, h, corner) {
    e.preventDefault(); e.stopPropagation();
    setSelected(h.id);
    setDrag({
      mode: "move-corner", id: h.id, corner,
      startX: e.clientX, startY: e.clientY,
      origPt: [...h.pts[corner]],
    });
  }

  return (
    <div className={"logo-stage " + (focused ? "focused" : "")}>
      <div className="logo-tilt-wrap">
        <div className="logo-img-wrap" ref={wrapRef}
             onMouseDown={(e) => { if (editMode && e.target === e.currentTarget) setSelected(null); }}>
          <img src="assets/logo.png" alt="Movement Cube" className="logo-img" draggable="false" />

          {/* SVG overlay for the quads — paths + corner handles */}
          <svg className="hot-svg" viewBox="0 0 100 100" preserveAspectRatio="none">
            {HOTSPOTS.map(h => {
              const isSelected = selected === h.id && editMode;
              const isHover = hover === h.id;
              const isFocused = focusId === h.id;
              const d = `M ${h.pts.t[0]} ${h.pts.t[1]} L ${h.pts.r[0]} ${h.pts.r[1]} L ${h.pts.b[0]} ${h.pts.b[1]} L ${h.pts.l[0]} ${h.pts.l[1]} Z`;
              return (
                <g key={h.id}
                   className={"hot-quad "
                     + (isSelected ? "selected " : "")
                     + (isHover ? "hover " : "")
                     + (isFocused ? "focused " : "")
                     + (editMode ? "outlined " : "")
                   }
                   style={{ '--hot-color': h.color }}>
                  <path
                    d={d}
                    className="hot-quad-fill"
                    onMouseDown={(e) => {
                      if (editMode) startMoveAll(e, h);
                      else {
                        const cx = (h.pts.t[0] + h.pts.r[0] + h.pts.b[0] + h.pts.l[0]) / 4;
                        const cy = (h.pts.t[1] + h.pts.r[1] + h.pts.b[1] + h.pts.l[1]) / 4;
                        // Convert from cube image % to viewport %
                        const wrap = wrapRef.current;
                        if (wrap) {
                          const rect = wrap.getBoundingClientRect();
                          const vx = ((rect.left + (cx/100) * rect.width) / window.innerWidth) * 100;
                          const vy = ((rect.top + (cy/100) * rect.height) / window.innerHeight) * 100;
                          onSelect(h.id, [vx, vy]);
                        } else {
                          onSelect(h.id, [50, 50]);
                        }
                      }
                    }}
                    onMouseEnter={() => setHover(h.id)}
                    onMouseLeave={() => setHover(null)}
                  />
                </g>
              );
            })}
          </svg>

          {/* Hover labels — positioned at quad centroid */}
          {HOTSPOTS.map(h => {
            const cx = (h.pts.t[0] + h.pts.r[0] + h.pts.b[0] + h.pts.l[0]) / 4;
            const cy = (h.pts.t[1] + h.pts.r[1] + h.pts.b[1] + h.pts.l[1]) / 4;
            return (
              <div key={h.id + "-lbl"} className={"hot-label-float " + (hover === h.id ? "show " : "")}
                   style={{ left: `${cx}%`, top: `${cy}%` }}>
                <span className="hot-num">{h.num}</span>
                <span className="hot-name">{h.label}</span>
              </div>
            );
          })}

          {/* Corner handles overlay (only for selected hotspot in edit mode) */}
          {HOTSPOTS.map(h => {
            const isSelected = selected === h.id && editMode;
            if (!isSelected) return null;
            return (
              <React.Fragment key={h.id + "-handles"}>
                {CORNERS.map(c => (
                  <span
                    key={c}
                    className={`hot-corner hot-corner-${c}`}
                    style={{
                      left: `${h.pts[c][0]}%`, top: `${h.pts[c][1]}%`,
                      '--hot-color': h.color,
                    }}
                    onMouseDown={(e) => startMoveCorner(e, h, c)}
                    title={`Drag ${c} corner`}
                  ></span>
                ))}
              </React.Fragment>
            );
          })}
        </div>
      </div>
    </div>
  );
}

window.LogoCube = LogoCube;
window.DEFAULT_HOTSPOTS = DEFAULT_HOTSPOTS;
