<script lang="ts">
  import { onMount } from "svelte";
  import Header from "$lib/components/Header.svelte";
  import StatusBar from "$lib/components/StatusBar.svelte";
  import Controls from "$lib/components/Controls.svelte";
  import TranscriptionDisplay from "$lib/components/TranscriptionDisplay.svelte";
  import Settings from "$lib/components/Settings.svelte";
  import SidecarSetup from "$lib/components/SidecarSetup.svelte";
  import { backendStore } from "$lib/stores/backend";
  import { configStore } from "$lib/stores/config";

  type SidecarState = "checking" | "needs_setup" | "update_available" | "starting" | "connected";

  let showSettings = $state(false);
  let sidecarState = $state<SidecarState>("checking");
  let debugLog = $state("");
  let availableUpdate = $state("");
  let appVersion = $state("");

  let obsDisplayUrl = $derived(backendStore.obsUrl);
  let syncDisplayUrl = $derived(backendStore.syncUrl);
  let isConnected = $derived(backendStore.connectionState === "connected");
  let connectionState = $derived(backendStore.connectionState);

  function openSettings() {
    showSettings = true;
  }

  function closeSettings() {
    showSettings = false;
  }

  let tauriInvoke: ((cmd: string, args?: Record<string, unknown>) => Promise<unknown>) | null = null;

  function log(msg: string) {
    console.log(`[App] ${msg}`);
    debugLog = msg;
    // Also write to file via Tauri if available
    tauriInvoke?.("write_log", { message: msg });
  }

  async function checkAndLaunchSidecar() {
    try {
      log("Importing Tauri API...");
      const { invoke } = await import("@tauri-apps/api/core");
      tauriInvoke = invoke;

      log("Checking if sidecar is installed...");
      sidecarState = "checking";
      const installed = await invoke<boolean>("check_sidecar");
      log(`Sidecar installed: ${installed}`);

      if (!installed) {
        sidecarState = "needs_setup";
        return;
      }

      // Check for sidecar updates before launching
      try {
        log("Checking for sidecar updates...");
        const update = await invoke<string | null>("check_sidecar_update");
        if (update) {
          log(`Sidecar update available: ${update}`);
          availableUpdate = update;
          sidecarState = "update_available";
          return;
        }
      } catch (err) {
        log(`Update check failed (non-fatal): ${err}`);
      }

      await launchSidecar();
    } catch (err) {
      // Not running in Tauri (browser dev mode) - skip sidecar check
      // and connect directly to localhost:8081
      log(`Tauri not available (${err}), using dev mode`);
      sidecarState = "starting";
      backendStore.setPort(8081);
      backendStore.connect();
      configStore.fetchConfig();
    }
  }

  async function launchSidecar() {
    try {
      const { invoke } = await import("@tauri-apps/api/core");

      log("Starting sidecar...");
      sidecarState = "starting";
      await invoke("start_sidecar");

      log("Getting sidecar port...");
      const port = await invoke<number>("get_sidecar_port");
      log(`Sidecar ready on port ${port}`);
      backendStore.setPort(port);
      backendStore.connect();
      configStore.fetchConfig();
    } catch (err) {
      // If sidecar launch fails, still try connecting to default port
      log(`Sidecar launch failed: ${err}, trying default port`);
      sidecarState = "starting";
      backendStore.connect();
      configStore.fetchConfig();
    }
  }

  async function onSidecarReady() {
    await launchSidecar();
  }

  onMount(() => {
    // Get app version from Tauri
    import("@tauri-apps/api/app").then(({ getVersion }) =>
      getVersion().then((v) => { appVersion = v; })
    ).catch(() => {
      // Browser dev mode -- read from package.json or use fallback
      appVersion = "dev";
    });

    checkAndLaunchSidecar();

    return () => {
      backendStore.disconnect();
    };
  });
</script>

