/**
 * Pi Multi-FX Pedal — App Shell
 *
 * Main application with:
 * - Status bar (mode selector, connection status, CPU, sample rate)
 * - Screen area (tab content: Rig, FX Chain, Models, IRs, Presets, Settings)
 * - Footswitch bar (8 footswitches with dynamic scribble strips per mode)
 * - Tab bar (bottom navigation)
 */

import { useState, useEffect, useCallback } from 'react';
import { usePedalState, fetchPresets, apiPost, apiPut, apiGet, apiUpload } from './pedal/hooks/usePedalState';
import { FootswitchModeProvider } from './pedal/FootswitchModeContext';
import { FootswitchBar } from './pedal/footswitch/FootswitchBar';
import { ModeSelector } from './pedal/footswitch/ModeSelector';
import type { PedalState, PedalBlock, BankData } from './pedal/types';
import './pedal/pedal.css';

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

// ── VU Meter ─────────────────────────────────────────────────

function VUMeter({ level = 0, height = 60 }: { level?: number; height?: number }) {
  const segs = 12;
  const active = Math.round((level / 100) * segs);
  const segColor = (i: number) => {
    if (i >= 10) return T.red;
    if (i >= 8) return '#E8C030';
    return T.green;
  };
  return (
    <div style={{ display: 'flex', flexDirection: 'column-reverse', gap: 2, height, alignItems: 'center' }}>
      {Array.from({ length: segs }).map((_, i) => (
        <div key={i} style={{
          width: 6, height: (height - segs * 2) / segs,
          borderRadius: 1, background: i < active ? segColor(i) : T.border,
          boxShadow: i < active ? `0 0 4px ${segColor(i)}` : 'none',
          transition: 'background 0.05s, box-shadow 0.05s',
        }} />
      ))}
    </div>
  );
}

// ── FX Type Labels ───────────────────────────────────────────

const FX_TYPE_LABELS: Record<string, string> = {
  noise_gate: 'Noise Gate', compressor: 'Compressor', boost: 'Boost',
  overdrive: 'Overdrive', distortion: 'Distortion', fuzz: 'Fuzz',
  eq: 'EQ', chorus: 'Chorus', flanger: 'Flanger', phaser: 'Phaser',
  tremolo: 'Tremolo', vibrato: 'Vibrato', delay: 'Delay', reverb: 'Reverb',
  volume: 'Volume', nam_amp: 'NAM Amp', ir_cab: 'IR Cab',
  octaver: 'Octaver', pitch_shifter: 'Pitch Shifter', harmonizer: 'Harmonizer',
  whammy: 'Whammy', detune: 'Detune', ring_modulator: 'Ring Mod',
  auto_wah: 'Auto Wah', envelope_filter: 'Env Filter', rotary_speaker: 'Rotary',
  uni_vibe: 'Uni-Vibe', auto_pan: 'Auto Pan', stereo_widener: 'Stereo Widener',
  bitcrusher: 'Bitcrusher', wavefolder: 'Wavefolder', rectifier: 'Rectifier',
  expander: 'Expander', de_esser: 'De-esser', transient_shaper: 'Transient Shaper',
  parametric_eq: 'Parametric EQ', high_pass_filter: 'High Pass',
  low_pass_filter: 'Low Pass', band_pass_filter: 'Band Pass',
  notch_filter: 'Notch Filter', formant_filter: 'Formant Filter',
  ping_pong_delay: 'Ping Pong Delay', multi_tap_delay: 'Multi Tap',
  reverse_delay: 'Reverse Delay', tape_echo: 'Tape Echo',
  shimmer_reverb: 'Shimmer Reverb', early_reflections: 'Early Reflections',
  sidechain_compressor: 'Sidechain Comp', looper: 'Looper',
};

// ══════════════════════════════════════════════════════════════
// RIG SCREEN
// ══════════════════════════════════════════════════════════════

