import { useState, useRef, useCallback, useEffect } from "react";

const T = {
  bg: "#0A0A0C", panel: "#141418", surface: "#1C1C22", border: "#2A2A32",
  amber: "#E8A030", amberDim: "#7A5218", blue: "#3A7BA8", blueDim: "#1E4060",
  green: "#3AB87A", red: "#C84040", textPrimary: "#F0EDE6", textSec: "#8888A0", textDim: "#444458",
};

// ── EQ Band definitions ──
const EQ_BANDS = [
  { key: "low",  label: "Low",   freq: "80 Hz",  color: "#60A0E0", shadow: "#60A0E044" },
  { key: "mid",  label: "Mid",   freq: "800 Hz", color: T.amber,    shadow: `${T.amber}44` },
  { key: "high", label: "High",  freq: "6.4 kHz",color: "#60D080", shadow: "#60D08044" },
];

// ── Knob Widget ──
function EqKnob({ label, freq, value, min, max, color, onChange }) {
  const startRef = useRef(null);
  const norm = (value - min) / (max - min);
  const angle = -140 + norm * 280;
  const size = 80;
  const dotH = size * 0.38;
  const dotTop = size * 0.5 - dotH;

  const handleStart = (e) => {
    e.preventDefault();
    const clientY = e.touches ? e.touches[0].clientY : e.clientY;
    startRef.current = { y: clientY, val: value };
    const move = (ev) => {
      const cy = ev.touches ? ev.touches[0].clientY : ev.clientY;
      const delta = (startRef.current.y - cy) / 120;
      const next = Math.max(min, Math.min(max, startRef.current.val + delta * (max - min)));
      onChange?.(Math.round(next * 10) / 10);
    };
    const up = () => {
      window.removeEventListener("mousemove", move);
      window.removeEventListener("mouseup", up);
      window.removeEventListener("touchmove", move);
      window.removeEventListener("touchend", up);
    };
    window.addEventListener("mousemove", move);
    window.addEventListener("mouseup", up);
    window.addEventListener("touchmove", move, { passive: false });
    window.addEventListener("touchend", up);
  };

  const svgSize = size + 16, cx = svgSize / 2, cy = svgSize / 2, r = size / 2 + 4;
  const lx = cx + r * Math.cos((-140 - 90) * (Math.PI / 180));
  const ly = cy + r * Math.sin((-140 - 90) * (Math.PI / 180));
  const ex = cx + r * Math.cos((angle - 90) * (Math.PI / 180));
  const ey = cy + r * Math.sin((angle - 90) * (Math.PI / 180));
  const large = norm * 280 > 180 ? 1 : 0;

  return (
    <div style={{
      display: "flex", flexDirection: "column", alignItems: "center", gap: 4,
      cursor: "pointer", minWidth: 0,
    }}>
      {/* Knob */}
      <div style={{ width: size, height: size, position: "relative", touchAction: "none" }}
        onMouseDown={handleStart} onTouchStart={handleStart}>
        <svg style={{ position: "absolute", inset: -8, width: svgSize, height: svgSize, overflow: "visible" }}>
          <circle cx={cx} cy={cy} r={r} fill="none" stroke={T.border} strokeWidth="3" strokeLinecap="round" opacity=".5" />
          {norm > 0 && (
            <path d={`M ${lx} ${ly} A ${r} ${r} 0 ${large} 1 ${ex} ${ey}`}
              fill="none" stroke={color} strokeWidth="3" strokeLinecap="round"
              style={{ filter: `drop-shadow(0 0 4px ${color})` }} />
          )}
        </svg>
        <div style={{
          borderRadius: "50%", width: "100%", height: "100%", position: "relative",
          background: "radial-gradient(circle at 35% 30%, #3A3A48, #1A1A22)",
          boxShadow: "0 3px 12px rgba(0,0,0,.6), inset 0 1px 0 rgba(255,255,255,.07)",
        }}>
          <div style={{
            position: "absolute", width: 4, borderRadius: 2, background: color,
            left: "50%", transformOrigin: "bottom center",
            height: dotH, top: dotTop,
            transform: `translateX(-50%) rotate(${angle}deg)`,
            transformOrigin: `50% ${dotH}px`,
            boxShadow: `0 0 6px ${color}`,
          }} />
        </div>
      </div>

      {/* Value */}
      <div style={{
        fontFamily: "'JetBrains Mono', monospace", fontSize: 14, fontWeight: 700, color,
      }}>{value > 0 ? `+${value}` : value} dB</div>

      {/* Label */}
      <div style={{ fontSize: 8, color: T.textDim, letterSpacing: ".08em", textTransform: "uppercase" }}>
        {label}
      </div>
      <div style={{ fontSize: 8, color: T.textDim, fontFamily: "'JetBrains Mono', monospace" }}>
        {freq}
      </div>
    </div>
  );
}

