import { useRef, 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",
};

const TYPE_COLORS = {
  overdrive: T.amber, drive: T.amber, distortion: T.red, fuzz: "#D060E0",
  chorus: T.blue, flanger: T.blue, phaser: T.blue, tremolo: T.blue,
  delay: "#60A0E0", echo: "#60A0E0", reverb: "#60C0D0",
  compressor: T.green, gate: T.green, eq: "#80A0B0",
  ir: T.green, cab: T.green, nam: "#E0A040",
};

function getBlockColor(type) {
  return TYPE_COLORS[(type || "").toLowerCase()] || T.amber;
}

function getShortLabel(type) {
  return {
    gate: "GATE", overdrive: "OD", distortion: "DST", fuzz: "FUZZ",
    chorus: "CHO", flanger: "FLN", phaser: "PHA", tremolo: "TRE",
    delay: "DLY", echo: "ECH", reverb: "REV",
    compressor: "CMP", eq: "EQ", cabinet: "CAB", ir: "IR", nam: "NAM",
  }[(type || "").toLowerCase()] || (type || "FX").toUpperCase().slice(0, 4);
}

// ── Single Footswitch with Scribble Strip ──
function Footswitch({ id, label, mainLabel, type, sub, active, enabled, onClick, onDoubleClick, isBank, bankDir }) {
  const tapRef = useRef(null);

  useEffect(() => {
    const el = tapRef.current;
    if (!el || !onDoubleClick) return;
    let lastTap = 0;
    const handler = () => {
      const now = Date.now();
      if (now - lastTap < 300) { onDoubleClick(id); lastTap = 0; }
      else { lastTap = now; }
    };
    el.addEventListener("click", handler);
    return () => el.removeEventListener("click", handler);
  }, [id, onDoubleClick]);

  const isBypassSwitch = type === "bypass";
  const isBankSwitch = type === "bank";
  const isActive = active || (isBypassSwitch && !enabled);
  const borderClr = isActive ? T.amber : isBankSwitch ? T.blueDim : T.border;

  return (
    <div
      ref={tapRef}
      onClick={() => onClick?.(id)}
      style={{
        flex: 1, minWidth: 0, display: "flex", flexDirection: "column",
        alignItems: "center", gap: 2, padding: "6px 3px 8px",
        borderRadius: 8, border: `1px solid ${borderClr}`,
        background: isActive && !isBypassSwitch
          ? `linear-gradient(180deg, ${T.amber}15 0%, ${T.panel} 100%)`
          : isBypassSwitch && !enabled
            ? `linear-gradient(180deg, ${T.red}15 0%, ${T.panel} 100%)`
            : T.surface,
        cursor: "pointer", minHeight: 58, position: "relative",
        transition: "all .1s", WebkitTapHighlightColor: "transparent",
        boxShadow: isActive && !isBypassSwitch
          ? `0 0 8px ${T.amber}33, inset 0 0 0 1px ${T.amber}22`
          : isBypassSwitch && !enabled ? `0 0 8px ${T.red}33` : "none",
      }}
    >
      {/* Scribble strip */}
      <div style={{
        width: "100%", background: "#0A0A10",
        border: `1px solid ${isActive ? T.amber + "66" : T.border}`,
        borderRadius: 3, padding: "2px 2px", textAlign: "center",
        minHeight: 18, display: "flex", alignItems: "center", justifyContent: "center",
        boxShadow: isActive ? `inset 0 0 4px ${T.amber}22` : "none",
      }}>
        <span style={{
          fontFamily: "'JetBrains Mono', monospace", fontSize: 7, fontWeight: 700,
          letterSpacing: ".02em",
          color: isActive ? T.amber : (isBypassSwitch && !enabled ? T.red : T.textPrimary),
          whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis",
          maxWidth: "100%", lineHeight: 1.1,
        }}>{label}</span>
      </div>

      {/* Main label */}
      <div style={{
        fontFamily: "'JetBrains Mono', monospace", fontSize: isBankSwitch ? 10 : 9,
        fontWeight: 700,
        color: enabled !== false ? T.textPrimary : T.textDim,
        whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis",
        maxWidth: "100%", lineHeight: 1.2, marginTop: 1,
      }}>{mainLabel || label || type || id || "FX"}</div>

      {/* Sub label */}
      {sub && (
        <div style={{
          fontSize: 7, color: T.textDim,
          whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis",
          maxWidth: "100%", lineHeight: 1,
        }}>{sub}</div>
      )}

      {/* LED */}
      {!isBankSwitch && (
        <div style={{
          position: "absolute", top: 3, right: 3, width: 4, height: 4,
          borderRadius: "50%",
          background: enabled !== false ? T.green : T.textDim,
          boxShadow: enabled !== false ? `0 0 5px ${T.green}` : "none",
          transition: "all .15s",
        }} />
      )}

      {/* Bank indicator */}
      {isBankSwitch && (
        <div style={{
          position: "absolute", top: 3, right: 3, fontSize: 6,
          padding: "1px 3px", borderRadius: 2,
          background: `${T.blueDim}88`, color: T.blue, fontWeight: 700, lineHeight: 1,
        }}>{bankDir === "up" ? "▲" : "▼"}</div>
      )}
    </div>
  );
}

