<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from "vue";
import { invoke } from "@tauri-apps/api/core";
import type {
  Settings,
  GetSettingsResponse,
  EncoderPreset,
  NvencPreset,
  AmfPreset,
  X264Preset,
  DaemonStatusResponse,
  EncodersResponse,
} from "../types/daemon";
import {
  QUALITY_LEVELS,
  CONTAINER_FORMATS,
  LOG_LEVELS,
  X264_PRESETS,
  AMF_QUALITIES,
} from "../types/daemon";

// Emits
const emit = defineEmits<{
  (e: "back"): void;
}>();

// ---------------------------------------------------------------------------
// State
// ---------------------------------------------------------------------------

const loading = ref(true);
const error = ref<string | null>(null);
const saving = ref(false);
const saveSuccess = ref(false);
const settings = ref<Settings | null>(null);
const daemonStatus = ref<DaemonStatusResponse | null>(null);
const encoders = ref<EncodersResponse | null>(null);
const daemonRunning = ref(false);
const statusPolling = ref<ReturnType<typeof setInterval> | null>(null);
const autostartEnabled = ref(false);
const autostartLoading = ref(false);

// Active settings tab
type SettingsTab = "video" | "output" | "audio" | "daemon";
const activeTab = ref<SettingsTab>("video");

// ---------------------------------------------------------------------------
// Load data
// ---------------------------------------------------------------------------

async function loadSettings() {
  try {
    loading.value = true;
    error.value = null;

    // Check if daemon is running
    daemonRunning.value = await invoke<boolean>("daemon_is_running");

    if (daemonRunning.value) {
      // Load settings from daemon via IPC
      const settingsData = await invoke<GetSettingsResponse>("daemon_get_settings");
      settings.value = settingsData.settings;

      // Load status
      try {
        daemonStatus.value = await invoke<DaemonStatusResponse>("daemon_get_status");
      } catch {
        daemonStatus.value = null;
      }

      // Load encoders
      try {
        const encodersData = await invoke<EncodersResponse>("daemon_get_encoders");
        encoders.value = encodersData;
      } catch {
        encoders.value = null;
      }
    } else {
      settings.value = null;
    }
  } catch (e) {
    error.value = `Failed to load settings: ${e}`;
  } finally {
    loading.value = false;
  }
}

async function refreshStatus() {
  if (!daemonRunning.value) return;
  try {
    daemonStatus.value = await invoke<DaemonStatusResponse>("daemon_get_status");
  } catch {
    // Silently ignore - daemon might have stopped
  }
  try {
    daemonRunning.value = await invoke<boolean>("daemon_is_running");
  } catch {
    daemonRunning.value = false;
  }
}

// ---------------------------------------------------------------------------
// Autostart management
// ---------------------------------------------------------------------------

async function checkAutostart() {
  try {
    autostartEnabled.value = await invoke<boolean>("plugin:autostart|is_enabled");
  } catch {
    autostartEnabled.value = false;
  }
}

async function toggleAutostart() {
  autostartLoading.value = true;
  try {
    if (autostartEnabled.value) {
      await invoke("plugin:autostart|disable");
      autostartEnabled.value = false;
    } else {
      await invoke("plugin:autostart|enable");
      autostartEnabled.value = true;
    }
  } catch (e) {
    error.value = `Failed to ${autostartEnabled.value ? 'disable' : 'enable'} autostart: ${e}`;
  } finally {
    autostartLoading.value = false;
  }
}

// ---------------------------------------------------------------------------
// Save settings
// ---------------------------------------------------------------------------

async function saveSettings() {
  if (!settings.value) return;
  try {
    saving.value = true;
    saveSuccess.value = false;
    await invoke("daemon_update_settings", { settings: settings.value });
    saveSuccess.value = true;
    setTimeout(() => {
      saveSuccess.value = false;
    }, 2000);
  } catch (e) {
    error.value = `Failed to save settings: ${e}`;
  } finally {
    saving.value = false;
  }
}

