import { useEffect, useRef, useState } from 'react';
import { Star, Lock, Eye, Plus } from 'lucide-react';
import { REGIONS, regionForPiece } from '@/lib/canvasDemo';

// Neutral vertical design canvas with direct manipulation (move / resize / rotate).
// Coordinates are NORMALISED (0..1) so the master design is cover-independent.
export default function UniversalCanvas({ pieces, selectedId, focalId, onSelect, onChange, onCommit, showRegions = true, readOnly = false, advanced = false }) {
  const ref = useRef(null);
  const drag = useRef(null);
  const [, force] = useState(0);

  const sorted = [...(Array.isArray(pieces) ? pieces : [])].sort((a, b) => (a.order ?? 0) - (b.order ?? 0));

  useEffect(() => {
    const move = (e) => {
      const d = drag.current;
      if (!d || !ref.current) return;
      const rect = ref.current.getBoundingClientRect();
      if (d.mode === 'move') {
        const cx = clamp(d.cx + (e.clientX - d.startX) / rect.width, 0.03, 0.97);
        const cy = clamp(d.cy + (e.clientY - d.startY) / rect.height, 0.03, 0.97);
        updatePiece(d.id, { cx, cy }, true);
      } else if (d.mode === 'resize') {
        const w = clamp(d.w + (e.clientX - d.startX) / rect.width, 0.06, 0.98);
        const h = clamp(d.h + (e.clientY - d.startY) / rect.height, 0.06, 0.98);
        updatePiece(d.id, { w, h }, true);
      } else if (d.mode === 'rotate') {
        const cxp = rect.left + d.cx * rect.width;
        const cyp = rect.top + d.cy * rect.height;
        const ang = Math.atan2(e.clientY - cyp, e.clientX - cxp) * 180 / Math.PI + 90;
        const rotation = Math.round(d.rotation + (ang - d.startAngle));
        updatePiece(d.id, { rotation }, true);
      }
    };
    const up = () => {
      if (drag.current) { onCommit?.(); drag.current = null; force(x => x + 1); }
      window.removeEventListener('pointermove', move);
      window.removeEventListener('pointerup', up);
    };
    if (drag.current) {
      window.addEventListener('pointermove', move);
      window.addEventListener('pointerup', up);
    }
    return () => { window.removeEventListener('pointermove', move); window.removeEventListener('pointerup', up); };
  }, [pieces, onCommit]);

  const updatePiece = (id, patch, live) => {
    const next = pieces.map(p => p.id === id ? { ...p, ...patch } : p);
    onChange?.(next, live);
  };

  const begin = (e, p, mode) => {
    if (readOnly || p.locked) { onSelect?.(p.id); return; }
    e.stopPropagation();
    onSelect?.(p.id);
    const start = mode === 'rotate' ? null : null;
    drag.current = { mode, id: p.id, startX: e.clientX, startY: e.clientY, cx: p.cx, cy: p.cy, w: p.w, h: p.h, rotation: p.rotation };
    if (mode === 'rotate') {
      const rect = ref.current.getBoundingClientRect();
      const cxp = rect.left + p.cx * rect.width;
      const cyp = rect.top + p.cy * rect.height;
      drag.current.startAngle = Math.atan2(e.clientY - cyp, e.clientX - cxp) * 180 / Math.PI + 90;
    }
    force(x => x + 1);
  };

  return (
    <div ref={ref} className="viewport-grid relative mx-auto aspect-[3/4.4] w-full max-w-[440px] overflow-hidden rounded-2xl border border-white/[0.07]">
      {/* region guides */}
      {showRegions && (
        <>
          <div className="pointer-events-none absolute inset-x-0 top-0 h-[32%] border-b border-dashed border-cyan-400/10" />
          <div className="pointer-events-none absolute inset-x-0 bottom-0 h-[34%] border-t border-dashed border-cyan-400/10" />
          <div className="pointer-events-none absolute left-1/2 top-0 bottom-0 w-px -translate-x-1/2 bg-cyan-400/15" />
          {REGIONS.map(([k, label]) => {
            const pos = { main_focal: 'left-1/2 top-[40%]', upper: 'left-1/2 top-2', lower: 'left-1/2 bottom-2', background: 'left-2 top-1/2', border: 'right-2 top-1/2', wrap: 'left-2 bottom-2' }[k];
            return <span key={k} className={`pointer-events-none absolute -translate-x-1/2 -translate-y-1/2 text-[8px] font-medium uppercase tracking-wider text-slate-600 ${pos}`}>{label.replace(' area', '')}</span>;
          })}
        </>
      )}

      {/* safe master boundary */}
      <div className="pointer-events-none absolute inset-[3%] rounded-xl border border-dashed border-cyan-400/20" />

      {sorted.length === 0 ? (
        <div className="absolute inset-0 grid place-items-center p-6 text-center">
          <div>
            <p className="font-heading text-base font-semibold text-white">Start with an image, drawing or idea</p>
            <p className="mx-auto mt-1.5 max-w-[16rem] text-xs text-slate-400">Build the design first. Choose the prosthetic cover afterward.</p>
          </div>
        </div>
      ) : (
        sorted.filter(p => p.visible !== false).map(p => {
          const selected = p.id === selectedId && !readOnly;
          const isFocal = p.id === focalId;
          return (
            <div key={p.id} onPointerDown={e => begin(e, p, 'move')}
              className={`absolute touch-none select-none ${selected ? 'cursor-move' : 'cursor-grab'}`}
              style={{ left: `${p.cx * 100}%`, top: `${p.cy * 100}%`, width: `${p.w * 100}%`, height: `${p.h * 100}%`, transform: `translate(-50%,-50%) rotate(${p.rotation || 0}deg)${p.mirrored ? ' scaleX(-1)' : ''}`, zIndex: p.order ?? 0 }}>
              <img src={p.src} alt={p.name} draggable={false} className={`h-full w-full object-contain ${isFocal ? 'drop-shadow-[0_0_10px_rgba(34,211,238,0.7)]' : ''} ${selected ? 'ring-2 ring-cyan-400' : ''}`} />
              {isFocal && <span className="absolute -top-2 -left-2 grid h-5 w-5 place-items-center rounded-full border border-cyan-300 bg-cyan-400/30 text-cyan-100"><Star size={11} fill="currentColor" /></span>}
              {p.locked && <span className="absolute -top-2 -right-2 grid h-5 w-5 place-items-center rounded-full border border-white/20 bg-black/60 text-slate-300"><Lock size={10} /></span>}
              {selected && !readOnly && (
                <>
                  <span onPointerDown={e => begin(e, p, 'rotate')} className="absolute left-1/2 -top-7 -translate-x-1/2 cursor-grab rounded-full border border-cyan-400/60 bg-cyan-400/20 text-cyan-100 text-[10px] grid h-5 w-5 place-items-center">↻</span>
                  <span onPointerDown={e => begin(e, p, 'resize')} className="absolute -bottom-2 -right-2 h-4 w-4 cursor-nwse-resize rounded-sm border border-cyan-400/70 bg-cyan-400/30" />
                  <span className="absolute -bottom-2 -left-2 h-4 w-4 rounded-sm border border-white/30 bg-black/50" />
                  <span className="absolute -top-2 -right-2 h-4 w-4 rounded-sm border border-white/30 bg-black/50" />
                  <span className="absolute -top-2 -left-2 h-4 w-4 rounded-sm border border-white/30 bg-black/50" />
                </>
              )}
            </div>
          );
        })
      )}

      {advanced && selectedId && (() => {
        const p = pieces.find(x => x.id === selectedId);
        return p ? <span className="absolute right-2 top-2 rounded border border-white/10 bg-black/50 px-2 py-1 text-[9px] text-slate-300 mono">U {p.cx.toFixed(2)} · V {p.cy.toFixed(2)} · W {p.w.toFixed(2)} · H {p.h.toFixed(2)} · {p.rotation || 0}° · {regionForPiece(p)}</span> : null;
      })()}

      {pieces?.length > 0 && !readOnly && (
        <span className="pointer-events-none absolute left-2 bottom-2 rounded border border-amber-400/30 bg-amber-400/10 px-2 py-1 text-[9px] text-amber-100 backdrop-blur">Adaptation preview — final surface fitting requires the LimbForge Geometry Engine</span>
      )}
    </div>
  );
}

const clamp = (n, min, max) => Math.min(max, Math.max(min, n));