// ── Footswitch Bar ──
export default function FootswitchBar({
  mode = "stomp",
  blocks = [],
  selectedBlockId,
  currentBank = "A",
  presets = [],
  currentPreset,
  snapshots = [],
  currentSnapshot,
  onSelectBlock,
  onToggleBlock,
  onBankUp,
  onBankDown,
  onGlobalBypass,
  globalBypass,
  onTunerToggle,
  tunerEnabled,
  onPresetClick,
  onSnapshotClick,
}) {
  let items = [];

  if (mode === "stomp" || mode === "stomp-b") {
    // Stomp mode: up to 6 block footswitches + global bypass
    const maxBlocks = blocks.length > 5 ? 6 : Math.max(4, blocks.length);
    const blockSwitches = blocks.slice(0, maxBlocks).map(b => ({
      id: b.id, type: "block",
      label: getShortLabel(b.type),
      mainLabel: b.name || b.type || "FX",
      sub: b.bypassed ? "BYPASSED" : "",
      enabled: !b.bypassed,
    }));
    // Fill remaining with empty slots
    while (blockSwitches.length < 5) {
      blockSwitches.push({ id: "empty_" + blockSwitches.length, type: "empty", label: "—", mainLabel: "Empty", enabled: false });
    }
    items = [
      ...blockSwitches.slice(0, 5),
      { id: "bypass", type: "bypass", label: globalBypass ? "MUTED" : "BYPASS", mainLabel: "GLOBAL", sub: globalBypass ? "" : "tap to mute", enabled: !globalBypass },
    ];
  } else if (mode === "preset") {
    // Preset mode: bank up/down + 4 presets
    items = [
      { id: "bank_up", type: "bank", label: "BANK ▲", mainLabel: `${currentBank} · ${currentPreset}`, bankDir: "up", enabled: true },
      ...presets.slice(0, 4).map((p, i) => ({
        id: "preset_" + i, type: "preset",
        label: `0${p.num || (i+1)}`,
        mainLabel: p.name || `P${i+1}`,
        sub: p.num === currentPreset ? "ACTIVE" : "",
        enabled: true,
      })),
      { id: "bank_down", type: "bank", label: "BANK ▼", mainLabel: `${currentBank} · ${currentPreset}`, bankDir: "down", enabled: true },
    ];
  } else if (mode === "snapshot") {
    // Snapshot mode (placeholder for future snapshot feature)
    items = [
      ...snapshots.slice(0, 6).map((s, i) => ({
        id: "snap_" + (s.num || i), type: "snapshot",
        label: `SNAP ${s.num || (i+1)}`,
        mainLabel: s.name || `Snapshot ${s.num || (i+1)}`,
        sub: (s.num || i+1) === currentSnapshot ? "ACTIVE" : "",
        enabled: true,
      })),
    ];
    while (items.length < 6) {
      items.push({ id: "snap_empty_" + items.length, type: "empty", label: "—", mainLabel: "Empty", enabled: false });
    }
  }

  return (
    <div style={{
      display: "flex", gap: 4, padding: "6px 8px 10px",
      background: T.bg, borderTop: `1px solid ${T.border}`, flexShrink: 0,
    }}>
      {items.map(item => (
        <Footswitch
          key={item.id}
          id={item.id}
          label={item.label}
          mainLabel={item.mainLabel}
          type={item.type}
          sub={item.sub}
          active={item.id === selectedBlockId || (item.type === "preset" && item.sub === "ACTIVE") || (item.type === "snapshot" && item.sub === "ACTIVE")}
          enabled={item.enabled}
          isBank={item.type === "bank"}
          bankDir={item.bankDir}
          onClick={(id) => {
            if (id === "bank_up") onBankUp?.();
            else if (id === "bank_down") onBankDown?.();
            else if (id === "bypass") onGlobalBypass?.();
            else if (id?.startsWith("preset_")) onPresetClick?.(id.replace("preset_", ""));
            else if (id?.startsWith("snap_")) onSnapshotClick?.(id.replace("snap_", ""));
            else if (mode === "stomp" || mode === "stomp-b") onSelectBlock?.(id);
          }}
          onDoubleClick={(id) => {
            if (id !== "bank_up" && id !== "bank_down" && id !== "bypass" && (mode === "stomp" || mode === "stomp-b")) {
              onToggleBlock?.(id);
            }
          }}
        />
      ))}
    </div>
  );
}
