<!-- #region MigrationMappingsPage [C:3] [TYPE Page] [SEMANTICS sveltekit, migration, mapping, fuzzy, environment] -->
<!-- @BRIEF Page component: routes/migration/mappings/+page.svelte — uses MappingsModel for all state and actions. -->
<!-- @LAYER Page -->
<!--
@SEMANTICS: migration, mapping, environment, fuzzy-matching, persistence
@PURPOSE: Render and orchestrate mapping management UI for source/target environments with backend persistence.
@LAYER UI
@RELATION DEPENDS_ON ->[MappingsModel]
@RELATION DEPENDS_ON ->[MappingTable]
@RELATION DEPENDS_ON ->[EnvSelector]
@RELATION BINDS_TO ->[EXT:frontend:migration.mappings.route]
@INVARIANT: No business logic in the page component — all state and actions delegated to MappingsModel.
@INVARIANT: Changing source environment resets target databases, mappings, suggestions, and target env.
@INVARIANT: Changing target environment resets target databases, mappings, and suggestions.
@PRE: Translation store and API client are available; route is mounted in authenticated UI shell.
@POST: UI exposes deterministic Idle/Loading/Error/Success states via model atoms.
@SIDE_EFFECT: MappingsModel performs network I/O to environment/database/mapping endpoints.
@UX_STATE: Idle -> Await environment selection and user-triggered fetch.
@UX_STATE: Loading -> Show loading text/spinner while environments or databases are fetched.
@UX_STATE: Error -> Render red alert panel with backend error message.
@UX_STATE: Success -> Render green confirmation panel after mapping save.
@UX_FEEDBACK: Error panel for failed API calls; success panel for persisted mapping confirmation.
@UX_RECOVERY: Retry via "fetch databases" action; reselection of environments clears stale arrays.
@UX_REACTIVITY: MappingsModel atoms ($state) drive all template reactivity.
-->
<script lang="ts">
  // #region MappingsPageScript [C:3] [TYPE Block] [SEMANTICS page-script,model]
  // @BRIEF Page script — instantiates MappingsModel and delegates all state/actions to it.
  // @RELATION CALLS -> [MappingsModel]
  // @INVARIANT: No local state or business logic. All atoms and actions come from model.

  import { onMount } from 'svelte';
  import { MappingsModel } from '$lib/models/MappingsModel.svelte.ts';
  import EnvSelector from '../../../components/EnvSelector.svelte';
  import MappingTable from '../../../components/MappingTable.svelte';
  import { t } from '$lib/i18n/index.svelte.js';
  import { Button, PageHeader } from '$lib/ui';

  /** @type {MappingsModel} */
  const model = new MappingsModel();

  onMount(() => model.loadEnvironments());
  // #endregion MappingsPageScript
</script>

<!-- #region MappingsPageTemplate [C:2] [TYPE Block] [SEMANTICS migration, mapping, page-layout] -->
<!-- @BRIEF Mapping page template with environment selectors, database mapping table, and action buttons. -->
<!-- @RELATION READS -> [MappingsModel.environments, .sourceDatabases, .targetDatabases, .mappings, .suggestions, .loading, .fetchingDbs, .error, .success] -->
<!-- @RELATION CALLS -> [MappingsModel.selectSourceEnv, .selectTargetEnv, .fetchDatabases, .saveMapping] -->
<div class="max-w-6xl mx-auto p-6">
  <PageHeader title={$t.migration?.mapping_management} />

  {#if model.loading}
    <p>{$t.migration?.loading_envs}</p>
  {:else}
    <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
      <EnvSelector
        label={$t.migration?.source_env}
        selectedId={model.sourceEnvId}
        environments={model.environments}
        onchange={(e) => model.selectSourceEnv(e.id)}
      />
      <EnvSelector
        label={$t.migration?.target_env}
        selectedId={model.targetEnvId}
        environments={model.environments}
        onchange={(e) => model.selectTargetEnv(e.id)}
      />
    </div>

    <div class="mb-8">
      <Button
        onclick={() => model.fetchDatabases()}
        disabled={!model.sourceEnvId || !model.targetEnvId || model.sourceEnvId === model.targetEnvId || model.fetchingDbs}
        isLoading={model.fetchingDbs}
      >
        {$t.migration?.fetch_dbs}
      </Button>
    </div>

    {#if model.error}
      <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
        {model.error}
      </div>
    {/if}

    {#if model.success}
      <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-4">
        {model.success}
      </div>
    {/if}

    {#if model.sourceDatabases.length > 0}
      <MappingTable
        sourceDatabases={model.sourceDatabases}
        targetDatabases={model.targetDatabases}
        mappings={model.mappings}
        suggestions={model.suggestions}
        onupdate={(detail) => model.saveMapping(detail.sourceUuid, detail.targetUuid)}
      />
    {:else if !model.fetchingDbs && model.sourceEnvId && model.targetEnvId}
      <p class="text-gray-500 italic">{$t.migration?.mapping_hint}</p>
    {/if}
  {/if}
</div>
<!-- #endregion MappingsPageTemplate -->

<!-- #endregion MigrationMappingsPage -->
