// CSS Gradient Generator — build linear/radial gradients with live preview and CSS output.

window.TOOL_HANDLERS['css-gradient'] = function CssGradientTool() {
  const [type, setType] = React.useState('linear');
  const [angle, setAngle] = React.useState(135);
  const [stops, setStops] = React.useState([
    { color: '#667eea', pos: 0 },
    { color: '#764ba2', pos: 100 },
  ]);
  const [copied, setCopied] = React.useState(false);
  const angleDragRef = React.useRef(false);
  const angleBoxRef = React.useRef(null);

  const presets = {
    Sunset:  [{ color: '#f093fb', pos: 0 }, { color: '#f5576c', pos: 50 }, { color: '#fda085', pos: 100 }],
    Ocean:   [{ color: '#667eea', pos: 0 }, { color: '#00c9ff', pos: 100 }],
    Forest:  [{ color: '#11998e', pos: 0 }, { color: '#38ef7d', pos: 100 }],
    Candy:   [{ color: '#f7797d', pos: 0 }, { color: '#FBD786', pos: 50 }, { color: '#C6FFDD', pos: 100 }],
    Night:   [{ color: '#0f0c29', pos: 0 }, { color: '#302b63', pos: 50 }, { color: '#24243e', pos: 100 }],
  };

  const niceColors = [
    ['#ff6b6b','#feca57'],['#48dbfb','#ff9ff3'],['#1dd1a1','#10ac84'],
    ['#5f27cd','#c44569'],['#0abde3','#ee5a24','#f6e58d'],
    ['#6c5ce7','#a29bfe'],['#fdcb6e','#e17055'],['#00cec9','#6c5ce7','#fd79a8'],
  ];

  const randomGradient = () => {
    const combo = niceColors[Math.floor(Math.random() * niceColors.length)];
    const newStops = combo.map((c, i) => ({
      color: c,
      pos: Math.round((i / (combo.length - 1)) * 100),
    }));
    setStops(newStops);
    setAngle(Math.floor(Math.random() * 360));
  };

  const updateStop = (idx, field, val) => {
    setStops(prev => prev.map((s, i) => i === idx ? { ...s, [field]: val } : s));
  };

  const addStop = () => {
    const lastPos = stops[stops.length - 1]?.pos ?? 50;
    const newPos = Math.min(100, lastPos + 10);
    setStops(prev => [...prev, { color: '#ffffff', pos: newPos }]);
  };

  const removeStop = (idx) => {
    if (stops.length <= 2) return;
    setStops(prev => prev.filter((_, i) => i !== idx));
  };

  const stopsStr = stops.map(s => `${s.color} ${s.pos}%`).join(', ');
  const gradientCSS = type === 'linear'
    ? `linear-gradient(${angle}deg, ${stopsStr})`
    : `radial-gradient(circle, ${stopsStr})`;
  const cssText = `background: ${gradientCSS};`;

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

  // Angle picker: compute angle from mouse position relative to center
  const handleAngleMouse = (e) => {
    const box = angleBoxRef.current;
    if (!box) return;
    const rect = box.getBoundingClientRect();
    const cx = rect.left + rect.width / 2;
    const cy = rect.top + rect.height / 2;
    const dx = e.clientX - cx;
    const dy = e.clientY - cy;
    let deg = Math.round(Math.atan2(dy, dx) * (180 / Math.PI) + 90);
    if (deg < 0) deg += 360;
    setAngle(deg);
  };

  const onAngleDown = (e) => {
    e.preventDefault();
    angleDragRef.current = true;
    handleAngleMouse(e);
    const onMove = (ev) => { if (angleDragRef.current) handleAngleMouse(ev); };
    const onUp = () => { angleDragRef.current = false; window.removeEventListener('mousemove', onMove); window.removeEventListener('mouseup', onUp); };
    window.addEventListener('mousemove', onMove);
    window.addEventListener('mouseup', onUp);
  };

  // Knob indicator position
  const rad = (angle - 90) * (Math.PI / 180);
  const knobR = 28;
  const knobX = 32 + Math.cos(rad) * knobR;
  const knobY = 32 + Math.sin(rad) * knobR;

  return (
    <div className="mini-tool">
      {/* Type toggle */}
      <div style={{ display: 'flex', gap: 8, marginBottom: 16 }}>
        {['linear', 'radial'].map(t => (
          <button key={t} className={`filter-pill${type === t ? ' active' : ''}`}
                  onClick={() => setType(t)} style={{ textTransform: 'capitalize' }}>{t}</button>
        ))}
      </div>

      {/* Angle picker (linear only) */}
      {type === 'linear' && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginBottom: 16 }}>
          <label className="mini-label" style={{ margin: 0 }}>Angle</label>
          <div ref={angleBoxRef}
               onMouseDown={onAngleDown}
               style={{
                 width: 64, height: 64, borderRadius: '50%',
                 border: '2px solid var(--id-border)', background: 'var(--id-surface)',
                 position: 'relative', cursor: 'pointer', flexShrink: 0,
               }}>
            {/* Line from center to knob */}
            <div style={{
              position: 'absolute', left: 32, top: 32,
              width: knobR, height: 2, background: 'var(--id-primary)',
              transformOrigin: '0 50%', transform: `rotate(${angle - 90}deg)`,
            }} />
            {/* Knob dot */}
            <div style={{
              position: 'absolute',
              left: knobX - 6, top: knobY - 6,
              width: 12, height: 12, borderRadius: '50%',
              background: 'var(--id-primary)', border: '2px solid var(--id-surface)',
            }} />
          </div>
          <input type="number" className="mini-input" min="0" max="360"
                 value={angle} onChange={(e) => setAngle(Math.max(0, Math.min(360, +e.target.value || 0)))}
                 style={{ width: 70 }} />
          <span style={{ color: 'var(--id-text)', opacity: 0.6 }}>deg</span>
        </div>
      )}

      {/* Color stops */}
      <div className="mini-label">Color Stops</div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 16 }}>
        {stops.map((s, i) => (
          <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <input type="color" value={s.color} onChange={(e) => updateStop(i, 'color', e.target.value)}
                   style={{ width: 40, height: 36, border: '1px solid var(--id-border)', borderRadius: 6, padding: 2, cursor: 'pointer' }} />
            <input type="text" className="mini-input" value={s.color}
                   onChange={(e) => updateStop(i, 'color', e.target.value)}
                   style={{ width: 90, fontFamily: 'monospace' }} />
            <input type="number" className="mini-input" min="0" max="100" value={s.pos}
                   onChange={(e) => updateStop(i, 'pos', Math.max(0, Math.min(100, +e.target.value || 0)))}
                   style={{ width: 64 }} />
            <span style={{ color: 'var(--id-text)', opacity: 0.5, fontSize: 13 }}>%</span>
            {stops.length > 2 && (
              <button className="btn btn-secondary" onClick={() => removeStop(i)}
                      style={{ padding: '4px 8px', minWidth: 0 }}>
                <window.Icon name="x" size={14} />
              </button>
            )}
          </div>
        ))}
        <button className="btn btn-secondary" onClick={addStop} style={{ alignSelf: 'flex-start' }}>
          + Add stop
        </button>
      </div>

      {/* Preview */}
      <div style={{
        width: '100%', height: 200, borderRadius: 12,
        background: gradientCSS,
        border: '1px solid var(--id-border)',
        marginBottom: 16,
      }} />

      {/* Presets + Random */}
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginBottom: 16 }}>
        {Object.entries(presets).map(([name, stops]) => (
          <button key={name} className="filter-pill" onClick={() => setStops(stops)}>
            {name}
          </button>
        ))}
        <button className="filter-pill" onClick={randomGradient}>
          <window.Icon name="rotate" size={14} /> Random
        </button>
      </div>

      {/* 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>
  );
};
