// HEX-RGBA — bidirectional conversion between HEX color codes and RGBA values.

window.TOOL_HANDLERS['hex-rgba'] = function HexRgbaTool() {
  var _s = React.useState;

  // HEX to RGBA state
  var _hex = _s('#3b82f6');
  var hex = _hex[0]; var setHex = _hex[1];

  // RGBA to HEX state
  var _r = _s(59); var r = _r[0]; var setR = _r[1];
  var _g = _s(130); var g = _g[0]; var setG = _g[1];
  var _b = _s(246); var b = _b[0]; var setB = _b[1];
  var _a = _s(1); var a = _a[0]; var setA = _a[1];

  var _copied = _s('');
  var copied = _copied[0]; var setCopied = _copied[1];

  // Parse hex (3, 4, 6, or 8 digits) to rgba
  var parseHex = function (h) {
    var raw = h.replace(/^#/, '');
    if (!/^[0-9a-fA-F]+$/.test(raw)) return null;

    var rr, gg, bb, aa;
    if (raw.length === 3) {
      rr = parseInt(raw[0] + raw[0], 16);
      gg = parseInt(raw[1] + raw[1], 16);
      bb = parseInt(raw[2] + raw[2], 16);
      aa = 1;
    } else if (raw.length === 4) {
      rr = parseInt(raw[0] + raw[0], 16);
      gg = parseInt(raw[1] + raw[1], 16);
      bb = parseInt(raw[2] + raw[2], 16);
      aa = parseInt(raw[3] + raw[3], 16) / 255;
    } else if (raw.length === 6) {
      rr = parseInt(raw.slice(0, 2), 16);
      gg = parseInt(raw.slice(2, 4), 16);
      bb = parseInt(raw.slice(4, 6), 16);
      aa = 1;
    } else if (raw.length === 8) {
      rr = parseInt(raw.slice(0, 2), 16);
      gg = parseInt(raw.slice(2, 4), 16);
      bb = parseInt(raw.slice(4, 6), 16);
      aa = parseInt(raw.slice(6, 8), 16) / 255;
    } else {
      return null;
    }

    if (isNaN(rr) || isNaN(gg) || isNaN(bb) || isNaN(aa)) return null;
    return { r: rr, g: gg, b: bb, a: Math.round(aa * 100) / 100 };
  };

  // Build RGBA string from parsed values
  var hexParsed = React.useMemo(function () {
    return parseHex(hex);
  }, [hex]);

  var hexRgbaStr = React.useMemo(function () {
    if (!hexParsed) return '';
    if (hexParsed.a === 1) return 'rgb(' + hexParsed.r + ', ' + hexParsed.g + ', ' + hexParsed.b + ')';
    return 'rgba(' + hexParsed.r + ', ' + hexParsed.g + ', ' + hexParsed.b + ', ' + hexParsed.a + ')';
  }, [hexParsed]);

  // Build HEX from RGBA inputs
  var rgbaHexStr = React.useMemo(function () {
    var rr = Math.max(0, Math.min(255, Math.round(r)));
    var gg = Math.max(0, Math.min(255, Math.round(g)));
    var bb = Math.max(0, Math.min(255, Math.round(b)));
    var aa = Math.max(0, Math.min(1, a));
    var base = '#' + rr.toString(16).padStart(2, '0') + gg.toString(16).padStart(2, '0') + bb.toString(16).padStart(2, '0');
    if (aa < 1) {
      base += Math.round(aa * 255).toString(16).padStart(2, '0');
    }
    return base.toUpperCase();
  }, [r, g, b, a]);

  var copy = function (text, label) {
    navigator.clipboard.writeText(text);
    setCopied(label);
    setTimeout(function () { setCopied(''); }, 1500);
  };

  // Checkerboard for alpha preview
  var checkerBg = 'repeating-conic-gradient(#d0d0d0 0% 25%, #fff 0% 50%) 0 0 / 16px 16px';

  var swatchStyle = function (color) {
    return {
      width: 80, height: 80, borderRadius: 12,
      border: '2px solid var(--id-border)',
      background: checkerBg, position: 'relative', overflow: 'hidden',
      flexShrink: 0
    };
  };

  var swatchInner = function (color) {
    return {
      position: 'absolute', inset: 0,
      background: color, borderRadius: 10
    };
  };

  var sectionStyle = {
    padding: '16px', borderRadius: 12,
    border: '1px solid var(--id-border)',
    background: 'var(--id-surface-alt)', marginBottom: 16
  };

  var inputNumStyle = {
    width: 64, textAlign: 'center', fontFamily: 'monospace'
  };

  return (
    <div className="mini-tool">
      {/* HEX to RGBA */}
      <div style={sectionStyle}>
        <div className="mini-label" style={{ marginTop: 0 }}>HEX to RGBA</div>
        <div style={{ display: 'flex', gap: 16, alignItems: 'center', flexWrap: 'wrap' }}>
          <div style={swatchStyle()}>
            <div style={swatchInner(hexParsed ? (hexParsed.a < 1 ? 'rgba(' + hexParsed.r + ',' + hexParsed.g + ',' + hexParsed.b + ',' + hexParsed.a + ')' : hex) : 'transparent')} />
          </div>
          <div style={{ flex: 1, minWidth: 160 }}>
            <div style={{ display: 'flex', gap: 8, alignItems: 'center', marginBottom: 8 }}>
              <input
                className="mini-input"
                style={{ fontFamily: 'monospace', fontSize: 15, fontWeight: 600, maxWidth: 140 }}
                value={hex}
                onChange={function (e) { setHex(e.target.value); }}
                placeholder="#3b82f6"
              />
              <input
                type="color"
                value={hexParsed ? '#' + hexParsed.r.toString(16).padStart(2, '0') + hexParsed.g.toString(16).padStart(2, '0') + hexParsed.b.toString(16).padStart(2, '0') : '#000000'}
                onChange={function (e) { setHex(e.target.value); }}
                style={{ width: 36, height: 36, border: 'none', cursor: 'pointer', borderRadius: 8, padding: 0 }}
                title="Pick a color"
              />
            </div>
            {hexParsed ? (
              <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                <code style={{ fontSize: 13, color: 'var(--id-text)' }}>{hexRgbaStr}</code>
                <button
                  className="icon-btn"
                  onClick={function () { copy(hexRgbaStr, 'rgba-out'); }}
                  aria-label="Copy RGBA"
                  style={copied === 'rgba-out' ? { color: 'var(--id-success)' } : {}}
                >
                  <window.Icon name={copied === 'rgba-out' ? 'check' : 'doc'} size={13} />
                </button>
              </div>
            ) : (
              <div style={{ fontSize: 12, color: '#c8321f' }}>Enter a valid hex (3/4/6/8 digits)</div>
            )}
          </div>
        </div>
      </div>

      {/* RGBA to HEX */}
      <div style={sectionStyle}>
        <div className="mini-label" style={{ marginTop: 0 }}>RGBA to HEX</div>
        <div style={{ display: 'flex', gap: 16, alignItems: 'center', flexWrap: 'wrap' }}>
          <div style={swatchStyle()}>
            <div style={swatchInner('rgba(' + r + ',' + g + ',' + b + ',' + a + ')')} />
          </div>
          <div style={{ flex: 1, minWidth: 200 }}>
            <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap', marginBottom: 8 }}>
              <label style={{ fontSize: 11, fontWeight: 600, color: 'var(--id-text-muted)' }}>
                R
                <input className="mini-input" type="number" min="0" max="255" value={r}
                  onChange={function (e) { setR(Math.max(0, Math.min(255, +e.target.value || 0))); }}
                  style={inputNumStyle} />
              </label>
              <label style={{ fontSize: 11, fontWeight: 600, color: 'var(--id-text-muted)' }}>
                G
                <input className="mini-input" type="number" min="0" max="255" value={g}
                  onChange={function (e) { setG(Math.max(0, Math.min(255, +e.target.value || 0))); }}
                  style={inputNumStyle} />
              </label>
              <label style={{ fontSize: 11, fontWeight: 600, color: 'var(--id-text-muted)' }}>
                B
                <input className="mini-input" type="number" min="0" max="255" value={b}
                  onChange={function (e) { setB(Math.max(0, Math.min(255, +e.target.value || 0))); }}
                  style={inputNumStyle} />
              </label>
              <label style={{ fontSize: 11, fontWeight: 600, color: 'var(--id-text-muted)' }}>
                A
                <input className="mini-input" type="number" min="0" max="1" step="0.01" value={a}
                  onChange={function (e) { setA(Math.max(0, Math.min(1, +e.target.value || 0))); }}
                  style={inputNumStyle} />
              </label>
            </div>
            <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
              <code style={{ fontSize: 15, fontWeight: 600, color: 'var(--id-text)' }}>{rgbaHexStr}</code>
              <button
                className="icon-btn"
                onClick={function () { copy(rgbaHexStr, 'hex-out'); }}
                aria-label="Copy HEX"
                style={copied === 'hex-out' ? { color: 'var(--id-success)' } : {}}
              >
                <window.Icon name={copied === 'hex-out' ? 'check' : 'doc'} size={13} />
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};