// ── Frequency Response Graph ──
function FrequencyGraph({ bands, values }) {
  const canvasRef = useRef(null);

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext("2d");
    const w = canvas.width;
    const h = canvas.height;
    const pad = { top: 10, bottom: 10, left: 20, right: 10 };
    const gw = w - pad.left - pad.right;
    const gh = h - pad.top - pad.bottom;

    // Clear
    ctx.clearRect(0, 0, w, h);

    // Grid
    ctx.strokeStyle = T.border;
    ctx.lineWidth = 0.5;
    // Horizontal lines (dB)
    for (let db = -12; db <= 12; db += 4) {
      const y = pad.top + gh * (1 - (db + 12) / 24);
      ctx.beginPath();
      ctx.moveTo(pad.left, y);
      ctx.lineTo(w - pad.right, y);
      ctx.stroke();
      ctx.fillStyle = T.textDim;
      ctx.font = "7px 'JetBrains Mono', monospace";
      ctx.textAlign = "right";
      ctx.fillText(`${db > 0 ? "+" : ""}${db}`, pad.left - 2, y + 2);
    }

    // Log frequency positions (80, 800, 6400 Hz on 3 bands)
    const freqPositions = {
      low:  pad.left + gw * 0.1,
      mid:  pad.left + gw * 0.5,
      high: pad.left + gw * 0.9,
    };

    // Draw band markers
    const bandMap = {};
    bands.forEach((b, i) => { bandMap[b.key] = i; });

    // Draw response curve (smooth interpolated)
    const bandVals = bands.map(b => values[b.key] ?? 0);
    // Simple interpolation between bands with 100 sample points
    const curveX = [];
    const curveY = [];
    const samplePoints = 100;
    for (let i = 0; i <= samplePoints; i++) {
      const t = i / samplePoints;
      const x = pad.left + gw * t;
      // Map t (0-1) to frequency position space
      // Use the 3 bands as control points
      const bandPoints = bands.map((b, idx) => ({
        x: freqPositions[b.key],
        y: -(bandVals[idx] || 0),
      }));
      // Nearest-neighbor interpolation with smoothing
      let v = 0;
      if (t < 0.1) {
        v = bandVals[0] * (t / 0.1);
      } else if (t > 0.9) {
        v = bandVals[2] * ((1 - t) / 0.1);
      } else {
        // Map t (0.1-0.9) to position between bands
        const bt = (t - 0.1) / 0.8; // 0-1 between first and last band
        // Quadratic bezier through mid band
        const b0 = bandVals[0];
        const b1 = bandVals[1];
        const b2 = bandVals[2];
        v = (1 - bt) * (1 - bt) * b0 + 2 * (1 - bt) * bt * b1 + bt * bt * b2;
      }
      const y = pad.top + gh * (0.5 - v / 24);
      curveX.push(x);
      curveY.push(y);
    }

    // Fill area under curve
    ctx.beginPath();
    ctx.moveTo(curveX[0], pad.top + gh);
    for (let i = 0; i < curveX.length; i++) {
      ctx.lineTo(curveX[i], curveY[i]);
    }
    ctx.lineTo(curveX[curveX.length - 1], pad.top + gh);
    ctx.closePath();
    ctx.fillStyle = `${T.amber}15`;
    ctx.fill();

    // Draw curve line
    ctx.beginPath();
    for (let i = 0; i < curveX.length; i++) {
      if (i === 0) ctx.moveTo(curveX[i], curveY[i]);
      else ctx.lineTo(curveX[i], curveY[i]);
    }
    ctx.strokeStyle = T.amber;
    ctx.lineWidth = 2;
    ctx.stroke();

    // Center line (0 dB)
    const centerY = pad.top + gh / 2;
    ctx.strokeStyle = `${T.textDim}44`;
    ctx.lineWidth = 1;
    ctx.setLineDash([2, 3]);
    ctx.beginPath();
    ctx.moveTo(pad.left, centerY);
    ctx.lineTo(w - pad.right, centerY);
    ctx.stroke();
    ctx.setLineDash([]);

    // Band markers
    bands.forEach((b) => {
      const x = freqPositions[b.key];
      const val = bandVals[bandMap[b.key]] || 0;
      const y = pad.top + gh * (0.5 - val / 24);
      // Dot at band position
      ctx.beginPath();
      ctx.arc(x, y, 5, 0, Math.PI * 2);
      ctx.fillStyle = b.color;
      ctx.fill();
      ctx.strokeStyle = T.bg;
      ctx.lineWidth = 2;
      ctx.stroke();
    });

    // Frequency labels
    ctx.fillStyle = T.textDim;
    ctx.font = "7px 'JetBrains Mono', monospace";
    ctx.textAlign = "center";
    ctx.fillText("80Hz", freqPositions.low, h - 2);
    ctx.fillText("800Hz", freqPositions.mid, h - 2);
    ctx.fillText("6.4kHz", freqPositions.high, h - 2);

  }, [bands, values]);

  return (
    <canvas
      ref={canvasRef}
      width={320}
      height={160}
      style={{
        width: "100%", height: 140, borderRadius: 8,
        background: T.panel, border: `1px solid ${T.border}`,
      }}
    />
  );
}

