<!-- #region AutomationPage [C:3] [TYPE Page] [SEMANTICS sveltekit, automation, policy, validation, config] -->
<!-- @ingroup Routes -->
<!-- @BRIEF Page component: routes/settings/automation/+page.svelte -->
<!-- @LAYER Page -->
<!-- @RELATION USES -> [EXT:frontend:App] -->
<!-- @PURPOSE: Settings page for managing validation policies. -->
<!-- @UX_STATE: Idle -> Displays the list of automation policies. -->
<!-- @UX_STATE: Loading -> Shows a loading spinner while fetching policies. -->
<!-- @UX_REACTIVITY: State: $state, Derived: $derived. -->
<!-- @UX_STATE: Form -> Policy creation/edit form visible. -->
<!-- @UX_FEEDBACK: Toast on save/delete success/error. -->
<!-- @UX_RECOVERY: Retry load via refresh. -->
<script lang="ts">
  import { onMount } from 'svelte';
  import { Button, PageHeader, Card, EmptyState, ConfirmDialog } from '$lib/ui';
  import PolicyForm from '$lib/components/health/PolicyForm.svelte';
  import { 
    getValidationPolicies, 
    createValidationPolicy, 
    updateValidationPolicy, 
    deleteValidationPolicy,
    getEnvironments,
    getTranslationSchedules
  } from '$lib/api';
  import { addToast } from '$lib/toasts.svelte.js';
  import { log } from '$lib/cot-logger';
  import { t } from '$lib/i18n/index.svelte.js';

  let policies = $state([]);
  let environments = $state([]);
  let translationSchedules = $state([]);
  let isLoading = $state(true);
  let showForm = $state(false);
  let selectedPolicy = $state(null);
  let showDeletePolicy = $state(false);
  let pendingDeletePolicyId = $state(null);

  onMount(async () => {
    await loadData();
  });

  async function loadData() {
    isLoading = true;
    try {
      const [policiesData, envsData, schedulesData] = await Promise.all([
        getValidationPolicies(),
        getEnvironments(),
        getTranslationSchedules()
      ]);
      policies = policiesData;
      environments = envsData;
      translationSchedules = Array.isArray(schedulesData) ? schedulesData : [];
    } catch (error) {
      log("AutomationPage", "EXPLORE", "Failed to load automation data", {}, String(error));
      addToast(t.settings?.policy_load_failed || 'Failed to load automation data', 'error');
    } finally {
      isLoading = false;
    }
  }

  function handleAdd() {
    selectedPolicy = null;
    showForm = true;
  }

  function handleEdit(policy) {
    if (!policy) return;
    selectedPolicy = policy;
    showForm = true;
  }

  async function handleSave(formData) {
    try {
      if (selectedPolicy) {
        await updateValidationPolicy(selectedPolicy.id, formData);
        addToast(t.settings?.policy_updated || 'Policy updated successfully', 'success');
      } else {
        await createValidationPolicy(formData);
        addToast(t.settings?.policy_created || 'Policy created successfully', 'success');
      }
      showForm = false;
      await loadData();
    } catch (error) {
      log("AutomationPage", "EXPLORE", "Failed to save policy", {}, String(error));
      addToast(t.settings?.policy_save_failed || 'Failed to save policy', 'error');
    }
  }

  async function handleDelete(id) {
    pendingDeletePolicyId = id;
    showDeletePolicy = true;
  }

  async function confirmDeletePolicy() {
    const id = pendingDeletePolicyId;
    pendingDeletePolicyId = null;
    try {
      await deleteValidationPolicy(id);
      addToast(t.settings?.policy_deleted || 'Policy deleted successfully', 'success');
      await loadData();
    } catch (error) {
      log("AutomationPage", "EXPLORE", "Failed to delete policy", {}, String(error));
      addToast(t.settings?.policy_delete_failed || 'Failed to delete policy', 'error');
    }
  }

  function getEnvName(id) {
    const envMatch = environments.find((e) => e?.id === id);
    return envMatch?.name || id;
  }

  const dayLabels = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
</script>