async function resetSettings() {
  try {
    const result = await invoke<Settings>("daemon_reset_settings");
    settings.value = result;
    saveSuccess.value = true;
    setTimeout(() => {
      saveSuccess.value = false;
    }, 2000);
  } catch (e) {
    error.value = `Failed to reset settings: ${e}`;
  }
}

// ---------------------------------------------------------------------------
// Daemon control
// ---------------------------------------------------------------------------

async function startRecording() {
  try {
    await invoke("daemon_start_recording");
    await refreshStatus();
  } catch (e) {
    error.value = `Failed to start recording: ${e}`;
  }
}

async function stopRecording() {
  try {
    await invoke("daemon_stop_recording");
    await refreshStatus();
  } catch (e) {
    error.value = `Failed to stop recording: ${e}`;
  }
}

async function shutdownDaemon() {
  try {
    await invoke("daemon_shutdown");
    daemonRunning.value = false;
    daemonStatus.value = null;
  } catch (e) {
    error.value = `Failed to shutdown daemon: ${e}`;
  }
}

// ---------------------------------------------------------------------------
// Encoder preset helpers
// ---------------------------------------------------------------------------

const encoderType = computed({
  get: () => settings.value?.video.encoder_preset.type ?? "nvenc",
  set: (type: string) => {
    if (!settings.value) return;
    let newPreset: EncoderPreset;
    switch (type) {
      case "nvenc":
        newPreset = { type: "nvenc", bitrate: 8000, cq_level: 20, two_pass: true };
        break;
      case "amf":
        newPreset = { type: "amf", bitrate: 8000, quality: "balanced" };
        break;
      case "x264":
        newPreset = { type: "x264", preset: "veryfast", bitrate: 6000, crf: null };
        break;
      default:
        return;
    }
    settings.value.video.encoder_preset = newPreset;
  },
});

const nvencPreset = computed(() => {
  const ep = settings.value?.video.encoder_preset;
  return ep?.type === "nvenc" ? (ep as NvencPreset) : null;
});

const amfPreset = computed(() => {
  const ep = settings.value?.video.encoder_preset;
  return ep?.type === "amf" ? (ep as AmfPreset) : null;
});

const x264PresetComputed = computed(() => {
  const ep = settings.value?.video.encoder_preset;
  return ep?.type === "x264" ? (ep as X264Preset) : null;
});

// ---------------------------------------------------------------------------
// Status display helpers
// ---------------------------------------------------------------------------

const statusLabel = computed(() => {
  if (!daemonStatus.value) return "Unknown";
  const s = daemonStatus.value.status;
  const map: Record<string, string> = {
    idle: "Idle",
    monitoring: "Monitoring",
    recording: "Recording",
    error: "Error",
    shutting_down: "Shutting Down",
  };
  return map[s] ?? s;
});

const statusColor = computed(() => {
  if (!daemonStatus.value) return "#888";
  const s = daemonStatus.value.status;
  const map: Record<string, string> = {
    idle: "#6b7280",
    monitoring: "#3b82f6",
    recording: "#ef4444",
    error: "#f59e0b",
    shutting_down: "#9ca3af",
  };
  return map[s] ?? "#888";
});

// ---------------------------------------------------------------------------
// Lifecycle
// ---------------------------------------------------------------------------

onMounted(async () => {
  await loadSettings();
  await checkAutostart();
  // Poll daemon status every 3 seconds
  statusPolling.value = setInterval(refreshStatus, 3000);
});

onUnmounted(() => {
  if (statusPolling.value) {
    clearInterval(statusPolling.value);
  }
});
</script>