function RigScreen({ state, connected }: { state: PedalState | null; connected: boolean; refresh?: () => void }) {
  const [volume, setVolume] = useState<number>(
    state?.master_volume != null ? Math.round(state.master_volume * 100) : 80
  );
  const [localBypass, setLocalBypass] = useState<boolean | null>(null);
  const [localTuner, setLocalTuner] = useState<boolean | null>(null);

  const bypass = localBypass ?? state?.bypass ?? false;
  const tuner = localTuner ?? state?.tuner_enabled ?? false;

  useEffect(() => {
    if (state?.master_volume != null) setVolume(Math.round(state.master_volume * 100));
  }, [state?.master_volume]);

  useEffect(() => {
    if (state?.bypass !== undefined) setLocalBypass(null);
    if (state?.tuner_enabled !== undefined) setLocalTuner(null);
  }, [state?.bypass, state?.tuner_enabled]);

  const handleVolume = async (val: number) => {
    setVolume(val);
    try { await apiPut('/api/volume', { volume: val / 100 }); } catch {}
  };

  const handleBypass = async () => {
    const next = !bypass;
    setLocalBypass(next);
    try { await apiPost('/api/bypass', { bypass: next }); } catch { setLocalBypass(null); }
  };

  const handleTuner = async () => {
    const next = !tuner;
    setLocalTuner(next);
    try { await apiPost('/api/tuner', { enabled: next }); } catch { setLocalTuner(null); }
  };

  const inputLevel = state?.input_level ?? 0;
  const outputLevel = state?.output_level ?? 0;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <div className="screen-header">
        <div>
          <div style={{ fontSize: 13, fontWeight: 600, letterSpacing: '0.06em', textTransform: 'uppercase', color: T.textSec }}>Active Rig</div>
          <div style={{ display: 'flex', gap: 6, marginTop: 4, flexWrap: 'wrap', alignItems: 'center' }}>
            {state?.current_preset ? (
              <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 11, color: T.amber, border: `1px solid ${T.amber}55`, background: `${T.amber}15`, padding: '3px 8px', borderRadius: 5 }}>
                {state.current_preset.name}
              </span>
            ) : (
              <span style={{ fontSize: 11, color: T.textDim }}>No preset loaded</span>
            )}
            {connected ? (
              <span className="pedal-badge pedal-badge-green">Connected</span>
            ) : (
              <span className="pedal-badge pedal-badge-red">Offline</span>
            )}
          </div>
        </div>
        <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
          <VUMeter level={inputLevel} height={44} />
          <VUMeter level={outputLevel} height={44} />
        </div>
      </div>
      <div style={{ flex: 1, overflowY: 'auto', padding: 12, display: 'flex', flexDirection: 'column', gap: 12 }}>
        {/* Status row */}
        <div style={{ background: T.surface, border: `1px solid ${T.border}`, borderRadius: 8, padding: 12, display: 'flex', gap: 10, justifyContent: 'space-around' }}>
          <div style={{ textAlign: 'center' }}>
            <div className="section-label">Bypass</div>
            <div className={`switch ${bypass ? 'on' : ''}`} onClick={handleBypass} style={{ margin: '0 auto' }} />
          </div>
          <div style={{ textAlign: 'center' }}>
            <div className="section-label">Tuner</div>
            <div className={`switch ${tuner ? 'on' : ''}`} onClick={handleTuner} style={{ margin: '0 auto' }} />
          </div>
          <div style={{ textAlign: 'center' }}>
            <div className="section-label">Routing</div>
            <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 12, color: T.amber }}>{state?.routing_mode || 'mono'}</span>
          </div>
        </div>

        {/* Tuner */}
        {tuner && (
          <div style={{ background: `${T.amber}15`, border: `1px solid ${T.amber}`, borderRadius: 8, textAlign: 'center', padding: '20px 16px' }}>
            <div style={{ fontSize: 32, marginBottom: 8 }}>🎵</div>
            <div className="section-label" style={{ color: T.amber, marginBottom: 4, fontSize: 14 }}>TUNER ACTIVE</div>
            <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 24, color: T.amber, letterSpacing: 4 }}>—————●—————</div>
            <div style={{ fontSize: 11, color: T.textDim, marginTop: 8 }}>Tap switch again to exit tuner mode</div>
          </div>
        )}

        {/* Volume */}
        <div style={{ background: T.panel, border: `1px solid ${T.border}`, borderRadius: 10, padding: 16, display: 'flex', gap: 20, alignItems: 'center' }}>
          <div style={{ flex: 1 }}>
            <div className="section-label">Master Volume</div>
            <input type="range" min={0} max={100} value={volume}
              onChange={e => handleVolume(+e.target.value)}
              style={{ width: '100%', accentColor: T.amber }} />
            <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 11, color: T.amber, marginTop: 4 }}>{volume}%</div>
          </div>
          <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 11, color: T.textSec, textAlign: 'right' }}>
            {state?.nam_loaded ? 'NAM: Active' : 'NAM: —'}<br />
            {state?.ir_loaded ? 'IR: Active' : 'IR: —'}
          </div>
        </div>

        {/* Signal chain */}
        <div style={{ background: T.surface, border: `1px solid ${T.border}`, borderRadius: 8, padding: 12 }}>
          <div className="section-label">Signal Chain</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 4, overflowX: 'auto', padding: '4px 0' }}>
            {['IN', state?.bypass ? 'BYP' : (state?.nam_loaded ? 'NAM' : 'AMP'), state?.ir_loaded ? 'IR' : 'CAB', 'OUT'].map((s, i, arr) => (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 4, flexShrink: 0 }}>
                <div style={{ padding: '3px 8px', borderRadius: 4, fontSize: 10, fontWeight: 700,
                  background: i === 0 || i === arr.length - 1 ? T.blueDim : T.amberDim,
                  color: i === 0 || i === arr.length - 1 ? T.blue : T.amber,
                  border: `1px solid ${(i === 0 || i === arr.length - 1 ? T.blue : T.amber)}60` }}>{s}</div>
                {i < arr.length - 1 && <div style={{ width: 16, height: 2, background: T.border, borderRadius: 1 }} />}
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

// ══════════════════════════════════════════════════════════════
// FX CHAIN SCREEN
// ══════════════════════════════════════════════════════════════

function FXBlock({ title, type, active = true, bypassed = false }: {
  title: string; type: string; active?: boolean; bypassed?: boolean;
}) {
  const [open, setOpen] = useState(true);
  return (
    <div style={{ background: T.panel, border: `1px solid ${active ? T.amber : T.border}`, borderRadius: 10, overflow: 'hidden', opacity: bypassed ? 0.45 : 1 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px', borderBottom: `1px solid ${T.border}`, background: T.surface, cursor: 'pointer' }}
        onClick={() => setOpen(o => !o)}>
        <div style={{ width: 8, height: 8, borderRadius: '50%', background: !bypassed ? T.green : T.textDim, boxShadow: !bypassed ? `0 0 8px ${T.green}` : 'none' }} />
        <span style={{ flex: 1, fontSize: 13, fontWeight: 600 }}>{title}</span>
        <span className="pedal-badge pedal-badge-blue" style={{ fontSize: 10, padding: '2px 7px' }}>{type}</span>
        <span style={{ color: T.textDim, fontSize: 18, marginLeft: 6 }}>{open ? '▾' : '▸'}</span>
      </div>
    </div>
  );
}

function FXScreen({ state, connected }: { state: PedalState | null; connected: boolean }) {
  const [fxList, setFxList] = useState<{ id: number; title: string; type: string; bypassed: boolean }[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!connected || !state?.current_preset) { setFxList([]); setLoading(false); return; }
    fetchPresets().then(data => {
      const banks = data.banks || [];
      const cp = state.current_preset;
      const preset = cp ? banks[cp.bank]?.presets?.[cp.program] : null;
      if (preset?.chain) {
        setFxList(preset.chain.map((b, i) => ({
          id: i + 1,
          title: FX_TYPE_LABELS[b.fx_type] || b.fx_type,
          type: b.fx_type,
          bypassed: b.bypassed ?? false,
        })));
      }
      setLoading(false);
    }).catch(() => { setFxList([]); setLoading(false); });
  }, [connected, state]);

  if (loading) return <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><div className="loader" /></div>;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <div className="screen-header">
        <div style={{ fontSize: 13, fontWeight: 600, letterSpacing: '0.06em', textTransform: 'uppercase', color: T.textSec }}>FX Chain {fxList.length > 0 ? `(${fxList.length})` : ''}</div>
      </div>
      <div style={{ flex: 1, overflowY: 'auto', padding: 12, display: 'flex', flexDirection: 'column', gap: 12 }}>
        {fxList.length === 0 ? (
          <div style={{ textAlign: 'center', padding: 30, color: T.textDim, fontSize: 14 }}>No FX blocks in the chain.</div>
        ) : (
          fxList.map(f => <FXBlock key={f.id} {...f} active={!f.bypassed} />)
        )}
      </div>
    </div>
  );
}

