<!-- #region Translate.InsertMethodSelector [C:2] [TYPE Component] [SEMANTICS translate,insert,ui,database] -->
<!-- @ingroup Translate -->
<!-- @BRIEF Radio group for choosing insert method: SQL Lab API (default) or Direct DB Connection.
<!--      Both SQL Lab database selector and Direct DB connection selector appear -->
<!--      directly under their respective radio with identical indented design. -->
<!-- @UX_STATE sqllab_selected -> SQL Lab database selector visible under SQL Lab radio -->
<!-- @UX_STATE direct_db_selected -> Direct DB connection dropdown visible under Direct DB radio -->
<!-- @UX_STATE no_connections, connection_selected, testing_connection, test_success, test_error -->
<!-- @UX_SYMMETRY Both selectors use ml-6 pl-4 border-l-2 border-border spacing -->
<!-- @UX_FEEDBACK dialect compatibility badge; connection status indicator; 'No connections' empty state with CTA link -->
<!-- @UX_RECOVERY no_connections -> 'Go to Settings - Connections' link; test_error -> error details -->
<script lang="ts">
  import { getT } from "$lib/i18n/index.svelte.js";
  import { api } from "$lib/api.js";
  import { ROUTES } from "$lib/routes";
  import { addToast } from "$lib/toasts.svelte.js";
  import HelpTooltip from "$lib/ui/HelpTooltip.svelte";

  const _t = $derived(getT());

  interface Connection {
    id: string;
    name: string;
    dialect: string;
    host: string;
    port: number;
  }

  let {
    insertMethod = $bindable("sqllab"),
    connectionId = $bindable(null),
    targetDatabaseId = $bindable(''),
    jobDialect = "",
    databases = [] as Record<string, unknown>[],
    databasesLoading = false,
    environmentId = '',
  } = $props();

  let connections = $state<Connection[]>([]);
  let isLoading = $state(false);
  let testResult = $state<string | null>(null);
  let isTesting = $state(false);

  $effect(() => {
    if (insertMethod === "direct_db") {
      loadConnections();
    }
  });

  async function loadConnections() {
    isLoading = true;
    try {
      connections = await api.fetchConnections<Connection[]>();
    } catch {
      connections = [];
    } finally {
      isLoading = false;
    }
  }

  const compatibleConnections = $derived(
    jobDialect && jobDialect !== 'unknown'
      ? connections.filter(c => c.dialect === jobDialect)
      : connections
  );

  async function handleTestConnection() {
    if (!connectionId) return;
    isTesting = true;
    testResult = null;
    try {
      const r = await api.testConnection(connectionId);
      if (r.success) {
        testResult = `✅ Connected — ${r.latency_ms}ms`;
        addToast(`${_t.settings?.connections_test_success?.replace('{latency}', r.latency_ms) || `✅ Connected — ${r.latency_ms}ms`}`, "success");
      } else {
        testResult = `❌ ${r.error}`;
        addToast(`${_t.settings?.connections_test_failed ?? '❌'} ${r.error}`, "error");
      }
    } catch (err: unknown) {
      testResult = `❌ Test failed`;
      addToast(_t.settings?.connections_test_failed ?? "Connection test failed", "error");
    } finally {
      isTesting = false;
    }
  }
</script>