<template>
  <div class="settings">
    <!-- Header -->
    <header class="settings-header">
      <button class="back-btn" @click="emit('back')">
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <path d="M19 12H5M12 19l-7-7 7-7" />
        </svg>
        Back
      </button>
      <h1 class="settings-title">Settings</h1>
      <div class="header-actions">
        <button
          v-if="settings"
          class="btn btn-secondary"
          @click="resetSettings"
        >
          Reset to Defaults
        </button>
        <button
          v-if="settings"
          class="btn btn-primary"
          :disabled="saving"
          @click="saveSettings"
        >
          {{ saving ? "Saving..." : saveSuccess ? "✓ Saved" : "Save Changes" }}
        </button>
      </div>
    </header>

    <!-- Error banner -->
    <div v-if="error" class="error-banner">
      <span>{{ error }}</span>
      <button class="error-close" @click="error = null">×</button>
    </div>

    <!-- Daemon not running -->
    <div v-if="!loading && !daemonRunning" class="daemon-offline">
      <div class="offline-icon">
        <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
          <circle cx="12" cy="12" r="10" />
          <line x1="4.93" y1="4.93" x2="19.07" y2="19.07" />
        </svg>
      </div>
      <h2>Record Daemon Not Running</h2>
      <p>Start the record-daemon to configure settings and control recording.</p>
      <button class="btn btn-primary" @click="loadSettings">
        Retry Connection
      </button>
    </div>

    <!-- Loading -->
    <div v-if="loading" class="loading">
      <div class="spinner"></div>
      <p>Loading settings...</p>
    </div>

    <!-- Settings content -->
    <div v-if="!loading && daemonRunning && settings" class="settings-content">
      <!-- Daemon status bar -->
      <div class="status-bar">
        <div class="status-indicator">
          <span class="status-dot" :style="{ backgroundColor: statusColor }"></span>
          <span class="status-text">{{ statusLabel }}</span>
        </div>
        <div class="status-details">
          <span v-if="daemonStatus?.client_connected" class="status-tag connected">
            Client Connected
          </span>
          <span v-else class="status-tag disconnected">
            Client Disconnected
          </span>
          <span v-if="daemonStatus?.is_recording" class="status-tag recording">
            ● Recording
          </span>
        </div>
        <div class="status-actions">
          <button
            v-if="!daemonStatus?.is_recording"
            class="btn btn-small btn-accent"
            @click="startRecording"
          >
            Start Recording
          </button>
          <button
            v-else
            class="btn btn-small btn-danger"
            @click="stopRecording"
          >
            Stop Recording
          </button>
          <button class="btn btn-small btn-ghost" @click="shutdownDaemon">
            Shutdown Daemon
          </button>
        </div>
      </div>

      <!-- Tab navigation -->
      <nav class="tab-nav">
        <button
          v-for="tab in (['video', 'output', 'audio', 'daemon'] as const)"
          :key="tab"
          :class="['tab-btn', { active: activeTab === tab }]"
          @click="activeTab = tab"
        >
          {{ tab.charAt(0).toUpperCase() + tab.slice(1) }}
        </button>
      </nav>

      <!-- Video tab -->
      <div v-if="activeTab === 'video'" class="tab-content">
        <section class="settings-section">
          <h3>Encoder</h3>
          <div class="form-group">
            <label class="form-label">Encoder Type</label>
            <select v-model="encoderType" class="form-select">
              <option value="nvenc">NVIDIA NVENC (Hardware)</option>
              <option value="amf">AMD AMF (Hardware)</option>
              <option value="x264">x264 (Software)</option>
            </select>
          </div>

          <!-- NVENC settings -->
          <template v-if="nvencPreset">
            <div class="form-group">
              <label class="form-label">Bitrate (kbps)</label>
              <input
                v-model.number="nvencPreset.bitrate"
                type="number"
                class="form-input"
                min="1000"
                max="50000"
                step="500"
              />
              <span class="form-hint">Recommended: 8000 for 1080p60</span>
            </div>
            <div class="form-group">
              <label class="form-label">CQ Level</label>
              <input
                v-model.number="nvencPreset.cq_level"
                type="number"
                class="form-input"
                min="0"
                max="51"
                step="1"
              />
              <span class="form-hint">Lower = better quality, larger file. Default: 20</span>
            </div>
            <div class="form-group">
              <label class="form-label">Two-Pass Encoding</label>
              <label class="toggle">
                <input v-model="nvencPreset.two_pass" type="checkbox" />
                <span class="toggle-slider"></span>
              </label>
              <span class="form-hint">Better quality at the cost of slightly more GPU usage</span>
            </div>
          </template>

          <!-- AMF settings -->
          <template v-if="amfPreset">
            <div class="form-group">
              <label class="form-label">Bitrate (kbps)</label>
              <input
                v-model.number="amfPreset.bitrate"
                type="number"
                class="form-input"
                min="1000"
                max="50000"
                step="500"
              />
            </div>
            <div class="form-group">
              <label class="form-label">Quality Preset</label>
              <select v-model="amfPreset.quality" class="form-select">
                <option
                  v-for="q in AMF_QUALITIES"
                  :key="q.value"
                  :value="q.value"
                >
                  {{ q.label }}
                </option>
              </select>
            </div>
          </template>

          <!-- x264 settings -->
          <template v-if="x264PresetComputed">
            <div class="form-group">
              <label class="form-label">Preset</label>
              <select v-model="x264PresetComputed.preset" class="form-select">
                <option v-for="p in X264_PRESETS" :key="p" :value="p">
                  {{ p.charAt(0).toUpperCase() + p.slice(1) }}
                </option>
              </select>
              <span class="form-hint">Slower = better compression, more CPU usage</span>
            </div>
            <div class="form-group">
              <label class="form-label">Bitrate (kbps)</label>
              <input
                v-model.number="x264PresetComputed.bitrate"
                type="number"
                class="form-input"
                min="1000"
                max="50000"
                step="500"
              />
            </div>
            <div class="form-group">
              <label class="form-label">CRF (optional)</label>
              <input
                v-model.number="x264PresetComputed.crf"
                type="number"
                class="form-input"
                min="0"
                max="51"
                step="1"
                placeholder="Leave empty for bitrate mode"
              />
              <span class="form-hint">Constant Rate Factor. Overrides bitrate if set. Lower = better quality.</span>
            </div>
          </template>
        </section>

        <section class="settings-section">
          <h3>Quality</h3>
          <div class="form-group">
            <label class="form-label">Quality Level</label>
            <div class="quality-grid">
              <button
                v-for="q in QUALITY_LEVELS"
                :key="q.value"
                :class="['quality-card', { selected: settings.video.quality === q.value }]"
                @click="settings.video.quality = q.value"
              >
                <span class="quality-name">{{ q.label }}</span>
                <span class="quality-desc">{{ q.description }}</span>
              </button>
            </div>
          </div>
          <div class="form-group">
            <label class="form-label">Frame Rate</label>
            <select v-model.number="settings.video.frame_rate" class="form-select">
              <option :value="24">24 fps</option>
              <option :value="30">30 fps</option>
              <option :value="60">60 fps</option>
              <option :value="120">120 fps</option>
              <option :value="144">144 fps</option>
              <option :value="240">240 fps</option>
            </select>
          </div>
          <div class="form-group">
            <label class="form-label">Hardware Acceleration</label>
            <label class="toggle">
              <input v-model="settings.video.hardware_acceleration" type="checkbox" />
              <span class="toggle-slider"></span>
            </label>
          </div>
        </section>
      </div>

      <!-- Output tab -->
      <div v-if="activeTab === 'output'" class="tab-content">
        <section class="settings-section">
          <h3>Recording Output</h3>
          <div class="form-group">
            <label class="form-label">Output Directory</label>
            <input
              v-model="settings.output.path"
              type="text"
              class="form-input"
              placeholder="Path to save recordings"
            />
            <span class="form-hint">Directory where recordings will be saved</span>
          </div>
          <div class="form-group">
            <label class="form-label">Naming Pattern</label>
            <input
              v-model="settings.output.naming_pattern"
              type="text"
              class="form-input"
              placeholder="{date}_{time}_{champion}"
            />
            <span class="form-hint">
              Available tokens: {date}, {time}, {game_id}, {champion}, {queue_type}
            </span>
          </div>
          <div class="form-group">
            <label class="form-label">Container Format</label>
            <select v-model="settings.output.container" class="form-select">
              <option v-for="fmt in CONTAINER_FORMATS" :key="fmt" :value="fmt">
                {{ fmt.toUpperCase() }}
              </option>
            </select>
            <span class="form-hint">
              MP4 is most compatible. MKV is more resilient to crashes.
            </span>
          </div>
        </section>

        <section class="settings-section">
          <h3>Recording Split</h3>
          <div class="form-group">
            <label class="form-label">Split by Size (MB)</label>
            <input
              v-model.number="settings.output.split_size_mb"
              type="number"
              class="form-input"
              min="0"
              step="100"
              placeholder="0 = no splitting"
            />
            <span class="form-hint">Split recording when file reaches this size. 0 = disabled.</span>
          </div>
          <div class="form-group">
            <label class="form-label">Split by Time (minutes)</label>
            <input
              v-model.number="settings.output.split_time_minutes"
              type="number"
              class="form-input"
              min="0"
              step="5"
              placeholder="0 = no splitting"
            />
            <span class="form-hint">Split recording after this duration. 0 = disabled.</span>
          </div>
        </section>
      </div>

      <!-- Audio tab -->
      <div v-if="activeTab === 'audio'" class="tab-content">
        <section class="settings-section">
          <h3>Audio Capture</h3>
          <div class="form-group">
            <label class="form-label">Enable Audio Recording</label>
            <label class="toggle">
              <input v-model="settings.audio.enabled" type="checkbox" />
              <span class="toggle-slider"></span>
            </label>
          </div>
          <template v-if="settings.audio.enabled">
            <div class="form-group">
              <label class="form-label">Audio Bitrate (kbps)</label>
              <select v-model.number="settings.audio.bitrate" class="form-select">
                <option :value="96">96 kbps</option>
                <option :value="128">128 kbps</option>
                <option :value="192">192 kbps</option>
                <option :value="256">256 kbps</option>
                <option :value="320">320 kbps</option>
              </select>
            </div>
            <div class="form-group">
              <label class="form-label">Sample Rate (Hz)</label>
              <select v-model.number="settings.audio.sample_rate" class="form-select">
                <option :value="44100">44100 Hz</option>
                <option :value="48000">48000 Hz</option>
              </select>
            </div>
            <div class="form-group">
              <label class="form-label">Channels</label>
              <select v-model.number="settings.audio.channels" class="form-select">
                <option :value="1">Mono</option>
                <option :value="2">Stereo</option>
              </select>
            </div>
          </template>
        </section>

        <section class="settings-section">
          <h3>Audio Sources</h3>
          <div class="form-group">
            <label class="form-label">Capture Game Audio</label>
            <label class="toggle">
              <input v-model="settings.audio.capture_game" type="checkbox" />
              <span class="toggle-slider"></span>
            </label>
            <span class="form-hint">Record the game's audio output</span>
          </div>
          <div class="form-group">
            <label class="form-label">Capture Microphone</label>
            <label class="toggle">
              <input v-model="settings.audio.capture_mic" type="checkbox" />
              <span class="toggle-slider"></span>
            </label>
            <span class="form-hint">Record microphone input alongside game audio</span>
          </div>
          <div v-if="settings.audio.capture_mic" class="form-group">
            <label class="form-label">Microphone Device</label>
            <input
              v-model="settings.audio.mic_device"
              type="text"
              class="form-input"
              placeholder="Default device"
            />
            <span class="form-hint">Leave empty for system default microphone</span>
          </div>
        </section>
      </div>

      <!-- Daemon tab -->
      <div v-if="activeTab === 'daemon'" class="tab-content">
        <section class="settings-section">
          <h3>Startup</h3>
          <div class="form-group">
            <label class="form-label">Launch at Startup</label>
            <label class="toggle">
              <input
                type="checkbox"
                :checked="autostartEnabled"
                :disabled="autostartLoading"
                @change="toggleAutostart"
              />
              <span class="toggle-slider"></span>
            </label>
            <span class="form-hint">Automatically launch League Recorder when you log in to Windows</span>
          </div>
        </section>

        <section class="settings-section">
          <h3>Daemon Behavior</h3>
          <div class="form-group">
            <label class="form-label">Auto Record</label>
            <label class="toggle">
              <input v-model="settings.daemon.auto_record" type="checkbox" />
              <span class="toggle-slider"></span>
            </label>
            <span class="form-hint">Automatically start recording when a match begins</span>
          </div>
          <div class="form-group">
            <label class="form-label">Monitor League Client</label>
            <label class="toggle">
              <input v-model="settings.daemon.monitor_client" type="checkbox" />
              <span class="toggle-slider"></span>
            </label>
            <span class="form-hint">Watch for League Client startup and connect automatically</span>
          </div>
          <div class="form-group">
            <label class="form-label">Poll Interval (ms)</label>
            <input
              v-model.number="settings.daemon.poll_interval_ms"
              type="number"
              class="form-input"
              min="100"
              max="10000"
              step="100"
            />
            <span class="form-hint">How often to check for League Client (milliseconds)</span>
          </div>
          <div class="form-group">
            <label class="form-label">Save Timeline</label>
            <label class="toggle">
              <input v-model="settings.daemon.save_timeline" type="checkbox" />
              <span class="toggle-slider"></span>
            </label>
            <span class="form-hint">Keep event timeline data after recording ends</span>
          </div>
        </section>

        <section class="settings-section">
          <h3>Advanced</h3>
          <div class="form-group">
            <label class="form-label">Log Level</label>
            <select v-model="settings.daemon.log_level" class="form-select">
              <option v-for="level in LOG_LEVELS" :key="level" :value="level">
                {{ level.charAt(0).toUpperCase() + level.slice(1) }}
              </option>
            </select>
            <span class="form-hint">Increase to "debug" or "trace" for troubleshooting</span>
          </div>
          <div class="form-group">
            <label class="form-label">IPC Socket Path</label>
            <input
              v-model="settings.daemon.socket_path"
              type="text"
              class="form-input"
              placeholder="Default: \\.\pipe\record-daemon (Windows)"
            />
            <span class="form-hint">Custom IPC socket path. Leave empty for default.</span>
          </div>
        </section>

        <section class="settings-section danger-zone">
          <h3>Danger Zone</h3>
          <div class="danger-actions">
            <button class="btn btn-danger" @click="shutdownDaemon">
              Shutdown Daemon
            </button>
            <button class="btn btn-secondary" @click="resetSettings">
              Reset All Settings
            </button>
          </div>
        </section>
      </div>
    </div>
  </div>
