// CSS Clip-Path Generator — choose presets or drag custom polygon points with live preview.

window.TOOL_HANDLERS['css-clip-path'] = function CssClipPathTool() {
  const PRESETS = {
    Triangle:   { type: 'polygon', points: [[50,0],[0,100],[100,100]] },
    Rectangle:  { type: 'polygon', points: [[0,0],[100,0],[100,100],[0,100]] },
    Pentagon:   { type: 'polygon', points: [[50,0],[100,38],[82,100],[18,100],[0,38]] },
    Hexagon:    { type: 'polygon', points: [[50,0],[100,25],[100,75],[50,100],[0,75],[0,25]] },
    Circle:     { type: 'circle' },
    Ellipse:    { type: 'ellipse' },
    Star:       { type: 'polygon', points: [[50,0],[61,35],[98,35],[68,57],[79,91],[50,70],[21,91],[32,57],[2,35],[39,35]] },
    Arrow:      { type: 'polygon', points: [[40,0],[40,20],[100,20],[100,80],[40,80],[40,100],[0,50]] },
    Cross:      { type: 'polygon', points: [[35,0],[65,0],[65,35],[100,35],[100,65],[65,65],[65,100],[35,100],[35,65],[0,65],[0,35],[35,35]] },
    Rhombus:    { type: 'polygon', points: [[50,0],[100,50],[50,100],[0,50]] },
    Message:    { type: 'polygon', points: [[0,0],[100,0],[100,75],[75,75],[75,100],[50,75],[0,75]] },
  };

  const [activePreset, setActivePreset] = React.useState('Triangle');
  const [shapeType, setShapeType] = React.useState('polygon');
  const [points, setPoints] = React.useState([[50,0],[0,100],[100,100]]);
  const [customMode, setCustomMode] = React.useState(false);
  const [draggingIdx, setDraggingIdx] = React.useState(-1);
  const [copied, setCopied] = React.useState(false);
  const previewRef = React.useRef(null);

  const selectPreset = (name) => {
    const preset = PRESETS[name];
    setActivePreset(name);
    setCustomMode(false);
    if (preset.type === 'polygon') {
      setShapeType('polygon');
      setPoints(preset.points.map(p => [...p]));
    } else {
      setShapeType(preset.type);
      setPoints([]);
    }
  };

  const enterCustom = () => {
    setCustomMode(true);
    setActivePreset('');
    setShapeType('polygon');
    if (points.length === 0) {
      setPoints([[25,25],[75,25],[75,75],[25,75]]);
    }
  };

  // Build clip-path CSS
  const getClipPath = () => {
    if (shapeType === 'circle') return 'circle(50% at 50% 50%)';
    if (shapeType === 'ellipse') return 'ellipse(50% 40% at 50% 50%)';
    if (points.length === 0) return 'none';
    return 'polygon(' + points.map(([x, y]) => `${x}% ${y}%`).join(', ') + ')';
  };

  const clipPath = getClipPath();
  const cssText = `clip-path: ${clipPath};`;

  const copyCSS = () => {
    navigator.clipboard.writeText(cssText);
    setCopied(true);
    setTimeout(() => setCopied(false), 1500);
  };

  // Drag handlers
  const getRelativePos = (e) => {
    const box = previewRef.current;
    if (!box) return [0, 0];
    const rect = box.getBoundingClientRect();
    const x = Math.max(0, Math.min(100, ((e.clientX - rect.left) / rect.width) * 100));
    const y = Math.max(0, Math.min(100, ((e.clientY - rect.top) / rect.height) * 100));
    return [Math.round(x), Math.round(y)];
  };

  const onPointDown = (idx, e) => {
    e.preventDefault();
    e.stopPropagation();
    setDraggingIdx(idx);

    const onMove = (ev) => {
      const [x, y] = getRelativePos(ev);
      setPoints(prev => prev.map((p, i) => i === idx ? [x, y] : p));
    };

    const onUp = () => {
      setDraggingIdx(-1);
      window.removeEventListener('mousemove', onMove);
      window.removeEventListener('mouseup', onUp);
    };

    window.addEventListener('mousemove', onMove);
    window.addEventListener('mouseup', onUp);
  };

  const addPoint = () => {
    if (points.length === 0) {
      setPoints([[50, 50]]);
      return;
    }
    // Add midpoint between last and first point
    const last = points[points.length - 1];
    const first = points[0];
    const mx = Math.round((last[0] + first[0]) / 2);
    const my = Math.round((last[1] + first[1]) / 2);
    setPoints(prev => [...prev, [mx, my]]);
  };

  const removePoint = () => {
    if (points.length <= 3) return;
    setPoints(prev => prev.slice(0, -1));
  };

  const PREVIEW_SIZE = 300;

  return (
    <div className="mini-tool">
      {/* Preset buttons */}
      <div className="mini-label">Presets</div>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 16 }}>
        {Object.keys(PRESETS).map(name => (
          <button key={name}
                  className={`filter-pill${!customMode && activePreset === name ? ' active' : ''}`}
                  onClick={() => selectPreset(name)}>
            {name}
          </button>
        ))}
        <button className={`filter-pill${customMode ? ' active' : ''}`}
                onClick={enterCustom}>
          Custom
        </button>
      </div>

      {/* Custom controls */}
      {customMode && shapeType === 'polygon' && (
        <div style={{ display: 'flex', gap: 8, marginBottom: 12 }}>
          <button className="btn btn-secondary" onClick={addPoint} style={{ fontSize: 13 }}>
            + Add point
          </button>
          <button className="btn btn-secondary" onClick={removePoint}
                  disabled={points.length <= 3} style={{ fontSize: 13 }}>
            - Remove point
          </button>
          <span style={{ fontSize: 12, color: 'var(--id-text)', opacity: 0.6, alignSelf: 'center', marginLeft: 4 }}>
            {points.length} points — drag to reposition
          </span>
        </div>
      )}

      {/* Preview area */}
      <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 16 }}>
        <div ref={previewRef}
             style={{
               width: PREVIEW_SIZE, height: PREVIEW_SIZE,
               position: 'relative',
               border: '1px solid var(--id-border)',
               borderRadius: 8,
               overflow: 'hidden',
               background: 'var(--id-bg)',
             }}>
          {/* Checkerboard pattern for visibility */}
          <div style={{
            position: 'absolute', inset: 0, opacity: 0.06,
            backgroundImage: 'repeating-conic-gradient(var(--id-text) 0% 25%, transparent 0% 50%)',
            backgroundSize: '20px 20px',
          }} />

          {/* Clipped gradient shape */}
          <div style={{
            position: 'absolute', inset: 0,
            background: 'linear-gradient(135deg, #667eea 0%, #764ba2 40%, #f093fb 70%, #f5576c 100%)',
            clipPath: clipPath,
            WebkitClipPath: clipPath,
          }} />

          {/* Draggable points overlay (polygon only, when editing) */}
          {shapeType === 'polygon' && (customMode || activePreset) && points.map(([x, y], i) => (
            <div key={i}
                 onMouseDown={(e) => onPointDown(i, e)}
                 style={{
                   position: 'absolute',
                   left: `${x}%`, top: `${y}%`,
                   width: 14, height: 14,
                   marginLeft: -7, marginTop: -7,
                   borderRadius: '50%',
                   background: draggingIdx === i ? 'var(--id-primary)' : 'var(--id-surface)',
                   border: `2px solid ${draggingIdx === i ? 'var(--id-primary)' : 'var(--id-text)'}`,
                   cursor: 'grab',
                   zIndex: 10,
                   boxShadow: '0 1px 4px rgba(0,0,0,0.3)',
                 }}
                 title={`Point ${i + 1}: ${x}% ${y}%`}
            />
          ))}

          {/* Draw connecting lines between polygon points */}
          {shapeType === 'polygon' && points.length > 1 && (
            <svg style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', pointerEvents: 'none', zIndex: 5 }}
                 viewBox="0 0 100 100" preserveAspectRatio="none">
              <polygon
                points={points.map(([x, y]) => `${x},${y}`).join(' ')}
                fill="none"
                stroke="var(--id-text)"
                strokeWidth="0.4"
                strokeDasharray="1.5 1"
                opacity="0.4"
              />
            </svg>
          )}
        </div>
      </div>

      {/* Points table for polygon */}
      {shapeType === 'polygon' && points.length > 0 && (
        <details style={{ marginBottom: 16 }}>
          <summary style={{ cursor: 'pointer', fontSize: 13, color: 'var(--id-text)', opacity: 0.7 }}>
            Points ({points.length})
          </summary>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 8 }}>
            {points.map(([x, y], i) => (
              <span key={i} style={{
                fontSize: 12, fontFamily: 'monospace', padding: '2px 8px',
                background: 'var(--id-surface)', border: '1px solid var(--id-border)',
                borderRadius: 6, color: 'var(--id-text)',
              }}>
                {x}% {y}%
              </span>
            ))}
          </div>
        </details>
      )}

      {/* CSS output */}
      <div className="mini-label">CSS</div>
      <textarea className="mini-input" readOnly value={cssText}
                style={{ fontFamily: 'monospace', fontSize: 13, minHeight: 48, resize: 'vertical', width: '100%' }} />

      <div className="cmp-actions">
        <button className="btn btn-primary" onClick={copyCSS}>
          <window.Icon name={copied ? 'check' : 'doc'} size={16} />
          {copied ? 'Copied!' : 'Copy CSS'}
        </button>
      </div>
    </div>
  );
};