<div class="space-y-3">
  <!-- Heading provided by parent TargetTabForm -->

  <!-- SQL Lab radio -->
  <label class="flex items-center gap-2 p-3 border border-border rounded-md cursor-pointer hover:bg-surface-muted/50">
    <input type="radio" name="insert_method" value="sqllab" bind:group={insertMethod} checked={insertMethod === "sqllab"} />
    <div>
      <span class="text-sm font-medium text-text">{_t.translate?.config?.insert_method_sqllab || 'Superset SQL Lab API'}</span>
      <p class="text-xs text-text-muted">{_t.translate?.config?.insert_method_sqllab_hint || 'Executes via Superset /api/v1/sqllab/execute/'}</p>
    </div>
  </label>

  <!-- SQL Lab database selector — under SQL Lab radio -->
  {#if insertMethod === 'sqllab'}
    <div class="ml-6 pl-4 border-l-2 border-border space-y-2">
      <label class="block text-sm font-medium text-text flex items-center gap-1">
        {_t.translate?.config?.target_database || 'Target Database (SQL Lab)'}
        <HelpTooltip text={_t.translate?.config?.help_target_database || ''} />
      </label>
      <select
        bind:value={targetDatabaseId}
        class="w-full border border-border-strong rounded-md px-2 py-1.5 text-sm text-text bg-surface-card"
        disabled={!environmentId || databasesLoading}
      >
        <option value="">{_t.translate?.config?.select_target_database || 'Select database...'}</option>
        {#each databases as db}
          <option value={String(db.id || db.uuid)}>
            {db.database_name || db.name} ({db.engine || db.backend || '?'})
          </option>
        {/each}
      </select>
      {#if databasesLoading}
        <p class="text-xs text-text-muted">{_t.translate?.config?.loading_databases || 'Loading databases...'}</p>
      {:else if !environmentId}
        <p class="text-xs text-text-muted">{_t.translate?.config?.select_environment || 'Select environment first'}</p>
      {:else}
        <p class="text-xs text-text-muted">{_t.translate?.config?.target_database_hint || ''}</p>
      {/if}
    </div>
  {/if}

  <!-- Direct DB radio -->
  <label class="flex items-center gap-2 p-3 border border-border rounded-md cursor-pointer hover:bg-surface-muted/50">
    <input type="radio" name="insert_method" value="direct_db" bind:group={insertMethod} checked={insertMethod === "direct_db"} />
    <div>
      <span class="text-sm font-medium text-text">{_t.translate?.config?.insert_method_direct_db || 'Direct Database Connection'}</span>
      <p class="text-xs text-text-muted">{_t.translate?.config?.insert_method_direct_db_hint || 'Executes INSERT directly against target database'}</p>
    </div>
  </label>

  <!-- Direct DB connection selector — under Direct DB radio -->
  {#if insertMethod === "direct_db"}
    <div class="ml-6 pl-4 border-l-2 border-border space-y-2">
      {#if isLoading}
        <div class="h-8 animate-pulse bg-surface-muted rounded"></div>
      {:else if connections.length === 0}
        <div class="text-sm text-text-muted">
          {_t.translate?.config?.insert_method_no_conns || 'No database connections configured.'}
          <a href={ROUTES.settings.connections()} class="text-primary hover:underline">{_t.translate?.config?.insert_method_go_settings || 'Go to Settings → Connections'}</a>
        </div>
      {:else}
        <label class="block text-sm font-medium text-text flex items-center gap-1">
          {_t.translate?.config?.insert_method_connection_label || 'Database Connection'}
          <HelpTooltip text={_t.translate?.config?.insert_method_connection_help || ''} />
        </label>
        <select
          class="w-full border border-border-strong rounded-md px-2 py-1.5 text-sm text-text bg-surface-card"
          bind:value={connectionId}
        >
          <option value={null}>{_t.translate?.config?.insert_method_select || '— Select connection —'}</option>
          {#each compatibleConnections as conn (conn.id)}
            <option value={conn.id}>
              {conn.name} ({conn.dialect} · {conn.host}:{conn.port})
            </option>
          {/each}
          {#if compatibleConnections.length === 0}
            <option disabled>{_t.translate?.config?.insert_method_no_compatible?.replace('{dialect}', jobDialect) || 'No compatible connections for dialect: {dialect}'}</option>
          {/if}
        </select>

        {#if connectionId}
          <button
            class="text-xs text-primary hover:underline disabled:opacity-50"
            onclick={handleTestConnection}
            disabled={isTesting}
          >
            {isTesting ? (_t.translate?.config?.insert_method_testing || 'Testing...') : (_t.translate?.config?.insert_method_test || 'Test Connection')}
          </button>
        {/if}

        {#if testResult}
          <p class="text-xs {testResult.startsWith('✅') ? 'text-success' : 'text-destructive'}">{testResult}</p>
        {/if}
      {/if}
    </div>
  {/if}
</div>
<!-- #endregion Translate.InsertMethodSelector -->