</template>

<style scoped>
.settings {
  min-height: 100vh;
  background: #0a0a13;
  color: #e2e8f0;
}

/* Header */
.settings-header {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px 24px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.08);
  background: rgba(255, 255, 255, 0.02);
}

.back-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  background: none;
  border: none;
  color: #94a3b8;
  cursor: pointer;
  font-size: 14px;
  padding: 6px 10px;
  border-radius: 6px;
  transition: all 0.15s;
}

.back-btn:hover {
  color: #e2e8f0;
  background: rgba(255, 255, 255, 0.06);
}

.settings-title {
  flex: 1;
  font-size: 20px;
  font-weight: 600;
  color: #f1f5f9;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 8px;
}

/* Buttons */
.btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  padding: 8px 16px;
  border-radius: 8px;
  font-size: 13px;
  font-weight: 500;
  border: none;
  cursor: pointer;
  transition: all 0.15s;
  white-space: nowrap;
}

.btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.btn-primary {
  background: #3b82f6;
  color: white;
}

.btn-primary:hover:not(:disabled) {
  background: #2563eb;
}

.btn-secondary {
  background: rgba(255, 255, 255, 0.08);
  color: #e2e8f0;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.btn-secondary:hover:not(:disabled) {
  background: rgba(255, 255, 255, 0.12);
}