// ══════════════════════════════════════════════════════════════
// MODELS SCREEN
// ══════════════════════════════════════════════════════════════

function ModelsScreen({ connected, refresh }: { state?: PedalState | null; connected: boolean; refresh: () => void }) {
  const [models, setModels] = useState<{ name: string; path?: string; architecture?: string; size_mb?: string; loaded?: boolean }[]>([]);
  const [current, setCurrent] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [fileRef, setFileRef] = useState<HTMLInputElement | null>(null);

  const loadModels = useCallback(async () => {
    if (!connected) { setLoading(false); return; }
    try {
      const data = await apiGet<{ models?: any[]; current?: string }>('/api/models');
      setModels(data.models || []);
      setCurrent(data.current ?? null);
    } catch {}
    setLoading(false);
  }, [connected]);

  useEffect(() => { loadModels(); }, [loadModels]);

  const handleLoad = async (path?: string) => {
    if (!path) return;
    try { await apiPost('/api/models/load', { path }); await loadModels(); refresh(); } catch { alert('Failed to load model'); }
  };

  const handleUnload = async () => {
    try { await apiPost('/api/models/unload'); setCurrent(null); await loadModels(); refresh(); } catch { alert('Failed to unload'); }
  };

  const handleUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    try { await apiUpload('/api/models/upload', file); await loadModels(); } catch { alert('Upload failed'); }
  };

  if (loading) return <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><div className="loader" /></div>;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <div className="screen-header">
        <div style={{ fontSize: 13, fontWeight: 600, letterSpacing: '0.06em', textTransform: 'uppercase', color: T.textSec }}>NAM Models ({models.length})</div>
        <button className="btn btn-primary btn-sm" onClick={() => fileRef?.click()}>+ Upload</button>
        <input ref={el => setFileRef(el)} type="file" accept=".nam" style={{ display: 'none' }} onChange={handleUpload} />
      </div>
      <div style={{ flex: 1, overflowY: 'auto', padding: 12, display: 'flex', flexDirection: 'column', gap: 8 }}>
        {current && (
          <div style={{ background: T.surface, border: `1px solid ${T.border}`, borderRadius: 8, padding: 12 }}>
            <div className="section-label">Loaded Model</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 11, color: T.blue, border: `1px solid ${T.blue}55`, background: `${T.blue}15`, padding: '3px 8px', borderRadius: 5 }}>{current}</span>
              <button className="btn btn-danger btn-sm" onClick={handleUnload}>Unload</button>
            </div>
          </div>
        )}
        {models.length === 0 ? (
          <div style={{ textAlign: 'center', padding: 30, color: T.textDim, fontSize: 14 }}>No NAM models found.</div>
        ) : (
          models.map(m => (
            <div key={m.name} className="preset-row"
              style={{ border: m.loaded ? `1px solid ${T.amber}40` : '1px solid transparent', background: m.loaded ? `${T.amber}08` : 'transparent' }}
              onClick={() => !m.loaded && handleLoad(m.path)}>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 500 }}>{m.name}</div>
                <div style={{ fontSize: 10, color: T.textDim }}>{m.architecture} · {m.size_mb} MB</div>
              </div>
              {m.loaded ? <span className="pedal-badge pedal-badge-green">Loaded</span> : <button className="btn btn-ghost btn-sm">Load</button>}
            </div>
          ))
        )}
      </div>
    </div>
  );
}

