// Color Shades — generate tints and shades from a base color.

window.TOOL_HANDLERS['color-shades'] = function ColorShadesTool() {
  const [color, setColor] = React.useState('#3b82f6');
  const [steps, setSteps] = React.useState(11);
  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 shades = React.useMemo(() => {
    const [r, g, b] = hexToRgb(color);
    const mid = Math.floor(steps / 2);
    const result = [];
    for (let i = 0; i < steps; i++) {
      let hex;
      if (i < mid) {
        // tints: lerp from white toward base color
        const t = i / mid;
        hex = rgbToHex(
          255 + (r - 255) * t,
          255 + (g - 255) * t,
          255 + (b - 255) * t
        );
      } else if (i === mid) {
        hex = color;
      } else {
        // shades: lerp from base color toward black
        const t = (i - mid) / (steps - 1 - mid);
        hex = rgbToHex(r * (1 - t), g * (1 - t), b * (1 - t));
      }
      result.push(hex);
    }
    return result;
  }, [color, steps]);

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

  // Determine if text should be light or dark based on luminance
  const textColor = (hex) => {
    const [r, g, b] = hexToRgb(hex);
    const lum = 0.299 * r + 0.587 * g + 0.114 * b;
    return lum > 140 ? '#1a1a1a' : '#ffffff';
  };

  return (
    <div className="mini-tool">
      <div className="mini-row" style={{ alignItems: 'flex-end', gap: 16, marginBottom: 20 }}>
        <div className="mini-field" style={{ flex: '0 0 auto' }}>
          <label className="mini-label">Base color</label>
          <input type="color" className="mini-input" value={color}
                 onChange={(e) => setColor(e.target.value)}
                 style={{ width: 60, height: 40, padding: 4, cursor: 'pointer' }} />
        </div>
        <div className="mini-field" style={{ flex: '0 0 auto' }}>
          <label className="mini-label">Hex</label>
          <input className="mini-input" value={color}
                 onChange={(e) => {
                   const v = e.target.value;
                   if (/^#[0-9a-fA-F]{6}$/.test(v)) setColor(v);
                 }}
                 style={{ width: 100, fontFamily: 'monospace' }} />
        </div>
        <div className="mini-field" style={{ flex: 1 }}>
          <label className="mini-label">Steps: {steps}</label>
          <input type="range" min="5" max="20" value={steps}
                 onChange={(e) => setSteps(Number(e.target.value))}
                 style={{ width: '100%' }} />
        </div>
      </div>

      <div style={{
        display: 'flex', flexWrap: 'wrap', gap: 6,
        justifyContent: 'center', padding: '16px 0'
      }}>
        {shades.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: 60, height: 60,
              backgroundColor: hex,
              borderRadius: 8,
              border: hex === color ? '3px solid var(--id-primary)' : '1px solid var(--id-border)',
              boxShadow: hex === color ? '0 0 0 2px var(--id-primary-soft, rgba(59,130,246,0.2))' : 'none',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              {copied === hex && (
                <span style={{
                  fontSize: 10, fontWeight: 700,
                  color: textColor(hex),
                  textShadow: '0 1px 2px rgba(0,0,0,0.3)',
                }}>Copied!</span>
              )}
            </div>
            <span style={{
              fontSize: 11, fontFamily: 'monospace',
              color: 'var(--id-text-sub, var(--id-text))',
              opacity: 0.8,
            }}>{hex.toUpperCase()}</span>
          </div>
        ))}
      </div>

      {copied && (
        <div style={{
          textAlign: 'center', marginTop: 8,
          color: 'var(--id-primary)', fontWeight: 600, fontSize: 13,
        }}>
          Copied {copied.toUpperCase()} to clipboard
        </div>
      )}
    </div>
  );
};