.btn-accent {
  background: #10b981;
  color: white;
}

.btn-accent:hover:not(:disabled) {
  background: #059669;
}

.btn-danger {
  background: #ef4444;
  color: white;
}

.btn-danger:hover:not(:disabled) {
  background: #dc2626;
}

.btn-ghost {
  background: transparent;
  color: #94a3b8;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.btn-ghost:hover:not(:disabled) {
  color: #e2e8f0;
  background: rgba(255, 255, 255, 0.06);
}

.btn-small {
  padding: 5px 12px;
  font-size: 12px;
}

/* Error banner */
.error-banner {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 16px;
  background: rgba(239, 68, 68, 0.15);
  border-bottom: 1px solid rgba(239, 68, 68, 0.3);
  color: #fca5a5;
  font-size: 13px;
}

.error-close {
  background: none;
  border: none;
  color: #fca5a5;
  cursor: pointer;
  font-size: 18px;
  padding: 0 4px;
  line-height: 1;
}

/* Daemon offline */
.daemon-offline {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80px 24px;
  text-align: center;
}

.offline-icon {
  color: #64748b;
  margin-bottom: 16px;
}

.daemon-offline h2 {
  font-size: 20px;
  font-weight: 600;
  color: #f1f5f9;
  margin: 0 0 8px;
}