// ══════════════════════════════════════════════════════════════
// IRS SCREEN
// ══════════════════════════════════════════════════════════════

function IRsScreen({ connected, refresh }: { state?: PedalState | null; connected: boolean; refresh: () => void }) {
  const [irs, setIrs] = useState<{ name: string; path?: string; sample_rate?: number; length_ms?: number; loaded?: boolean }[]>([]);
  const [current, setCurrent] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [fileRef, setFileRef] = useState<HTMLInputElement | null>(null);

  const loadIrs = useCallback(async () => {
    if (!connected) { setLoading(false); return; }
    try {
      const data = await apiGet<{ irs?: any[]; current?: string }>('/api/irs');
      setIrs(data.irs || []);
      setCurrent(data.current ?? null);
    } catch {}
    setLoading(false);
  }, [connected]);

  useEffect(() => { loadIrs(); }, [loadIrs]);

  const handleLoad = async (path?: string) => {
    if (!path) return;
    try { await apiPost('/api/irs/load', { path }); await loadIrs(); refresh(); } catch { alert('Failed to load IR'); }
  };

  const handleUnload = async () => {
    try { await apiPost('/api/irs/unload'); setCurrent(null); await loadIrs(); refresh(); } catch { alert('Failed to unload'); }
  };

  const handleUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    try { await apiUpload('/api/irs/upload', file); await loadIrs(); } catch { alert('Upload failed'); }
  };

  if (loading) return <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><div className="loader" /></div>;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <div className="screen-header">
        <div style={{ fontSize: 13, fontWeight: 600, letterSpacing: '0.06em', textTransform: 'uppercase', color: T.textSec }}>IR Files ({irs.length})</div>
        <button className="btn btn-primary btn-sm" onClick={() => fileRef?.click()}>+ Upload</button>
        <input ref={el => setFileRef(el)} type="file" accept=".wav" style={{ display: 'none' }} onChange={handleUpload} />
      </div>
      <div style={{ flex: 1, overflowY: 'auto', padding: 12, display: 'flex', flexDirection: 'column', gap: 8 }}>
        {current && (
          <div style={{ background: T.surface, border: `1px solid ${T.border}`, borderRadius: 8, padding: 12 }}>
            <div className="section-label">Loaded IR</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 11, color: T.green, border: `1px solid ${T.green}55`, background: `${T.green}15`, padding: '3px 8px', borderRadius: 5 }}>{current}</span>
              <button className="btn btn-danger btn-sm" onClick={handleUnload}>Unload</button>
            </div>
          </div>
        )}
        {irs.length === 0 ? (
          <div style={{ textAlign: 'center', padding: 30, color: T.textDim, fontSize: 14 }}>No IR files found.</div>
        ) : (
          irs.map(ir => (
            <div key={ir.name} className="preset-row"
              style={{ border: ir.loaded ? `1px solid ${T.amber}40` : '1px solid transparent', background: ir.loaded ? `${T.amber}08` : 'transparent' }}
              onClick={() => !ir.loaded && handleLoad(ir.path)}>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 500 }}>{ir.name}</div>
                <div style={{ fontSize: 10, color: T.textDim }}>{ir.sample_rate} Hz · {ir.length_ms} ms</div>
              </div>
              {ir.loaded ? <span className="pedal-badge pedal-badge-green">Loaded</span> : <button className="btn btn-ghost btn-sm">Load</button>}
            </div>
          ))
        )}
      </div>
    </div>
  );
}

