<!-- #region AutomationPage [C:3] [TYPE Page] [SEMANTICS sveltekit, automation, policy, validation, config] -->
<!-- @BRIEF Page component: routes/settings/automation/+page.svelte -->
<!-- @LAYER Page -->
<!--
@RELATION USES -> [EXT:frontend:App]
 
  @PURPOSE: Settings page for managing validation policies.
  @LAYER Page
  @UX_STATE: Idle -> Displays the list of automation policies.
  @UX_STATE: Loading -> Shows a loading spinner while fetching policies.
  @UX_REATIVITY: State: $state, Derived: $derived.
-->
<script lang="ts">
  import { onMount } from 'svelte';
  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';

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

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

  async function loadData() {
    isLoading = true;
    try {
      const [policiesData, envsData, schedulesData] = await Promise.all([
        getValidationPolicies(),
        getEnvironments(),
        getTranslationSchedules()
      ]);

      const policyArray = Array.isArray(policiesData) ? policiesData : [];
      const environmentArray = Array.isArray(envsData) ? envsData : [];

      const invalidPolicies = policyArray
        .map((policy, index) => ({ index, policy }))
        .filter(({ policy }) => !policy || typeof policy !== 'object');
      const policiesWithMissingName = policyArray
        .map((policy, index) => ({ index, policy }))
        .filter(({ policy }) => policy && (policy.name === null || policy.name === undefined));

      const invalidEnvironments = environmentArray
        .map((env, index) => ({ index, env }))
        .filter(({ env }) => !env || typeof env !== 'object');
      const environmentsWithMissingName = environmentArray
        .map((env, index) => ({ index, env }))
        .filter(({ env }) => env && (env.name === null || env.name === undefined));

      console.log('[AutomationSettingsPage][Debug] Loaded payload shapes', {
        policiesCount: policyArray.length,
        environmentsCount: environmentArray.length,
        invalidPoliciesCount: invalidPolicies.length,
        policiesWithMissingNameCount: policiesWithMissingName.length,
        invalidEnvironmentsCount: invalidEnvironments.length,
        environmentsWithMissingNameCount: environmentsWithMissingName.length
      });

      if (invalidPolicies.length > 0 || policiesWithMissingName.length > 0) {
        console.warn('[AutomationSettingsPage][Debug] Suspicious policy payload detected', {
          invalidPolicies,
          policiesWithMissingName
        });
      }

      if (invalidEnvironments.length > 0 || environmentsWithMissingName.length > 0) {
        console.warn('[AutomationSettingsPage][Debug] Suspicious environments payload detected', {
          invalidEnvironments,
          environmentsWithMissingName
        });
      }

      policies = policiesData;
      environments = envsData;
      translationSchedules = Array.isArray(schedulesData) ? schedulesData : [];
    } catch (error) {
      console.error('Failed to load automation data:', error);
    } finally {
      isLoading = false;
    }
  }

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

  function handleEdit(policy) {
    if (!policy) {
      console.error('[AutomationSettingsPage][Debug] handleEdit received invalid policy', { policy });
      return;
    }
    console.log('[AutomationSettingsPage][Debug] handleEdit policy snapshot', {
      id: policy.id,
      name: policy.name,
      environment_id: policy.environment_id,
      dashboard_ids_type: Array.isArray(policy.dashboard_ids) ? 'array' : typeof policy.dashboard_ids
    });
    selectedPolicy = policy;
    showForm = true;
  }

  async function handleSave(formData) {
    try {
      if (selectedPolicy) {
        await updateValidationPolicy(selectedPolicy.id, formData);
        addToast('Policy updated successfully', 'success');
      } else {
        await createValidationPolicy(formData);
        addToast('Policy created successfully', 'success');
      }
      showForm = false;
      await loadData();
    } catch (error) {
      console.error('Failed to save policy:', error);
    }
  }

  async function handleDelete(id) {
    if (!confirm('Are you sure you want to delete this policy?')) return;
    try {
      await deleteValidationPolicy(id);
      addToast('Policy deleted successfully', 'success');
      await loadData();
    } catch (error) {
      console.error('Failed to delete policy:', error);
    }
  }

  function getEnvName(id) {
    const envMatch = environments.find((e) => e?.id === id);
    if (!envMatch) {
      console.warn('[AutomationSettingsPage][Debug] Environment not found for policy environment_id', {
        requestedEnvironmentId: id,
        environmentsCount: Array.isArray(environments) ? environments.length : -1
      });
    } else if (envMatch.name === null || envMatch.name === undefined) {
      console.warn('[AutomationSettingsPage][Debug] Environment has null/undefined name', {
        requestedEnvironmentId: id,
        environment: envMatch
      });
    }
    return envMatch?.name || id;
  }

  const dayLabels = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];

  $effect(() => {
    if (isLoading) return;

    const policiesWithNullName = (Array.isArray(policies) ? policies : []).filter(
      (policy) => policy && (policy.name === null || policy.name === undefined)
    );
    const policyEntriesWithNullDashboardIds = (Array.isArray(policies) ? policies : []).filter(
      (policy) => policy && !Array.isArray(policy.dashboard_ids)
    );

    if (policiesWithNullName.length > 0 || policyEntriesWithNullDashboardIds.length > 0) {
      console.warn('[AutomationSettingsPage][Debug] Render-time suspicious policy data detected', {
        policiesWithNullName,
        policyEntriesWithNullDashboardIds
      });
    }
  });