.daemon-offline p {
  color: #94a3b8;
  font-size: 14px;
  margin: 0 0 24px;
  max-width: 400px;
}

/* Loading */
.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80px 24px;
  color: #94a3b8;
}

.spinner {
  width: 32px;
  height: 32px;
  border: 3px solid rgba(255, 255, 255, 0.1);
  border-top-color: #3b82f6;
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
  margin-bottom: 12px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

/* Status bar */
.status-bar {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 12px 24px;
  background: rgba(255, 255, 255, 0.02);
  border-bottom: 1px solid rgba(255, 255, 255, 0.06);
}

.status-indicator {
  display: flex;
  align-items: center;
  gap: 8px;
}

.status-dot {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  flex-shrink: 0;
}

.status-text {
  font-size: 14px;
  font-weight: 500;
}

.status-details {
  display: flex;
  gap: 8px;
  flex: 1;
}

.status-tag {
  font-size: 11px;
  padding: 2px 8px;
  border-radius: 4px;
  font-weight: 500;
}

.status-tag.connected {
  background: rgba(16, 185, 129, 0.15);
  color: #6ee7b7;
}

.status-tag.disconnected {
  background: rgba(107, 114, 128, 0.15);
  color: #9ca3af;
}

.status-tag.recording {
  background: rgba(239, 68, 68, 0.15);
  color: #fca5a5;
  animation: pulse 1.5s ease-in-out infinite;
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.6; }
}

