<!-- #region DeploymentModal [C:3] [TYPE Component] [SEMANTICS git, deploy, environment, modal, promote] -->
<!-- @BRIEF Modal for deploying a dashboard to a target environment with stage selection and PROD confirmation. -->
<!-- @LAYER UI -->
<!--
@UX_STATE: Loading -> "Loading environments..." text visible, select disabled.
@UX_STATE: NoCandidates -> Error message shown with close button.
@UX_STATE: Ready -> Environment select enabled, deploy button active.
@UX_STATE: Deploying -> Button shows spinner and "Deploying..." label.
@UX_STATE: ConfirmProd -> Warning banner visible for PROD targets.
@UX_FEEDBACK Success/error toast on deploy result.
@UX_RECOVERY Close modal on error, retry deploy.
@UX_REACTIVITY Props -> $props(), Model -> DeploymentModel
-->
<!-- @RELATION BINDS_TO -> [DeploymentModel] -->
<!-- @INVARIANT This component contains NO business logic — all state and actions are delegated to DeploymentModel. -->

<script lang="ts">
  import { DeploymentModel } from '$lib/models/DeploymentModel.svelte.ts';
  import { t } from '$lib/i18n/index.svelte.js';

  let { dashboardId, envId = null, show = $bindable(false), preferredTargetStage = '' } = $props();

  const model = new DeploymentModel({ dashboardId, envId, show, preferredTargetStage });

  // Sync prop changes to model
  $effect(() => {
    model.dashboardId = dashboardId;
    model.envId = envId;
    model.show = show;
    model.preferredTargetStage = preferredTargetStage;
  });

  // Load environments when modal opens
  $effect(() => {
    if (show) model.loadEnvironments();
  });

  // Sync show changes back to parent
  $effect(() => {
    show = model.show;
  });
</script>

{#if show}
  <div class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
    <div class="bg-white p-6 rounded-lg shadow-xl w-96">
      <h2 class="text-xl font-bold mb-4">{$t.git?.deploy}</h2>

      {#if model.loading}
        <p class="text-gray-500">{$t.migration?.loading_envs}</p>
      {:else if model.deploymentCandidates.length === 0}
        <p class="text-red-500 mb-4">
          {$t.git?.no_deploy_envs}
        </p>
        <div class="flex justify-end">
          <button
            onclick={() => (show = false)}
            class="px-4 py-2 bg-gray-200 text-gray-800 rounded hover:bg-gray-300"
          >
            {$t.common?.close}
          </button>
        </div>
      {:else}
        {#if model.normalizedPreferredStage}
          <p class="mb-3 rounded border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-800">
            GitFlow target stage: {model.normalizedPreferredStage}
          </p>
        {/if}
        <div class="mb-6">
          <label for="deployment-target-env" class="block text-sm font-medium text-gray-700 mb-2"
            >{$t.migration?.target_env}</label
          >
          <select
            id="deployment-target-env"
            bind:value={model.selectedEnv}
            class="w-full border rounded p-2 focus-visible:ring-2 focus-visible:ring-primary-ring outline-none bg-white"
          >
            {#each model.deploymentCandidates as env}
              <option value={env.id}
                >{env.name} [{model.normalizeEnvStage(env)}] ({model.resolveEnvUrl(env)})</option
              >
            {/each}
          </select>
        </div>
        {#if model.isProdTarget}
          <p class="mb-3 rounded border border-destructive-light bg-destructive-light px-3 py-2 text-xs text-red-800">
            Внимание: выбрано PROD окружение. Потребуется подтверждение перед deploy.
          </p>
        {/if}

        <div class="flex justify-end space-x-3">
          <button
            onclick={() => (show = false)}
            class="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded"
          >
            {$t.common?.cancel}
          </button>
          <button
            onclick={() => model.handleDeploy()}
            disabled={model.deploying || !model.selectedEnv}
            class={`px-4 py-2 text-white rounded disabled:opacity-50 flex items-center ${model.isProdTarget ? 'bg-destructive hover:bg-destructive-hover' : 'bg-green-600 hover:bg-green-700'}`}
          >
            {#if model.deploying}
              <svg
                class="animate-spin -ml-1 mr-2 h-4 w-4 text-white"
                xmlns="http://www.w3.org/2000/svg"
                fill="none"
                viewBox="0 0 24 24"
              >
                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
              </svg>
              {$t.git?.deploying}
            {:else}
              {$t.git?.deploy}
            {/if}
          </button>
        </div>
      {/if}
    </div>
  </div>
{/if}
<!-- #endregion DeploymentModal -->