// ══════════════════════════════════════════════════════════════
// PRESETS SCREEN
// ══════════════════════════════════════════════════════════════

function PresetsScreen({ state, connected, refresh }: { state: PedalState | null; connected: boolean; refresh: () => void }) {
  const [banks, setBanks] = useState<BankData[]>([]);
  const [selectedBank, setSelectedBank] = useState(0);
  const [loading, setLoading] = useState(true);

  const loadPresets = useCallback(async () => {
    if (!connected) {
      setBanks([{ name: 'Default', number: 0, presets: [{ name: 'Edge of Breakup', bank: 0, program: 0 }, { name: 'Modern High Gain', bank: 0, program: 1 }, null, null] }]);
      setLoading(false);
      return;
    }
    try {
      const data = await fetchPresets();
      setBanks(data.banks || []);
    } catch {}
    setLoading(false);
  }, [connected]);

  useEffect(() => { loadPresets(); }, [loadPresets]);

  const handleActivate = async (bank: number, program: number) => {
    try { await apiPost(`/api/presets/${bank}/${program}/activate`); await loadPresets(); refresh(); } catch { alert('Failed to load preset'); }
  };

  if (loading) return <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><div className="loader" /></div>;

  const currentPreset = state?.current_preset;
  const bankData = banks[selectedBank];
  const presets = bankData?.presets || [];

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <div className="screen-header">
        <div style={{ fontSize: 13, fontWeight: 600, letterSpacing: '0.06em', textTransform: 'uppercase', color: T.textSec }}>Presets</div>
      </div>
      <div style={{ flex: 1, overflowY: 'auto', padding: 12, display: 'flex', flexDirection: 'column', gap: 8 }}>
        {banks.length > 1 && (
          <div style={{ display: 'flex', background: T.surface, borderRadius: 6, border: `1px solid ${T.border}`, overflow: 'hidden' }}>
            {banks.map((b, i) => (
              <button key={b.number} style={{
                flex: 1, padding: '7px 12px', fontSize: 12, fontWeight: 500, letterSpacing: '0.04em',
                background: selectedBank === i ? T.amber : 'none', border: 'none',
                color: selectedBank === i ? '#000' : T.textSec, cursor: 'pointer', transition: 'all 0.15s',
              }} onClick={() => setSelectedBank(i)}>{b.name}</button>
            ))}
          </div>
        )}
        {currentPreset && (
          <div style={{ background: T.surface, border: `1px solid ${T.border}`, borderRadius: 8, padding: 12, display: 'flex', alignItems: 'center', gap: 8 }}>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 11, color: T.textDim }}>Current</div>
              <div style={{ fontSize: 14, fontWeight: 600, color: T.amber }}>
                {currentPreset.name}
                <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10, color: T.textDim, marginLeft: 8 }}>Bank {currentPreset.bank} · Prog {currentPreset.program}</span>
              </div>
            </div>
          </div>
        )}
        {presets.length === 0 ? (
          <div style={{ textAlign: 'center', padding: 30, color: T.textDim, fontSize: 14 }}>No presets in this bank.</div>
        ) : (
          presets.map((p, i) => {
            if (!p) return null;
            const isActive = currentPreset?.bank === p.bank && currentPreset?.program === p.program;
            return (
              <div key={i} className="preset-row"
                style={{ border: isActive ? `1px solid ${T.amber}40` : '1px solid transparent', background: isActive ? `${T.amber}08` : 'transparent' }}
                onClick={() => handleActivate(p.bank, p.program)}>
                <div style={{
                  width: 28, height: 28, borderRadius: 6, display: 'flex', alignItems: 'center',
                  justifyContent: 'center', fontSize: 12, fontWeight: 700,
                  background: isActive ? `${T.amber}22` : T.surface,
                  color: isActive ? T.amber : T.textDim,
                  border: `1px solid ${isActive ? `${T.amber}60` : T.border}`,
                  fontFamily: "'JetBrains Mono', monospace",
                }}>{p.program + 1}</div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, fontWeight: 600 }}>{p.name}</div>
                  <div style={{ fontSize: 10, color: T.textDim }}>Bank {p.bank} · Program {p.program}</div>
                </div>
                {isActive && <span style={{ color: T.amber, fontSize: 16 }}>●</span>}
              </div>
            );
          })
        )}
      </div>
    </div>
  );
}

