<!-- #region MaintenanceSettingsPanel [C:3] [TYPE Component] [SEMANTICS maintenance, settings, form, configuration] -->
<!-- @BRIEF Collapsible settings form for maintenance mode configuration. Uses existing UI primitives. -->
<!-- @LAYER Component -->
<!-- @RELATION DEPENDS_ON -> [MaintenanceStore] -->
<!-- @RELATION DEPENDS_ON -> [Select] -->
<!-- @RELATION DEPENDS_ON -> [Input] -->
<!-- @RELATION DEPENDS_ON -> [SearchableMultiSelect] -->
<!-- @RELATION DEPENDS_ON -> [Button] -->
<!-- @UX_STATE Idle -> Form fields populated with current settings. -->
<!-- @UX_STATE Saving -> Save button shows spinner, fields disabled. -->
<!-- @UX_STATE Saved -> Toast "Settings saved" appears. -->
<!-- @UX_STATE Error -> Error toast with message. -->
<!-- @UX_FEEDBACK Toast on save success/error. -->
<!-- @UX_REACTIVITY Props -> $props(), LocalState -> $state(isSaving, scope, envId, ...) -->
<script lang="ts">
  /**
   * Maintenance settings panel. Collapsible via <details><summary>.
   * Uses Select, Input, SearchableMultiSelect, Button from ui library.
   */
  import { onMount } from "svelte";
  import { maintenanceStore } from "$lib/stores/maintenance.svelte.js";
  import Select from "$lib/ui/Select.svelte";
  import Input from "$lib/ui/Input.svelte";
  import Button from "$lib/ui/Button.svelte";
  import SearchableMultiSelect from "$lib/components/ui/SearchableMultiSelect.svelte";
  import { api } from "$lib/api.js";
  import { t } from "$lib/i18n/index.svelte.js";
  import HelpTooltip from "$lib/ui/HelpTooltip.svelte";

  let isSaving = $state(false);
  let environments = $state([]);
  let dashboards = $state([]);

  // Form fields
  let targetEnvId = $state("");
  let displayTimezone = $state("UTC");
  let scope = $state("published_only");
  let excludedIds = $state([]);
  let forcedIds = $state([]);
  let bannerTemplate = $state("");

  // Environment select options
  let envOptions = $derived(
    environments.map((e) => ({ value: e.id || e.environment_id || e, label: e.name || e.id || e }))
  );

  // Dashboard options for SearchableMultiSelect (lazy-loaded)
  let dashboardOptions = $derived(
    dashboards.map((d) => ({ id: String(d.id), name: d.title || String(d.id) }))
  );

  // Banner template preview (using test values)
  let bannerPreview = $derived.by(() => {
    if (!bannerTemplate) return "";
    return bannerTemplate
      .replace(/\{start_time\}/g, "2026-05-21 22:00 UTC")
      .replace(/\{end_time\}/g, "2026-05-22 02:00 UTC")
      .replace(/\{message\}/g, "Scheduled data mart refresh");
  });

  /**
   * Load settings from store and populate form.
   */
  function populateForm() {
    const s = maintenanceStore.settings;
    if (!s) return;
    targetEnvId = s.target_environment_id || "";
    displayTimezone = s.display_timezone || "UTC";
    scope = s.dashboard_scope || "published_only";
    excludedIds = (s.excluded_dashboard_ids || []).map(String);
    forcedIds = (s.forced_dashboard_ids || []).map(String);
    bannerTemplate = s.banner_template || "";
  }

  /**
   * Load dashboards for multi-select options.
   */
  async function loadDashboards() {
    if (!targetEnvId && environments.length > 0) {
      targetEnvId = environments[0].id || environments[0].environment_id || environments[0];
    }
    if (!targetEnvId) return;
    try {
      const data = await api.getDashboards(targetEnvId, { page_size: 100, override_show_all: true });
      dashboards = data?.dashboards || [];
    } catch (e) {
      console.error("[EXT:frontend:MaintenanceSettingsPanel] Failed to load dashboards:", e?.message);
    }
  }

  /**
   * Handle save button click.
   */
  async function handleSave() {
    isSaving = true;
    try {
      await maintenanceStore.updateSettings({
        target_environment_id: targetEnvId || undefined,
        display_timezone: displayTimezone || undefined,
        dashboard_scope: scope || undefined,
        excluded_dashboard_ids: excludedIds.map(Number),
        forced_dashboard_ids: forcedIds.map(Number),
        banner_template: bannerTemplate || undefined,
      });
    } catch {
      // Error toast handled by store
    } finally {
      isSaving = false;
    }
  }

  // Load environments on mount. populateForm and loadDashboards are triggered
  // by $effect blocks below when their dependencies become available.
  onMount(async () => {
    try {
      environments = await api.getEnvironments();
    } catch {
      environments = [];
    }
    populateForm();
  });

  // Re-populate form when settings change from outside
  $effect(() => {
    if (maintenanceStore.settings) {
      populateForm();
    }
  });

  // Reload dashboards when env changes or environments first load.
  // Both conditions ensure loadDashboards runs exactly once on mount
  // (not twice — once from onMount and once from $effect reactivity).
  $effect(() => {
    if (targetEnvId && environments.length > 0) {
      void loadDashboards();
    }
  });
