// T-Shirt design editor: drag, resize via corner handles, rotate, snap, color invert.

const { useState, useEffect, useRef, useMemo, useCallback } = React;

// Convert a percent-based design item (x,y,w,h in %) to absolute SVG coords
// given a print zone rect. Items are stored as percent of the print zone so
// the same data can render in both editor and PDF preview.
function pctToAbs(item, zone) {
  return NordicrewGeometry.pctToAbs(item, zone);
}

// Compute mm size (the editor is in viewBox px). We say the print zone in
// real life equals the configured printW × printH mm.
function pxToMm(item, zoneCfg) {
  return {
    xMm: Math.round((item.x / 100) * zoneCfg.printW),
    yMm: Math.round((item.y / 100) * zoneCfg.printH),
    wMm: Math.round((item.w / 100) * zoneCfg.printW),
    hMm: Math.round((item.h / 100) * zoneCfg.printH),
  };
}

function DesignItem({ item, zoneRect, selected, onSelect, onChange, viewportSize, snap, locked, customLib }) {
  const aspectRatio = item.aspectRatio || getLogoAspectRatio(item.logoId, item.customText, customLib);
  const displayItem = NordicrewGeometry.normalizeItemAspect(item, zoneRect, aspectRatio);
  const abs = pctToAbs(displayItem, zoneRect);
  const handleSize = 14;
  const ref = useRef(null);
  const dragRef = useRef(null);
  const mirrorTransform = `scale(${item.flipX ? -1 : 1}, ${item.flipY ? -1 : 1})`;

  const startInteraction = (e, mode, corner) => {
    if (locked) return;
    e.stopPropagation();
    e.preventDefault();
    onSelect(item.id);
    const svg = ref.current.ownerSVGElement;
    const startPoint = NordicrewGeometry.pointerToSvg(svg, e);
    const start = NordicrewGeometry.normalizeItemAspect({ ...item, aspectRatio }, zoneRect, aspectRatio);
    dragRef.current = { startPoint, start, mode, corner };

    const onMove = (ev) => {
      const point = NordicrewGeometry.pointerToSvg(svg, ev);
      const deltaSvg = { x: point.x - startPoint.x, y: point.y - startPoint.y };
      let next = start;
      if (mode === 'move') {
        next = NordicrewGeometry.moveItemByDelta({ item: start, zoneRect, deltaSvg, aspectRatio, snap });
      } else if (mode === 'resize') {
        next = NordicrewGeometry.resizeItemFromCorner({ item: start, zoneRect, corner, deltaSvg, aspectRatio, snap });
      } else if (mode === 'rotate') {
        next = NordicrewGeometry.rotateItemTowardPoint({ item: start, zoneRect, pointSvg: point, snap });
      }
      onChange(item.id, next);
    };
    const onUp = () => {
      window.removeEventListener('mousemove', onMove);
      window.removeEventListener('mouseup', onUp);
    };
    window.addEventListener('mousemove', onMove);
    window.addEventListener('mouseup', onUp);
  };

  return (
    <g ref={ref} transform={`translate(${abs.x}, ${abs.y}) rotate(${displayItem.rotation || 0})`} style={{ cursor: locked ? 'default' : 'move' }}>
      <g transform={`translate(${-abs.w/2}, ${-abs.h/2})`} onMouseDown={(e) => startInteraction(e, 'move')} style={{ cursor: locked ? 'default' : 'move' }}>
        <rect width={abs.w} height={abs.h} fill="transparent" pointerEvents="all"/>
        <foreignObject x="0" y="0" width={abs.w} height={abs.h} style={{ pointerEvents: 'none' }}>
          <div style={{
            width: '100%',
            height: '100%',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            pointerEvents: 'none',
            color: item.color,
            transform: mirrorTransform,
            transformOrigin: '50% 50%',
          }}>
            <LogoRender logoId={item.logoId} color={item.color} customText={item.customText} customLib={customLib}/>
          </div>
        </foreignObject>
      </g>
      {selected && !locked && (
        <g>
          <rect x={-abs.w/2} y={-abs.h/2} width={abs.w} height={abs.h}
                fill="none" stroke="var(--accent, #00ff9c)" strokeWidth="1.5"/>
          {/* corners */}
          {[
            { x: -abs.w/2, y: -abs.h/2, c: 'nw', cursor: 'nwse-resize' },
            { x:  abs.w/2, y: -abs.h/2, c: 'ne', cursor: 'nesw-resize' },
            { x: -abs.w/2, y:  abs.h/2, c: 'sw', cursor: 'nesw-resize' },
            { x:  abs.w/2, y:  abs.h/2, c: 'se', cursor: 'nwse-resize' },
          ].map(p => (
            <rect key={p.c} x={p.x - handleSize/2} y={p.y - handleSize/2}
                  width={handleSize} height={handleSize}
                  fill="var(--bg, #0c0e10)" stroke="var(--accent, #00ff9c)" strokeWidth="2"
                  style={{ cursor: p.cursor }}
                  onMouseDown={(e) => startInteraction(e, 'resize', p.c)}/>
          ))}
          {/* rotate */}
          <line x1={0} y1={-abs.h/2} x2={0} y2={-abs.h/2 - 24} stroke="var(--accent, #00ff9c)" strokeWidth="1.5"/>
          <circle cx={0} cy={-abs.h/2 - 30} r={7}
                  fill="var(--bg, #0c0e10)" stroke="var(--accent, #00ff9c)" strokeWidth="2"
                  style={{ cursor: 'grab' }}
                  onMouseDown={(e) => startInteraction(e, 'rotate')}/>
        </g>
      )}
    </g>
  );
}

function clamp(v, lo, hi) { return NordicrewGeometry.clamp(v, lo, hi); }

// Print canvas — renders shirt + zone + items
function ShirtCanvas({ shirt, zoneId, designs, onChange, selectedId, onSelect, snap, locked, hideZoneOutline, customLib }) {
  const zoneRect = ZONE_RECTS[zoneId];
  const ZoneShirt =
    zoneId === 'front' ? <ShirtFront shirtColor={shirt.color} showZoneOutline={!hideZoneOutline}>
      {designs.map(d => (
        <DesignItem key={d.id} item={d} zoneRect={zoneRect} selected={selectedId === d.id}
                    onSelect={onSelect} onChange={onChange} snap={snap} locked={locked} customLib={customLib}/>
      ))}
    </ShirtFront>
    : zoneId === 'back' ? <ShirtBack shirtColor={shirt.color} showZoneOutline={!hideZoneOutline}>
      {designs.map(d => (
        <DesignItem key={d.id} item={d} zoneRect={zoneRect} selected={selectedId === d.id}
                    onSelect={onSelect} onChange={onChange} snap={snap} locked={locked} customLib={customLib}/>
      ))}
    </ShirtBack>
    : <ShirtSleeve shirtColor={shirt.color} showZoneOutline={!hideZoneOutline}>
      {designs.map(d => (
        <DesignItem key={d.id} item={d} zoneRect={{ ...ZONE_RECTS.sleeve, x: ZONE_RECTS.sleeve.x + 30, y: ZONE_RECTS.sleeve.y + 20 }}
                    selected={selectedId === d.id} onSelect={onSelect} onChange={onChange} snap={snap} locked={locked} customLib={customLib}/>
      ))}
    </ShirtSleeve>;

  return (
    <div className="shirt-canvas" onMouseDown={() => onSelect && onSelect(null)}>
      {ZoneShirt}
    </div>
  );
}

Object.assign(window, { DesignItem, ShirtCanvas, pctToAbs, pxToMm, clamp });
