<script lang="ts">
  import { onMount } from 'svelte';
  import { Smartphone } from 'lucide-svelte';
  import { api } from '$lib/api/client';

  // Polls /api/client/version once on mount. Renders nothing on 404
  // (no bundled APK — graceful degradation in dev / pre-CI images)
  // or 401 (defensive — caller must be logged in).
  //
  // The /api/client/* endpoints are auth-gated to prevent anonymous
  // bandwidth abuse on the APK stream, so this component only shows
  // for logged-in users. Mount in Settings, never in pre-auth surfaces.

  // Server returns snake_case (clientVersionResponse in
  // internal/api/client_assets.go). Map to a camelCase struct for
  // the rest of the component.
  type WireInfo = { version: string; apk_url: string; size_bytes: number };
  type Info = { version: string; apkUrl: string; sizeBytes: number };

  let info = $state<Info | null>(null);

  function formatSize(bytes: number): string {
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB`;
    return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
  }

  onMount(async () => {
    try {
      const body = await api.get<Partial<WireInfo>>('/api/client/version');
      if (!body.version || !body.apk_url) return;
      info = {
        version: body.version,
        apkUrl: body.apk_url,
        sizeBytes: body.size_bytes ?? 0
      };
    } catch {
      // 404 (no APK), 401 (somehow unauthed), network error — silent.
    }
  });
</script>

{#if info}
  <section class="space-y-3 rounded border border-border bg-surface p-4">
    <h2 class="text-lg font-semibold">Mobile app</h2>
    <p class="text-sm text-text-secondary">
      Install the Android app paired to this server. Sign in with the same account.
    </p>
    <a
      href={info.apkUrl}
      download="minstrel.apk"
      class="mobile-app-download flex items-center gap-3 rounded-md border border-border bg-surface px-3 py-2 text-sm text-text-primary no-underline transition-colors hover:bg-surface-hover hover:text-accent focus-visible:ring-2 focus-visible:ring-accent"
    >
      <Smartphone size={18} strokeWidth={1.5} class="shrink-0 text-accent" />
      <span class="flex flex-col leading-tight">
        <span class="font-medium">Get the Android app</span>
        <span class="text-xs text-text-secondary">
          {info.version}{info.sizeBytes > 0 ? ` · ${formatSize(info.sizeBytes)}` : ''}
        </span>
      </span>
    </a>
  </section>
{/if}