// ══════════════════════════════════════════════════════════════
// SETTINGS SCREEN
// ══════════════════════════════════════════════════════════════

function SettingsScreen({ state: pedalState }: { state: PedalState | null; refresh?: () => void }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <div className="screen-header">
        <div style={{ fontSize: 13, fontWeight: 600, letterSpacing: '0.06em', textTransform: 'uppercase', color: T.textSec }}>Settings</div>
      </div>
      <div style={{ flex: 1, overflowY: 'auto', padding: 12, display: 'flex', flexDirection: 'column', gap: 8 }}>
        <div style={{ background: T.surface, border: `1px solid ${T.border}`, borderRadius: 8, padding: 12 }}>
          <div className="section-label">System</div>
          {pedalState?.cpu_percent != null && (
            <div className="setting-row">
              <span style={{ fontSize: 13 }}>CPU</span>
              <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 11, color: T.amber }}>{pedalState.cpu_percent}%</span>
            </div>
          )}
          {pedalState?.sample_rate && (
            <div className="setting-row">
              <span style={{ fontSize: 13 }}>Sample Rate</span>
              <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 11, color: T.amber }}>{pedalState.sample_rate / 1000}kHz</span>
            </div>
          )}
          <div className="setting-row" style={{ border: 'none' }}>
            <span style={{ fontSize: 13 }}>Connection</span>
            <span className="pedal-badge pedal-badge-green">Live</span>
          </div>
        </div>
      </div>
    </div>
  );
}

