// SVG Blob Generator — create organic blob shapes as SVG.

window.TOOL_HANDLERS['svg-blob'] = function SvgBlobTool() {
  const [complexity, setComplexity] = React.useState(8);
  const [size, setSize] = React.useState(400);
  const [randomness, setRandomness] = React.useState(50);
  const [fill, setFill] = React.useState('#3b82f6');
  const [seed, setSeed] = React.useState(1);
  const [copied, setCopied] = React.useState('');

  // Simple seeded random for reproducibility per seed value
  const seededRandom = React.useCallback((s) => {
    let x = Math.sin(s * 9301 + 49297) * 233280;
    return x - Math.floor(x);
  }, []);

  const svgCode = React.useMemo(() => {
    const cx = size / 2;
    const cy = size / 2;
    const baseRadius = size * 0.35;
    const points = [];
    const n = complexity;
    const randFactor = randomness / 100;

    // Generate points around a circle with random radius offsets
    for (let i = 0; i < n; i++) {
      const angle = (Math.PI * 2 * i) / n;
      const rand = seededRandom(seed * 1000 + i * 137);
      const offset = 1 + (rand - 0.5) * 2 * randFactor * 0.5;
      const r = baseRadius * offset;
      points.push({
        x: cx + Math.cos(angle) * r,
        y: cy + Math.sin(angle) * r,
      });
    }

    // Build smooth closed path using cubic bezier
    // For smooth curves through each point, compute control points
    const getControlPoints = (p0, p1, p2, tension) => {
      const d01 = Math.sqrt((p1.x - p0.x) ** 2 + (p1.y - p0.y) ** 2);
      const d12 = Math.sqrt((p2.x - p1.x) ** 2 + (p2.y - p1.y) ** 2);
      const fa = tension * d01 / (d01 + d12);
      const fb = tension - fa;
      return {
        cp1: {
          x: p1.x + fa * (p0.x - p2.x),
          y: p1.y + fa * (p0.y - p2.y),
        },
        cp2: {
          x: p1.x - fb * (p0.x - p2.x),
          y: p1.y - fb * (p0.y - p2.y),
        },
      };
    };

    const tension = 0.35;
    const allCps = [];
    for (let i = 0; i < n; i++) {
      const p0 = points[(i - 1 + n) % n];
      const p1 = points[i];
      const p2 = points[(i + 1) % n];
      allCps.push(getControlPoints(p0, p1, p2, tension));
    }

    // Build path
    const f = (v) => v.toFixed(2);
    let d = `M ${f(points[0].x)} ${f(points[0].y)}`;
    for (let i = 0; i < n; i++) {
      const next = (i + 1) % n;
      const cp1 = allCps[i].cp2;
      const cp2 = allCps[next].cp1;
      const end = points[next];
      d += ` C ${f(cp1.x)} ${f(cp1.y)}, ${f(cp2.x)} ${f(cp2.y)}, ${f(end.x)} ${f(end.y)}`;
    }
    d += ' Z';

    return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${size} ${size}" width="${size}" height="${size}">\n  <path d="${d}" fill="${fill}" />\n</svg>`;
  }, [complexity, size, randomness, fill, seed, seededRandom]);

  const randomize = () => setSeed(s => s + 1);

  const copySvg = () => {
    navigator.clipboard.writeText(svgCode);
    setCopied('svg');
    setTimeout(() => setCopied(''), 1200);
  };

  const downloadSvg = () => {
    const blob = new Blob([svgCode], { type: 'image/svg+xml' });
    window.downloadBlob(blob, 'blob.svg');
  };

  // Checkerboard CSS for preview background
  const checkerBg = 'repeating-conic-gradient(rgba(0,0,0,0.06) 0% 25%, transparent 0% 50%) 0 0 / 20px 20px';

  return (
    <div className="mini-tool">
      <div className="mini-row" style={{ alignItems: 'flex-end', gap: 12, marginBottom: 16, flexWrap: 'wrap' }}>
        <div className="mini-field">
          <label className="mini-label">Points: {complexity}</label>
          <input type="range" min="3" max="20" value={complexity}
                 onChange={(e) => setComplexity(Number(e.target.value))}
                 style={{ width: 120 }} />
        </div>
        <div className="mini-field">
          <label className="mini-label">Size: {size}px</label>
          <input type="range" min="200" max="600" step="20" value={size}
                 onChange={(e) => setSize(Number(e.target.value))}
                 style={{ width: 120 }} />
        </div>
        <div className="mini-field">
          <label className="mini-label">Randomness: {randomness}%</label>
          <input type="range" min="0" max="100" value={randomness}
                 onChange={(e) => setRandomness(Number(e.target.value))}
                 style={{ width: 120 }} />
        </div>
        <div className="mini-field">
          <label className="mini-label">Fill</label>
          <input type="color" className="mini-input" value={fill}
                 onChange={(e) => setFill(e.target.value)}
                 style={{ width: 48, height: 36, padding: 4, cursor: 'pointer' }} />
        </div>
        <button className="btn btn-secondary" onClick={randomize} style={{ alignSelf: 'flex-end' }}>
          <window.Icon name="rotate" size={14} /> Randomize
        </button>
      </div>

      {/* SVG Preview */}
      <div style={{
        display: 'flex', justifyContent: 'center',
        padding: 20, borderRadius: 12,
        background: checkerBg,
        border: '1px solid var(--id-border)',
        marginBottom: 16,
      }}>
        <div dangerouslySetInnerHTML={{ __html: svgCode }}
             style={{ maxWidth: '100%', width: size, height: 'auto' }} />
      </div>

      {/* SVG Code output */}
      <div className="mini-field">
        <label className="mini-label">SVG Code</label>
        <textarea
          className="mini-input"
          readOnly
          value={svgCode}
          style={{
            width: '100%', minHeight: 100, resize: 'vertical',
            fontFamily: 'monospace', fontSize: 11,
          }}
          onClick={(e) => e.target.select()}
        />
      </div>

      {copied === 'svg' && (
        <div style={{
          textAlign: 'center', marginTop: 6,
          color: 'var(--id-primary)', fontWeight: 600, fontSize: 13,
        }}>SVG code copied!</div>
      )}

      <div className="cmp-actions">
        <button className="btn btn-secondary" onClick={copySvg}>
          <window.Icon name="clipboard" size={16} /> Copy SVG
        </button>
        <button className="btn btn-primary" onClick={downloadSvg}>
          <window.Icon name="download" size={16} /> Download SVG
        </button>
      </div>
    </div>
  );
};