<div class="container mx-auto">
  {#if showForm}
    <!-- Form Mode -->
    <div class="mb-6">
      <div class="flex items-center mb-4">
        <Button variant="ghost" onclick={() => showForm = false}>
          <svg class="mr-1 h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
          </svg>
          {$t.settings?.back_to_list || 'Back to list'}
        </Button>
        <span class="mx-2 text-text-subtle">|</span>
        <h2 class="text-lg font-medium text-text">
          {selectedPolicy ? ($t.settings?.edit_policy || 'Edit Policy') : ($t.settings?.new_policy || 'New Policy')}
        </h2>
      </div>
      <PolicyForm 
        policy={selectedPolicy} 
        {environments}
        onSave={handleSave} 
        onCancel={() => showForm = false} 
      />
    </div>
  {:else if isLoading}
    <!-- Loading State -->
    <div class="flex justify-center py-12">
      <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
    </div>
  {:else}
    <!-- Header -->
    <PageHeader title={$t.settings?.automation_policies || 'Automation Policies'}>
      {#snippet subtitle()}
        <p class="text-sm text-text-muted dark:text-text-subtle">{$t.settings?.automation_policies_subtitle || 'Manage scheduled validation rules and execution windows.'}</p>
      {/snippet}
      {#snippet actions()}
        <Button onclick={handleAdd}>
          <svg class="-ml-1 mr-2 h-5 w-5" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
            <path fill-rule="evenodd" d="M10 3a1 1 0 011 1v5h5a1 1 0 110 2h-5v5a1 1 0 11-2 0v-5H4a1 1 0 110-2h5V4a1 1 0 011-1z" clip-rule="evenodd" />
          </svg>
          {$t.settings?.create_policy || 'Create Policy'}
        </Button>
      {/snippet}
    </PageHeader>

    <!-- Policy List -->
    <Card padding="none" class="mb-8">
      <ul class="divide-y divide-border">
        {#each policies as policy}
          <li>
            <div class="px-4 py-4 sm:px-6 hover:bg-surface-muted dark:hover:bg-terminal-bg/50 transition-colors">
              <div class="flex items-center justify-between">
                <div class="flex items-center min-w-0">
                  <div class="flex-shrink-0">
                    <div class="h-10 w-10 rounded-full bg-primary-light dark:bg-primary flex items-center justify-center text-primary">
                      <svg class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                      </svg>
                    </div>
                  </div>
                  <div class="ml-4 min-w-0">
                    <h3 class="text-sm font-medium text-primary truncate">{policy.name}</h3>
                    <div class="mt-1 flex items-center text-xs text-text-muted dark:text-text-subtle">
                      <span class="font-medium truncate">{getEnvName(policy.environment_id)}</span>
                      <span class="mx-2 shrink-0">•</span>
                      <span class="whitespace-nowrap">{$t.settings?.dashboards_count?.replace('{count}', policy.dashboard_ids.length) || `${policy.dashboard_ids.length} Dashboards`}</span>
                    </div>
                  </div>
                </div>
                <div class="flex items-center space-x-4 shrink-0 ml-4">
                  <div class="text-right hidden sm:block">
                    <div class="text-xs font-medium text-text dark:text-terminal-bright whitespace-nowrap">
                      {policy.window_start} – {policy.window_end}
                    </div>
                    <div class="text-xs text-text-muted dark:text-text-subtle whitespace-nowrap">
                      {policy.schedule_days.map(d => dayLabels[d]).join(', ')}
                    </div>
                  </div>
                  <div class="flex items-center space-x-1">
                    <Button variant="ghost" onclick={() => handleEdit(policy)} aria-label={$t.settings?.edit_policy || 'Edit policy'}>
                      <svg class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                      </svg>
                    </Button>
                    <Button variant="ghost" onclick={() => handleDelete(policy.id)} aria-label="Delete" class="hover:text-destructive">
                      <svg class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                      </svg>
                    </Button>
                  </div>
                </div>
              </div>
            </div>
          </li>
        {:else}
          <li>
            <EmptyState
              title={$t.settings?.no_policies || 'No policies'}
              description={$t.settings?.no_policies_desc || 'Get started by creating a new automation policy.'}
              actionLabel={$t.settings?.create_policy || 'Create Policy'}
              onAction={handleAdd}
            />
          </li>
        {/each}
      </ul>
    </Card>

    <!-- Translation Schedules -->
    {#if translationSchedules.length > 0}
      <h2 class="text-xl font-semibold text-text dark:text-terminal-bright mb-4">{$t.settings?.translation_schedules || 'Translation Schedules'}</h2>
      <Card padding="none">
        <ul class="divide-y divide-border">
          {#each translationSchedules as ts}
            <li>
              <div class="px-4 py-4 sm:px-6">
                <div class="flex items-center justify-between">
                  <div class="flex items-center min-w-0">
                    <div class="flex-shrink-0">
                      <div class="h-10 w-10 rounded-full bg-warning-light dark:bg-warning flex items-center justify-center text-warning">
                        <svg class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                        </svg>
                      </div>
                    </div>
                    <div class="ml-4 min-w-0">
                      <h3 class="text-sm font-medium text-text dark:text-terminal-bright truncate">{ts.job_name}</h3>
                      <div class="mt-1 flex items-center text-xs text-text-muted dark:text-text-subtle">
                        <span class="font-mono">{ts.cron_expression}</span>
                        <span class="mx-2 shrink-0">•</span>
                        <span>{ts.timezone}</span>
                      </div>
                    </div>
                  </div>
                  <div class="flex items-center space-x-3 shrink-0 ml-4">
                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium {ts.is_active ? 'bg-success-light text-success dark:bg-success dark:text-success' : 'bg-surface-muted text-text-muted dark:bg-terminal-bg dark:text-text-subtle'}">
                      {ts.is_active ? ($t.settings?.active || 'Active') : ($t.settings?.inactive || 'Inactive')}
                    </span>
                    {#if ts.last_run_at}
                      <span class="text-xs text-text-muted dark:text-text-subtle whitespace-nowrap">
                        {($t.settings?.last_run || 'Last: {date}').replace('{date}', new Date(ts.last_run_at).toLocaleString())}
                      </span>
                    {/if}
                  </div>
                </div>
              </div>
            </li>
          {/each}
        </ul>
      </Card>
    {/if}
  {/if}
</div>

<ConfirmDialog
  bind:show={showDeletePolicy}
  title={$t.settings?.delete_confirm_title || 'Delete policy?'}
  message={$t.settings?.delete_confirm || 'Are you sure you want to delete this policy?'}
  variant="destructive"
  confirmLabel={$t.common?.delete || 'Delete'}
  cancelLabel={$t.common?.cancel || 'Cancel'}
  onConfirm={confirmDeletePolicy}
  onCancel={() => { pendingDeletePolicyId = null; }}
/>

<!-- #endregion AutomationPage -->