.status-actions {
  display: flex;
  gap: 8px;
}

/* Tab navigation */
.tab-nav {
  display: flex;
  gap: 0;
  padding: 0 24px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.08);
  background: rgba(255, 255, 255, 0.01);
}

.tab-btn {
  padding: 12px 20px;
  background: none;
  border: none;
  border-bottom: 2px solid transparent;
  color: #94a3b8;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.15s;
}

.tab-btn:hover {
  color: #e2e8f0;
}

.tab-btn.active {
  color: #3b82f6;
  border-bottom-color: #3b82f6;
}

/* Tab content */
.tab-content {
  padding: 24px;
  max-width: 720px;
}

/* Settings section */
.settings-section {
  margin-bottom: 32px;
}

.settings-section h3 {
  font-size: 15px;
  font-weight: 600;
  color: #f1f5f9;
  margin: 0 0 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.06);
}

/* Form elements */
.form-group {
  display: flex;
  flex-direction: column;
  gap: 6px;
  margin-bottom: 16px;
}

.form-label {
  font-size: 13px;
  font-weight: 500;
  color: #cbd5e1;
}

.form-input {
  padding: 8px 12px;
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 6px;
  color: #e2e8f0;
  font-size: 14px;
  outline: none;
  transition: border-color 0.15s;
}