// ══════════════════════════════════════════════════════════════
// APP SHELL
// ══════════════════════════════════════════════════════════════

const TABS = [
  { id: 'rig', label: 'Rig', icon: '🎛' },
  { id: 'fx', label: 'FX', icon: '⛓' },
  { id: 'models', label: 'Models', icon: '📁' },
  { id: 'irs', label: 'IRs', icon: '🎚' },
  { id: 'presets', label: 'Presets', icon: '⭐' },
  { id: 'settings', label: 'Settings', icon: '⚙' },
] as const;

type TabId = (typeof TABS)[number]['id'];

// ── Pedal Shell Content (inner component that has context access) ──

function PedalContent() {
  const [tab, setTab] = useState<TabId>('rig');
  const { state, connected, refresh } = usePedalState();

  // Build block list from current preset state
  const [blocks, setBlocks] = useState<PedalBlock[]>([]);
  const [bankNames, setBankNames] = useState<string[]>(['Default']);

  useEffect(() => {
    if (connected && state?.current_preset) {
      fetchPresets().then(data => {
        const names = (data.banks || []).map((b: BankData) => b.name);
        if (names.length > 0) setBankNames(names);

        const cp = state.current_preset;
        const bank = data.banks?.[cp.bank];
        const preset = bank?.presets?.[cp.program];
        if (preset?.chain) {
          setBlocks(preset.chain.map((b, i) => ({
            id: i + 1,
            fx_type: b.fx_type,
            title: FX_TYPE_LABELS[b.fx_type] || b.fx_type,
            bypassed: b.bypassed ?? false,
          })));
        }
      }).catch(() => {});
    }
  }, [connected, state?.current_preset]);

  const handleToggleBlock = useCallback(async (blockId: number, newBypass: boolean) => {
    setBlocks(prev => prev.map(b => b.id === blockId ? { ...b, bypassed: newBypass } : b));
    if (connected) {
      try { await apiPost('/api/blocks/toggle', { block_id: blockId, bypass: newBypass }); } catch {}
    }
  }, [connected]);

  // Snapshots (placeholder — will be wired to real API)
  const [snapshots] = useState<{ name: string; active: boolean }[]>(
    Array.from({ length: 8 }, (_, i) => ({ name: `Snap ${i + 1}`, active: false }))
  );

  return (
    <FootswitchModeProvider
      state={state}
      connected={connected}
      refresh={refresh}
      blocks={blocks}
      bankNames={bankNames}
      snapshots={snapshots}
      onToggleBlock={handleToggleBlock}
    >
      <div className="pedal-shell">
        {/* ── Status Bar ── */}
        <div className="pedal-statusbar">
          <div className="pedal-statusbar-left">
            <div className="pedal-led-dot" style={{
              background: connected ? T.green : T.red,
              boxShadow: connected ? `0 0 6px ${T.green}` : 'none',
            }} />
            <span className="pedal-brand">PI MULTI-FX</span>
            {state?.tuner_enabled && <span className="pedal-badge pedal-badge-amber">TUNER</span>}
          </div>
          <div className="pedal-statusbar-mid">
            <ModeSelector collapsed />
          </div>
          <div className="pedal-statusbar-right">
            {state?.cpu_percent != null && (
              <span className="pedal-brand" style={{ color: T.textDim }}>CPU {state.cpu_percent}%</span>
            )}
            {state?.sample_rate && (
              <span className="pedal-brand" style={{ color: T.textDim }}>{state.sample_rate / 1000}kHz</span>
            )}
            {state?.bypass && <span className="pedal-badge pedal-badge-red">BYP</span>}
            {state?.nam_loaded && <span className="pedal-badge pedal-badge-blue">NAM</span>}
            {state?.ir_loaded && <span className="pedal-badge pedal-badge-green">IR</span>}
          </div>
        </div>

        {/* ── Screen Area ── */}
        <div className="pedal-screen">
          {tab === 'rig' && <RigScreen state={state} connected={connected} />}
          {tab === 'fx' && <FXScreen state={state} connected={connected} />}
          {tab === 'models' && <ModelsScreen connected={connected} refresh={refresh} />}
          {tab === 'irs' && <IRsScreen connected={connected} refresh={refresh} />}
          {tab === 'presets' && <PresetsScreen state={state} connected={connected} refresh={refresh} />}
          {tab === 'settings' && <SettingsScreen state={state} />}
        </div>

        {/* ── Footswitch Bar ── */}
        <FootswitchBar />

        {/* ── Tab Bar ── */}
        <div className="pedal-tabbar">
          {TABS.map(t => (
            <div key={t.id} className={`pedal-tab ${tab === t.id ? 'pedal-tab-active' : ''}`} onClick={() => setTab(t.id)}>
              <span className="pedal-tab-icon">{t.icon}</span>
              {t.label}
            </div>
          ))}
        </div>
      </div>
    </FootswitchModeProvider>
  );
}