{#if sidecarState === "checking"}
  <div class="connecting-overlay" style="background:#1e1e1e;color:#e0e0e0;display:flex;align-items:center;justify-content:center;height:100%;width:100%;">
    <div class="connecting-content" style="text-align:center;">
      <div class="connecting-icon">
        <div class="spinner"></div>
      </div>
      <h2 style="font-size:20px;margin:16px 0 8px;">Local Transcription</h2>
      <p style="color:#a0a0a0;font-size:14px;">Checking setup...</p>
      {#if debugLog}
        <p style="color:#707070;font-size:11px;margin-top:12px;">{debugLog}</p>
      {/if}
    </div>
  </div>

{:else if sidecarState === "needs_setup"}
  <SidecarSetup onComplete={onSidecarReady} />

{:else if sidecarState === "update_available"}
  <div class="connecting-overlay" style="background:#1e1e1e;color:#e0e0e0;display:flex;align-items:center;justify-content:center;height:100%;width:100%;">
    <div class="connecting-content" style="text-align:center;max-width:400px;">
      <h2 style="font-size:20px;margin:0 0 12px;">Sidecar Update Available</h2>
      <p style="color:#a0a0a0;font-size:14px;margin:0 0 20px;">
        A new version of the transcription engine is available ({availableUpdate}).
      </p>
      <div style="display:flex;gap:10px;justify-content:center;">
        <button
          style="padding:8px 20px;border:1px solid #555;border-radius:6px;background:transparent;color:#e0e0e0;cursor:pointer;"
          onclick={() => launchSidecar()}
        >Skip</button>
        <button
          style="padding:8px 20px;border:none;border-radius:6px;background:#4CAF50;color:white;cursor:pointer;font-weight:500;"
          onclick={() => { sidecarState = "needs_setup"; }}
        >Update Now</button>
      </div>
    </div>
  </div>

{:else if !isConnected}
  <div class="connecting-overlay" style="background:#1e1e1e;color:#e0e0e0;display:flex;align-items:center;justify-content:center;height:100%;width:100%;">
    <div class="connecting-content" style="text-align:center;">
      <div class="connecting-icon">
        {#if connectionState === "error"}
          <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="#e74c3c" stroke-width="2">
            <circle cx="12" cy="12" r="10"/>
            <line x1="15" y1="9" x2="9" y2="15"/>
            <line x1="9" y1="9" x2="15" y2="15"/>
          </svg>
        {:else}
          <div class="spinner"></div>
        {/if}
      </div>
      <h2 style="font-size:20px;margin:16px 0 8px;">Local Transcription</h2>
      {#if connectionState === "error"}
        <p style="color:#a0a0a0;">Cannot connect to backend</p>
        <p class="hint">Make sure the Python backend is running:<br>
          <code>uv run python -m backend.main_headless</code></p>
      {:else}
        <p style="color:#a0a0a0;">Connecting to backend...</p>
      {/if}
      {#if debugLog}
        <p style="color:#707070;font-size:11px;margin-top:12px;">{debugLog}</p>
      {/if}
    </div>
  </div>

{:else}
  <div class="app-shell">
    <Header onSettingsClick={openSettings} />
    <StatusBar />

    <div class="display-links">
      <span class="link-label">OBS:</span>
      <a href={obsDisplayUrl} target="_blank" rel="noopener">{obsDisplayUrl}</a>
      {#if syncDisplayUrl}
        <span class="link-separator">|</span>
        <span class="link-label">Sync:</span>
        <a href={syncDisplayUrl} target="_blank" rel="noopener"
          >{syncDisplayUrl}</a
        >
      {/if}
    </div>

    <TranscriptionDisplay />
    <Controls />

    <div class="version-label">v{appVersion || backendStore.version}</div>
  </div>

  {#if showSettings}
    <Settings onClose={closeSettings} />
  {/if}
{/if}

<style>
  .connecting-overlay {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
    width: 100%;
    background-color: var(--bg-primary);
  }

  .connecting-content {
    text-align: center;
    color: var(--text-primary);
  }

  .connecting-content h2 {
    margin: 16px 0 8px;
    font-size: 20px;
    font-weight: 600;
  }

  .connecting-content p {
    margin: 4px 0;
    color: var(--text-secondary);
    font-size: 14px;
  }

  .connecting-content .hint {
    margin-top: 16px;
    font-size: 12px;
    color: var(--text-muted);
  }

  .connecting-content code {
    display: inline-block;
    margin-top: 4px;
    padding: 4px 8px;
    background: var(--bg-tertiary);
    border-radius: 4px;
    font-size: 12px;
    color: var(--text-primary);
  }

  .connecting-icon {
    display: flex;
    justify-content: center;
    margin-bottom: 8px;
  }

  .spinner {
    width: 40px;
    height: 40px;
    border: 3px solid var(--border-color);
    border-top-color: var(--accent-color, #4CAF50);
    border-radius: 50%;
    animation: spin 0.8s linear infinite;
  }

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

  .app-shell {
    display: flex;
    flex-direction: column;
    height: 100%;
    width: 100%;
    background-color: var(--bg-primary);
  }

  .display-links {
    display: flex;
    align-items: center;
    gap: 6px;
    padding: 6px 20px;
    font-size: 12px;
    background-color: var(--bg-primary);
    border-bottom: 1px solid var(--border-color);
    flex-shrink: 0;
  }

  .link-label {
    color: var(--text-secondary);
    font-weight: 500;
  }

  .link-separator {
    color: var(--text-muted);
    margin: 0 4px;
  }

  .version-label {
    position: fixed;
    bottom: 6px;
    right: 12px;
    font-size: 11px;
    color: var(--text-muted);
    pointer-events: none;
    z-index: 10;
  }
</style>