.form-input:focus {
  border-color: #3b82f6;
}

.form-input::placeholder {
  color: #64748b;
}

.form-select {
  padding: 8px 12px;
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 6px;
  color: #e2e8f0;
  font-size: 14px;
  outline: none;
  cursor: pointer;
  transition: border-color 0.15s;
  appearance: none;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%2394a3b8' stroke-width='2'%3E%3Cpath d='M6 9l6 6 6-6'/%3E%3C/svg%3E");
  background-repeat: no-repeat;
  background-position: right 10px center;
  padding-right: 30px;
}

.form-select:focus {
  border-color: #3b82f6;
}

.form-select option {
  background: #1e1e2e;
  color: #e2e8f0;
}

.form-hint {
  font-size: 12px;
  color: #64748b;
}

/* Toggle switch */
.toggle {
  position: relative;
  display: inline-block;
  width: 44px;
  height: 24px;
  cursor: pointer;
}

.toggle input {
  opacity: 0;
  width: 0;
  height: 0;
}

.toggle-slider {
  position: absolute;
  inset: 0;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 12px;
  transition: all 0.2s;
}

.toggle-slider::before {
  content: "";
  position: absolute;
  width: 18px;
  height: 18px;
  left: 3px;
  bottom: 3px;
  background: #94a3b8;
  border-radius: 50%;
  transition: all 0.2s;
}

.toggle input:checked + .toggle-slider {
  background: #3b82f6;
}

.toggle input:checked + .toggle-slider::before {
  transform: translateX(20px);
  background: white;
}

/* Quality grid */
.quality-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 8px;
}

.quality-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
  padding: 12px 8px;
  background: rgba(255, 255, 255, 0.04);
  border: 1px solid rgba(255, 255, 255, 0.08);
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.15s;
}

.quality-card:hover {
  background: rgba(255, 255, 255, 0.08);
  border-color: rgba(255, 255, 255, 0.15);
}

.quality-card.selected {
  background: rgba(59, 130, 246, 0.15);
  border-color: #3b82f6;
}

.quality-name {
  font-size: 14px;
  font-weight: 500;
  color: #e2e8f0;
}

.quality-desc {
  font-size: 11px;
  color: #94a3b8;
}

/* Danger zone */
.danger-zone {
  border: 1px solid rgba(239, 68, 68, 0.2);
  border-radius: 8px;
  padding: 16px;
  background: rgba(239, 68, 68, 0.03);
}

.danger-zone h3 {
  color: #fca5a5;
  border-bottom-color: rgba(239, 68, 68, 0.2);
}

.danger-actions {
  display: flex;
  gap: 8px;
}

/* Responsive */
@media (max-width: 640px) {
  .settings-header {
    flex-wrap: wrap;
  }

  .header-actions {
    width: 100%;
    justify-content: flex-end;
  }

  .quality-grid {
    grid-template-columns: repeat(2, 1fr);
  }

  .status-bar {
    flex-wrap: wrap;
  }

  .status-actions {
    width: 100%;
    justify-content: flex-end;
  }
}
</style>