// ── Root App ─────────────────────────────────────────────────

export default function App() {
  useEffect(() => { document.title = 'Pi Multi-FX Pedal'; }, []);

  return (
    <>
      {/* Global styles for inline-styled components */}
      <style>{`
        .switch { width: 40px; height: 22px; border-radius: 11px; background: ${T.border}; cursor: pointer; position: relative; transition: background 0.2s; flex-shrink: 0; display: inline-block; }
        .switch.on { background: ${T.green}; }
        .switch::after { content: ''; position: absolute; top: 2px; left: 2px; width: 18px; height: 18px; border-radius: 50%; background: white; transition: transform 0.15s; }
        .switch.on::after { transform: translateX(18px); }

        .btn { padding: 10px 18px; border-radius: 7px; font-size: 13px; font-weight: 600; letter-spacing: 0.04em; border: none; cursor: pointer; transition: all 0.12s; }
        .btn-primary { background: ${T.amber}; color: #000; }
        .btn-primary:active { filter: brightness(0.85); transform: scale(0.97); }
        .btn-ghost { background: ${T.surface}; color: ${T.text}; border: 1px solid ${T.border}; }
        .btn-ghost:active { background: ${T.border}; }
        .btn-danger { background: rgba(200,64,64,0.2); color: ${T.red}; border: 1px solid rgba(200,64,64,0.3); }
        .btn-sm { padding: 6px 12px; font-size: 12px; }

        .loader { width: 20px; height: 20px; border: 2px solid ${T.border}; border-top-color: ${T.amber}; border-radius: 50%; animation: spin 0.6s linear infinite; }
        @keyframes spin { to { transform: rotate(360deg); } }

        .screen-header { padding: 10px 14px 6px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid ${T.border}; flex-shrink: 0; }
        .section-label { font-size: 10px; letter-spacing: 0.1em; text-transform: uppercase; color: ${T.textDim}; font-weight: 600; margin-bottom: 8px; }
        .preset-row { display: flex; align-items: center; gap: 12px; padding: 10px 12px; border-radius: 8px; cursor: pointer; transition: background 0.12s; }
        .preset-row:active { background: rgba(232,160,48,0.08); }
        .setting-row { display: flex; align-items: center; justify-content: space-between; padding: 8px 0; border-bottom: 1px solid ${T.border}; }

        ::-webkit-scrollbar { width: 4px; height: 4px; }
        ::-webkit-scrollbar-track { background: ${T.panel}; }
        ::-webkit-scrollbar-thumb { background: ${T.border}; border-radius: 2px; }
      `}</style>
      <PedalContent />
    </>
  );
}
