// Photo markup canvas — draw, pin, measure directly on uploaded photos
// Annotations: { id, type: 'draw'|'pin'|'measure', color, points: [{x,y}...], data: {...} }

const MARKUP_COLORS = [
  { id: 'amber', hex: 'oklch(65% 0.14 60)', label: 'Repair' },
  { id: 'red',   hex: 'oklch(55% 0.2 28)',  label: 'Damage' },
  { id: 'blue',  hex: 'oklch(55% 0.16 245)', label: 'Measure' },
  { id: 'green', hex: 'oklch(55% 0.14 150)', label: 'Note' },
];

const TOOLS = [
  { id: 'draw',    label: 'Draw',    icon: 'Pencil' },
  { id: 'pin',     label: 'Pin',     icon: 'Pin' },
  { id: 'measure', label: 'Measure', icon: 'Ruler' },
];

function MarkupCanvas({ photo, annotations, setAnnotations }) {
  const [tool, setTool] = React.useState('pin');
  const [color, setColor] = React.useState('amber');
  const [drawing, setDrawing] = React.useState(null); // in-progress annotation
  const [editingPin, setEditingPin] = React.useState(null);
  const stageRef = React.useRef(null);

  const getRelPos = (e) => {
    const r = stageRef.current.getBoundingClientRect();
    const t = e.touches?.[0] || e.changedTouches?.[0] || e;
    return {
      x: Math.max(0, Math.min(1, (t.clientX - r.left) / r.width)),
      y: Math.max(0, Math.min(1, (t.clientY - r.top) / r.height)),
    };
  };

  const nextPinNum = () => {
    const pins = annotations.filter(a => a.type === 'pin');
    return pins.length + 1;
  };

  const onPointerDown = (e) => {
    if (editingPin) return;
    e.preventDefault();
    const pos = getRelPos(e);
    const id = 'a' + Date.now() + Math.random().toString(36).slice(2, 6);
    const c = MARKUP_COLORS.find(c => c.id === color).hex;
    if (tool === 'draw') {
      setDrawing({ id, type: 'draw', color: c, points: [pos] });
    } else if (tool === 'pin') {
      const num = nextPinNum();
      const newPin = { id, type: 'pin', color: c, points: [pos], data: { num, label: '', dim: '' } };
      setAnnotations([...annotations, newPin]);
      setEditingPin(id);
    } else if (tool === 'measure') {
      setDrawing({ id, type: 'measure', color: c, points: [pos, pos], data: { length: '' } });
    }
  };

  const onPointerMove = (e) => {
    if (!drawing) return;
    e.preventDefault();
    const pos = getRelPos(e);
    if (drawing.type === 'draw') {
      setDrawing({ ...drawing, points: [...drawing.points, pos] });
    } else if (drawing.type === 'measure') {
      setDrawing({ ...drawing, points: [drawing.points[0], pos] });
    }
  };

  const onPointerUp = () => {
    if (!drawing) return;
    setAnnotations([...annotations, drawing]);
    setDrawing(null);
  };

  const undo = () => {
    setAnnotations(annotations.slice(0, -1));
  };
  const clear = () => setAnnotations([]);

  const deleteAnnotation = (id) => {
    setAnnotations(annotations.filter(a => a.id !== id));
    if (editingPin === id) setEditingPin(null);
  };

  const updateAnnotation = (id, patch) => {
    setAnnotations(annotations.map(a => a.id === id ? { ...a, data: { ...a.data, ...patch } } : a));
  };

  const pathFromPoints = (pts) => {
    if (!pts.length) return '';
    return pts.map((p, i) => `${i === 0 ? 'M' : 'L'} ${p.x * 100} ${p.y * 100}`).join(' ');
  };

  const allAnnos = drawing ? [...annotations, drawing] : annotations;
  const editingPinData = annotations.find(a => a.id === editingPin);

  return (
    <div className="markup">
      <div className="markup-stage" ref={stageRef}>
        <img src={photo} className="photo" alt="Cabinet" draggable={false}/>
        <svg
          className="overlay"
          viewBox="0 0 100 100"
          preserveAspectRatio="none"
          onMouseDown={onPointerDown}
          onMouseMove={onPointerMove}
          onMouseUp={onPointerUp}
          onMouseLeave={onPointerUp}
          onTouchStart={onPointerDown}
          onTouchMove={onPointerMove}
          onTouchEnd={onPointerUp}
        >
          {allAnnos.map(a => {
            if (a.type === 'draw') {
              return (
                <path key={a.id}
                  d={pathFromPoints(a.points)}
                  stroke={a.color} strokeWidth="0.6" fill="none"
                  strokeLinecap="round" strokeLinejoin="round"
                  vectorEffect="non-scaling-stroke"
                  style={{ strokeWidth: 3 }}
                />
              );
            }
            if (a.type === 'measure') {
              const [p1, p2] = a.points;
              const mx = (p1.x + p2.x) / 2 * 100;
              const my = (p1.y + p2.y) / 2 * 100;
              return (
                <g key={a.id}>
                  <line x1={p1.x * 100} y1={p1.y * 100} x2={p2.x * 100} y2={p2.y * 100}
                        stroke={a.color} strokeWidth="3" vectorEffect="non-scaling-stroke" />
                  <circle cx={p1.x * 100} cy={p1.y * 100} r="0.8" fill={a.color} vectorEffect="non-scaling-stroke" style={{r: 4}}/>
                  <circle cx={p2.x * 100} cy={p2.y * 100} r="0.8" fill={a.color} vectorEffect="non-scaling-stroke" style={{r: 4}}/>
                  {a.data?.length && (
                    <foreignObject x={mx - 10} y={my - 3} width="20" height="6" style={{overflow: 'visible'}}>
                      <div style={{
                        background: a.color, color: '#fff',
                        fontFamily: 'JetBrains Mono, monospace',
                        fontSize: 11, padding: '2px 6px', borderRadius: 3,
                        display: 'inline-block', whiteSpace: 'nowrap',
                        transform: 'translate(-50%, -50%)',
                        position: 'absolute', left: '50%', top: '50%',
                      }}>{a.data.length}</div>
                    </foreignObject>
                  )}
                </g>
              );
            }
            return null;
          })}
        </svg>

        {/* Pins rendered as absolute DOM for crisp typography */}
        {annotations.filter(a => a.type === 'pin').map(a => {
          const p = a.points[0];
          return (
            <div key={a.id} style={{
              position: 'absolute',
              left: `${p.x * 100}%`,
              top: `${p.y * 100}%`,
              transform: 'translate(-50%, -50%)',
              pointerEvents: 'auto',
            }}>
              <button
                onClick={(e) => { e.stopPropagation(); setEditingPin(a.id); }}
                style={{
                  width: 32, height: 32,
                  borderRadius: '50%',
                  background: a.color,
                  border: '2px solid white',
                  color: 'white',
                  fontFamily: 'JetBrains Mono, monospace',
                  fontSize: 13, fontWeight: 600,
                  cursor: 'pointer',
                  boxShadow: '0 2px 8px rgba(0,0,0,0.3)',
                  display: 'grid', placeItems: 'center',
                  padding: 0,
                }}
              >{a.data.num}</button>
              {a.data.dim && (
                <div style={{
                  position: 'absolute',
                  top: '100%', left: '50%',
                  transform: 'translateX(-50%)',
                  marginTop: 4,
                  background: 'rgba(0,0,0,0.85)',
                  color: 'white',
                  fontFamily: 'JetBrains Mono, monospace',
                  fontSize: 10,
                  padding: '2px 6px',
                  borderRadius: 3,
                  whiteSpace: 'nowrap',
                }}>{a.data.dim}</div>
              )}
            </div>
          );
        })}

        {/* Pin editor popover */}
        {editingPinData && (
          <div
            onClick={(e) => e.stopPropagation()}
            style={{
              position: 'absolute',
              left: `${editingPinData.points[0].x * 100}%`,
              top: `${editingPinData.points[0].y * 100}%`,
              transform: `translate(${editingPinData.points[0].x > 0.5 ? '-105%' : '5%'}, ${editingPinData.points[0].y > 0.6 ? '-105%' : '5%'})`,
              background: 'white',
              borderRadius: 10,
              padding: 14,
              boxShadow: '0 10px 30px rgba(0,0,0,0.25)',
              width: 240,
              zIndex: 10,
            }}
          >
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
              <div style={{
                width: 22, height: 22, borderRadius: '50%',
                background: editingPinData.color, color: 'white',
                display: 'grid', placeItems: 'center',
                fontFamily: 'JetBrains Mono', fontSize: 11, fontWeight: 600,
              }}>{editingPinData.data.num}</div>
              <div style={{ fontSize: 13, fontWeight: 500, flex: 1 }}>Pin details</div>
              <button onClick={() => setEditingPin(null)}
                style={{ border: 'none', background: 'transparent', cursor: 'pointer', padding: 4, color: 'var(--ink-soft)' }}>
                <Icon.X/>
              </button>
            </div>
            <input
              autoFocus
              placeholder="Describe the issue…"
              value={editingPinData.data.label}
              onChange={(e) => updateAnnotation(editingPinData.id, { label: e.target.value })}
              style={{ width: '100%', padding: '8px 10px', fontSize: 13, border: '1px solid var(--rule)', borderRadius: 6, marginBottom: 8, fontFamily: 'inherit' }}
            />
            <input
              placeholder="Dimensions (e.g. 24×30)"
              value={editingPinData.data.dim}
              onChange={(e) => updateAnnotation(editingPinData.id, { dim: e.target.value })}
              style={{ width: '100%', padding: '8px 10px', fontSize: 13, border: '1px solid var(--rule)', borderRadius: 6, fontFamily: 'JetBrains Mono, monospace' }}
            />
            <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 10 }}>
              <button onClick={() => { deleteAnnotation(editingPinData.id); }}
                className="btn danger" style={{ padding: '6px 10px', fontSize: 12 }}>
                <Icon.Trash/> Remove
              </button>
              <button onClick={() => setEditingPin(null)}
                className="btn primary" style={{ padding: '6px 14px', fontSize: 12 }}>Done</button>
            </div>
          </div>
        )}
      </div>

      <div className="tool-palette">
        <div style={{ fontSize: 11, fontWeight: 500, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--ink-faint)', fontFamily: 'var(--mono)' }}>
          Tool
        </div>
        <div className="tool-row">
          {TOOLS.map(t => {
            const TIcon = Icon[t.icon];
            return (
              <button key={t.id}
                className={'tool-btn' + (tool === t.id ? ' active' : '')}
                onClick={() => setTool(t.id)}>
                <TIcon/>
                {t.label}
              </button>
            );
          })}
        </div>

        <div style={{ fontSize: 11, fontWeight: 500, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--ink-faint)', fontFamily: 'var(--mono)', marginTop: 4 }}>
          Color
        </div>
        <div className="color-swatches">
          {MARKUP_COLORS.map(c => (
            <button key={c.id}
              className={color === c.id ? 'active' : ''}
              onClick={() => setColor(c.id)}
              style={{ background: c.hex }}
              title={c.label}
            />
          ))}
        </div>

        <div className="tool-row" style={{ marginTop: 4 }}>
          <button className="btn secondary" style={{ flex: 1, justifyContent: 'center' }} onClick={undo} disabled={!annotations.length}>
            <Icon.Undo/> Undo
          </button>
          <button className="btn ghost" style={{ flex: 1, justifyContent: 'center' }} onClick={clear} disabled={!annotations.length}>
            Clear all
          </button>
        </div>

        <div className="markup-legend">
          <div style={{ fontSize: 11, fontWeight: 500, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--ink-faint)', fontFamily: 'var(--mono)', marginBottom: 6 }}>
            Pinned items ({annotations.filter(a => a.type === 'pin').length})
          </div>
          {annotations.filter(a => a.type === 'pin').length === 0 && (
            <div style={{ fontSize: 12, color: 'var(--ink-faint)', padding: '8px 6px' }}>
              Drop pins on the photo to call out specific repair locations.
            </div>
          )}
          {annotations.filter(a => a.type === 'pin').map(a => (
            <div key={a.id} className="legend-item">
              <div className="num" style={{ background: a.color }}>{a.data.num}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div className="label" style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                  {a.data.label || <span style={{ color: 'var(--ink-faint)' }}>Untitled</span>}
                </div>
                {a.data.dim && <div className="dim">{a.data.dim}</div>}
              </div>
              <button className="btn ghost" onClick={() => setEditingPin(a.id)} style={{ padding: 4 }}>
                <Icon.Pencil/>
              </button>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { MarkupCanvas });