</script>

<details class="rounded-lg border border-gray-200 bg-white">
  <summary class="cursor-pointer px-4 py-3 text-sm font-semibold text-gray-900 hover:bg-gray-50 rounded-lg">
    {$t.maintenance?.settings || "Settings"}
  </summary>

  <div class="px-4 pb-4 space-y-4">
    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
      <!-- Environment -->
      <div>
        <span class="flex items-center gap-1.5 mb-1.5">
          <span class="text-sm font-medium text-gray-700">
            {$t.maintenance?.environment || "Environment"}
          </span>
          <HelpTooltip text={$t.maintenance?.help_environment || ""} />
        </span>
        <Select
          bind:value={targetEnvId}
          options={envOptions}
        />
      </div>

      <!-- Timezone -->
      <div>
        <span class="flex items-center gap-1.5 mb-1.5">
          <span class="text-sm font-medium text-gray-700">
            {$t.maintenance?.timezone || "Timezone"}
          </span>
          <HelpTooltip text={$t.maintenance?.help_timezone || ""} />
        </span>
        <Input
          bind:value={displayTimezone}
          placeholder={$t.maintenance?.timezone_placeholder || "e.g. Europe/Moscow"}
        />
      </div>
    </div>

    <!-- Scope Radio Group -->
    <fieldset>
      <legend class="flex items-center gap-1.5 text-sm font-medium text-gray-700 mb-2">
        {$t.maintenance?.scope || "Dashboard Scope"}
        <HelpTooltip text={$t.maintenance?.help_scope || ""} />
      </legend>
      <div class="flex flex-wrap gap-4">
        <label class="flex items-center gap-2 text-sm text-gray-700">
          <input type="radio" name="scope" value="published_only" bind:group={scope} class="text-blue-600" />
          {$t.maintenance?.scope_published || "Published only"}
        </label>
        <label class="flex items-center gap-2 text-sm text-gray-700">
          <input type="radio" name="scope" value="draft_only" bind:group={scope} class="text-blue-600" />
          {$t.maintenance?.scope_draft || "Drafts only"}
        </label>
        <label class="flex items-center gap-2 text-sm text-gray-700">
          <input type="radio" name="scope" value="all" bind:group={scope} class="text-blue-600" />
          {$t.maintenance?.scope_all || "All (published + drafts)"}
        </label>
      </div>
    </fieldset>

    <!-- Excluded / Forced Dashboards -->
    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
      <div>
        <span class="flex items-center gap-1.5 mb-1.5">
          <span class="text-sm font-medium text-gray-700">
            {$t.maintenance?.excluded_dashboards || "Excluded Dashboards"}
          </span>
          <HelpTooltip text={$t.maintenance?.help_excluded || ""} />
        </span>
        <SearchableMultiSelect
          bind:selected={excludedIds}
          options={dashboardOptions}
          placeholder="Search dashboards..."
        />
      </div>

      <div>
        <span class="flex items-center gap-1.5 mb-1.5">
          <span class="text-sm font-medium text-gray-700">
            {$t.maintenance?.forced_dashboards || "Forced Dashboards"}
          </span>
          <HelpTooltip text={$t.maintenance?.help_forced || ""} />
        </span>
        <SearchableMultiSelect
          bind:selected={forcedIds}
          options={dashboardOptions}
          placeholder="Search dashboards..."
        />
      </div>
    </div>

    <!-- Banner Template -->
    <div>
      <span class="flex items-center gap-1.5 mb-1.5">
        <label class="text-sm font-medium text-gray-700">
          {$t.maintenance?.banner_template || "Banner Template"}
        </label>
        <HelpTooltip text={$t.maintenance?.help_banner_template || ""} />
      </span>

      <!-- Template Presets -->
      <div class="mb-2">
        <span class="text-xs text-gray-500 mb-1.5 block">
          {$t.maintenance?.banner_templates || "Banner Templates"}:
        </span>
        <div class="flex flex-wrap gap-1.5">
          <button
            type="button"
            onclick={() => bannerTemplate = `<div style="background:#FFF3E0;border:1px solid #FFB74D;border-radius:8px;padding:12px;margin-bottom:12px;font-family:sans-serif">
  <strong style="color:#E65100;font-size:16px">⚠️ Maintenance in progress</strong>

  <p style="margin:8px 0;color:#333">{message}</p>

  <table style="font-size:13px;color:#555">
    <tr><td style="padding-right:12px">Start:</td><td><strong>{start_time}</strong></td></tr>
    <tr><td style="padding-right:12px">End:</td><td><strong>{end_time}</strong></td></tr>
  </table>

  <em style="font-size:12px;color:#888">Data may be incomplete or temporarily unavailable.</em>
</div>`}
            class="px-2.5 py-1 text-xs rounded-md border transition-colors
              border-gray-200 bg-white text-gray-600 hover:bg-orange-50 hover:border-orange-300 hover:text-orange-700"
          >
            {$t.maintenance?.banner_default || "Default (orange)"}
          </button>
          <button
            type="button"
            onclick={() => bannerTemplate = `> ⚠️ {message}

> Start: {start_time} | End: {end_time}`}
            class="px-2.5 py-1 text-xs rounded-md border transition-colors
              border-gray-200 bg-white text-gray-600 hover:bg-gray-100 hover:border-gray-400"
          >
            {$t.maintenance?.banner_minimal || "Minimal"}
          </button>
          <button
            type="button"
            onclick={() => bannerTemplate = `<div style="background:#FFEBEE;color:#B71C1C;padding:12px 16px;border-radius:8px;border:1px solid #EF9A9A;font-family:sans-serif;font-size:14px">
  🚧 <strong>Maintenance: {start_time} – {end_time}</strong>

  {message}
</div>`}
            class="px-2.5 py-1 text-xs rounded-md border transition-colors
              border-gray-200 bg-white text-gray-600 hover:bg-red-50 hover:border-red-300 hover:text-red-700"
          >
            {$t.maintenance?.banner_dark || "Dark theme"}
          </button>
          <button
            type="button"
            onclick={() => bannerTemplate = `⚠️ Maintenance: {start_time} — {end_time}`}
            class="px-2.5 py-1 text-xs rounded-md border transition-colors
              border-gray-200 bg-white text-gray-600 hover:bg-blue-50 hover:border-blue-300 hover:text-blue-700"
          >
            {$t.maintenance?.banner_time_only || "Time only"}
          </button>
        </div>
      </div>

      <textarea
        bind:value={bannerTemplate}
        rows="4"
        class="w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500"
        placeholder={'<div>## ⚠️ Maintenance...{message}...</div>'}
      ></textarea>
    </div>

    <!-- Live Preview -->
    {#if bannerTemplate}
      <div>
        <span class="text-sm font-medium text-gray-700 mb-1 block">
          {$t.maintenance?.banner_preview || "Preview"}
        </span>
        <div class="rounded-md border border-gray-200 bg-white p-4 overflow-auto max-h-48 [&_svg]:inline-block">
          {@html bannerPreview}
        </div>
      </div>
    {/if}

    <!-- Save Button -->
    <div class="pt-2">
      <Button onclick={handleSave} isLoading={isSaving} disabled={isSaving}>
        {$t.maintenance?.save_settings || "Save Settings"}
      </Button>
    </div>
  </div>
</details>
<!-- #endregion MaintenanceSettingsPanel -->