</script>

<div class="container mx-auto p-6 max-w-5xl">
  <div class="flex justify-between items-center mb-8">
    <div>
      <h1 class="text-2xl font-bold text-gray-900 dark:text-white">Automation Policies</h1>
      <p class="text-sm text-gray-500 dark:text-gray-400 mt-1">Manage scheduled validation rules and execution windows.</p>
    </div>
    {#if !showForm}
      <button onclick={handleAdd} 
        class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-primary hover:bg-primary-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-primary-ring">
        <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>
        Create Policy
      </button>
    {/if}
  </div>

  {#if showForm}
    <div class="mb-8">
      <div class="flex items-center mb-4">
        <button onclick={() => showForm = false} class="text-sm text-primary hover:text-primary-hover flex items-center">
          <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>
          Back to list
        </button>
        <span class="mx-2 text-gray-300">|</span>
        <h2 class="text-lg font-medium text-gray-900 dark:text-white">
          {selectedPolicy ? 'Edit Policy' : 'New Policy'}
        </h2>
      </div>
      <PolicyForm 
        policy={selectedPolicy} 
        {environments}
        onSave={handleSave} 
        onCancel={() => showForm = false} 
      />
    </div>
  {:else if isLoading}
    <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}
    <div class="bg-white dark:bg-gray-800 shadow overflow-hidden sm:rounded-md border border-gray-200 dark:border-gray-700">
      <ul class="divide-y divide-gray-200 dark:divide-gray-700">
        {#each policies as policy}
          <li>
            <div class="px-4 py-4 sm:px-6 hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors">
              <div class="flex items-center justify-between">
                <div class="flex items-center">
                  <div class="flex-shrink-0">
                    <div class="h-10 w-10 rounded-full bg-blue-100 dark:bg-blue-900 flex items-center justify-center text-blue-600 dark:text-blue-300">
                      <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">
                    <h3 class="text-sm font-medium text-primary dark:text-blue-400 truncate">{policy.name}</h3>
                    <div class="mt-1 flex items-center text-xs text-gray-500 dark:text-gray-400">
                      <span class="font-medium">{getEnvName(policy.environment_id)}</span>
                      <span class="mx-2">•</span>
                      <span>{policy.dashboard_ids.length} Dashboards</span>
                    </div>
                  </div>
                </div>
                <div class="flex items-center space-x-4">
                  <div class="text-right hidden sm:block">
                    <div class="text-xs font-medium text-gray-900 dark:text-white">
                      {policy.window_start} - {policy.window_end}
                    </div>
                    <div class="text-xs text-gray-500 dark:text-gray-400">
                      {policy.schedule_days.map(d => dayLabels[d]).join(', ')}
                    </div>
                  </div>
                  <div class="flex items-center space-x-2">
                    <button onclick={() => handleEdit(policy)} aria-label="Edit policy" title="Edit policy" class="p-2 text-gray-400 hover:text-blue-600 dark:hover:text-blue-400">
                      <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 onclick={() => handleDelete(policy.id)} aria-label="Delete policy" title="Delete policy" class="p-2 text-gray-400 hover:text-red-600 dark:hover:text-red-400">
                      <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 class="px-4 py-12 text-center">
            <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
            </svg>
            <h3 class="mt-2 text-sm font-medium text-gray-900 dark:text-white">No policies</h3>
            <p class="mt-1 text-sm text-gray-500 dark:text-gray-400">Get started by creating a new automation policy.</p>
            <div class="mt-6">
              <button onclick={handleAdd} class="inline-flex items-center px-4 py-2 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-primary hover:bg-primary-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-primary-ring">
                Create Policy
              </button>
            </div>
          </li>
        {/each}
      </ul>
    </div>

    {#if translationSchedules.length > 0}
      <h2 class="text-xl font-semibold text-gray-900 dark:text-white mb-4 mt-8">Translation Schedules</h2>
      <div class="bg-white dark:bg-gray-800 shadow overflow-hidden sm:rounded-md border border-gray-200 dark:border-gray-700">
        <ul class="divide-y divide-gray-200 dark:divide-gray-700">
          {#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">
                    <div class="flex-shrink-0">
                      <div class="h-10 w-10 rounded-full bg-amber-100 dark:bg-amber-900 flex items-center justify-center text-amber-600 dark:text-amber-300">
                        <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">
                      <h3 class="text-sm font-medium text-gray-900 dark:text-white">{ts.job_name}</h3>
                      <div class="mt-1 flex items-center text-xs text-gray-500 dark:text-gray-400">
                        <span class="font-mono">{ts.cron_expression}</span>
                        <span class="mx-2">•</span>
                        <span>{ts.timezone}</span>
                      </div>
                    </div>
                  </div>
                  <div class="flex items-center space-x-3">
                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium {ts.is_active ? 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200' : 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300'}">
                      {ts.is_active ? 'Active' : 'Inactive'}
                    </span>
                    {#if ts.last_run_at}
                      <span class="text-xs text-gray-500 dark:text-gray-400">
                        Last: {new Date(ts.last_run_at).toLocaleString()}
                      </span>
                    {/if}
                  </div>
                </div>
              </div>
            </li>
          {:else}
            <li class="px-4 py-8 text-center text-sm text-gray-500 dark:text-gray-400">
              No translation schedules configured
            </li>
          {/each}
        </ul>
      </div>
    {/if}
  {/if}
</div>
<!-- #endregion AutomationPage -->