// ── Global EQ ──
export default function GlobalEQ({ onClose }) {
  const [values, setValues] = useState({
    low: 0,
    mid: 0,
    high: 0,
  });

  const update = useCallback((key, val) => {
    setValues(prev => ({ ...prev, [key]: val }));
  }, []);

  return (
    <div style={{
      position: "fixed", inset: 0, zIndex: 998,
      display: "flex", flexDirection: "column",
      background: T.bg, color: T.textPrimary,
      fontFamily: "'Inter', sans-serif",
    }}>
      {/* Header */}
      <div style={{
        display: "flex", alignItems: "center", justifyContent: "space-between",
        padding: "10px 14px",
        borderBottom: `1px solid ${T.border}`,
        background: T.panel, flexShrink: 0,
      }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <button onClick={onClose}
            style={{
              width: 34, height: 34, borderRadius: 8,
              display: "flex", alignItems: "center", justifyContent: "center",
              background: T.surface, border: `1px solid ${T.border}`,
              color: T.textPrimary, fontSize: 16, cursor: "pointer",
            }}>
            ✕
          </button>
          <div>
            <div style={{ fontSize: 15, fontWeight: 600 }}>Global EQ</div>
            <div style={{ fontSize: 10, color: T.textSec, marginTop: 1 }}>
              3-band shelving equalizer
            </div>
          </div>
        </div>
      </div>

      {/* Body */}
      <div style={{
        flex: 1, overflowY: "auto", overflowX: "hidden",
        padding: "8px 14px",
        display: "flex", flexDirection: "column", gap: 12,
      }}>
        {/* Frequency response graph */}
        <FrequencyGraph bands={EQ_BANDS} values={values} />

        {/* EQ band knobs */}
        <div style={{
          display: "flex", justifyContent: "space-around", gap: 8,
          background: T.surface, borderRadius: 8,
          border: `1px solid ${T.border}`,
          padding: "16px 8px",
        }}>
          {EQ_BANDS.map(band => (
            <EqKnob
              key={band.key}
              label={band.label}
              freq={band.freq}
              value={values[band.key]}
              min={-12}
              max={12}
              color={band.color}
              onChange={v => update(band.key, v)}
            />
          ))}
        </div>

        {/* Reset button */}
        <button onClick={() => setValues({ low: 0, mid: 0, high: 0 })}
          style={{
            width: "100%",
            padding: "10px 14px", borderRadius: 8,
            background: T.surface, border: `1px solid ${T.border}`,
            color: T.textSec, fontSize: 11, fontWeight: 600,
            cursor: "pointer", letterSpacing: ".06em",
          }}>
          Reset EQ to Flat
        </button>
      </div>
    </div>
  );
}
