// Color Mixer — blend two colors in N steps with gradient preview.

window.TOOL_HANDLERS['color-mixer'] = function ColorMixerTool() {
  const [color1, setColor1] = React.useState('#ff0000');
  const [color2, setColor2] = React.useState('#0000ff');
  const [steps, setSteps] = React.useState(5);
  const [copied, setCopied] = React.useState('');

  const hexToRgb = (hex) => {
    const n = parseInt(hex.slice(1), 16);
    return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
  };

  const rgbToHex = (r, g, b) =>
    '#' + [r, g, b].map(v => Math.round(v).toString(16).padStart(2, '0')).join('');

  const swatches = React.useMemo(() => {
    const [r1, g1, b1] = hexToRgb(color1);
    const [r2, g2, b2] = hexToRgb(color2);
    const result = [];
    for (let i = 0; i < steps; i++) {
      const t = steps === 1 ? 0.5 : i / (steps - 1);
      result.push(rgbToHex(
        r1 + (r2 - r1) * t,
        g1 + (g2 - g1) * t,
        b1 + (b2 - b1) * t
      ));
    }
    return result;
  }, [color1, color2, steps]);

  const gradientCSS = `linear-gradient(to right, ${color1}, ${color2})`;

  const copyHex = (hex) => {
    navigator.clipboard.writeText(hex);
    setCopied(hex);
    setTimeout(() => setCopied(''), 1200);
  };

  const copyGradient = () => {
    navigator.clipboard.writeText(`background: ${gradientCSS};`);
    setCopied('gradient');
    setTimeout(() => setCopied(''), 1200);
  };

  const textColor = (hex) => {
    const [r, g, b] = hexToRgb(hex);
    return (0.299 * r + 0.587 * g + 0.114 * b) > 140 ? '#1a1a1a' : '#ffffff';
  };

  return (
    <div className="mini-tool">
      <div className="mini-row" style={{ alignItems: 'flex-end', gap: 16, marginBottom: 20 }}>
        <div className="mini-field">
          <label className="mini-label">Color 1</label>
          <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
            <input type="color" className="mini-input" value={color1}
                   onChange={(e) => setColor1(e.target.value)}
                   style={{ width: 48, height: 40, padding: 4, cursor: 'pointer' }} />
            <input className="mini-input" value={color1}
                   onChange={(e) => {
                     if (/^#[0-9a-fA-F]{6}$/.test(e.target.value)) setColor1(e.target.value);
                   }}
                   style={{ width: 90, fontFamily: 'monospace' }} />
          </div>
        </div>
        <div className="mini-field">
          <label className="mini-label">Color 2</label>
          <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
            <input type="color" className="mini-input" value={color2}
                   onChange={(e) => setColor2(e.target.value)}
                   style={{ width: 48, height: 40, padding: 4, cursor: 'pointer' }} />
            <input className="mini-input" value={color2}
                   onChange={(e) => {
                     if (/^#[0-9a-fA-F]{6}$/.test(e.target.value)) setColor2(e.target.value);
                   }}
                   style={{ width: 90, fontFamily: 'monospace' }} />
          </div>
        </div>
        <div className="mini-field" style={{ flex: 1 }}>
          <label className="mini-label">Steps: {steps}</label>
          <input type="range" min="3" max="20" value={steps}
                 onChange={(e) => setSteps(Number(e.target.value))}
                 style={{ width: '100%' }} />
        </div>
      </div>

      {/* Swatch row */}
      <div style={{
        display: 'flex', flexWrap: 'wrap', gap: 6,
        justifyContent: 'center', padding: '12px 0'
      }}>
        {swatches.map((hex, i) => (
          <div key={i} onClick={() => copyHex(hex)}
               style={{
                 cursor: 'pointer',
                 display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
                 transition: 'transform 0.15s',
               }}
               onMouseOver={(e) => e.currentTarget.style.transform = 'scale(1.08)'}
               onMouseOut={(e) => e.currentTarget.style.transform = 'scale(1)'}>
            <div style={{
              width: 56, height: 56,
              backgroundColor: hex,
              borderRadius: 8,
              border: '1px solid var(--id-border)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              {copied === hex && (
                <span style={{
                  fontSize: 9, fontWeight: 700,
                  color: textColor(hex),
                }}>Copied!</span>
              )}
            </div>
            <span style={{
              fontSize: 10, fontFamily: 'monospace',
              color: 'var(--id-text-sub, var(--id-text))',
              opacity: 0.8,
            }}>{hex.toUpperCase()}</span>
          </div>
        ))}
      </div>

      {/* Gradient preview */}
      <div style={{ marginTop: 16 }}>
        <div className="mini-label">CSS Gradient</div>
        <div style={{
          height: 40, borderRadius: 8,
          background: gradientCSS,
          border: '1px solid var(--id-border)',
          marginBottom: 8,
        }} />
        <div style={{
          fontFamily: 'monospace', fontSize: 12,
          padding: '8px 12px',
          background: 'var(--id-surface)',
          border: '1px solid var(--id-border)',
          borderRadius: 6,
          color: 'var(--id-text)',
          wordBreak: 'break-all',
        }}>
          background: {gradientCSS};
        </div>
      </div>

      {copied && (
        <div style={{
          textAlign: 'center', marginTop: 8,
          color: 'var(--id-primary)', fontWeight: 600, fontSize: 13,
        }}>
          {copied === 'gradient' ? 'Gradient CSS copied!' : `Copied ${copied.toUpperCase()}`}
        </div>
      )}

      <div className="cmp-actions">
        <button className="btn btn-secondary" onClick={copyGradient}>
          <window.Icon name="clipboard" size={16} /> Copy gradient CSS
        </button>
      </div>
    </div>
  );
};
