<!--
/**
 * inPIPE Settings Component - Free Version
 *
 * Clean settings component with no premium awareness or dependencies.
 * Handles basic UTM processing toggle and free version settings only.
 *
 * @package InPipe
 * @subpackage Free/Shared
 * @since 1.0.0
 * @since 1.0.2 Updated styling for main-title and text-group elements, updated upgrade messaging and buttons
 * @author Seresa
 * @license GPL-2.0+
 * @link https://seresa.io
 */
-->

<template>
  <div class="settings-container">
    <!-- Security Check Failed Message -->
    <div v-if="securityCheckFailed" class="security-warning">
      <inPipeBaseCard>
        <div class="text-center">
          <inPipeBaseText variant="danger" tag="h2">
            {{ $__("common.access_denied", "Access Denied") }}
          </inPipeBaseText>
          <div class="text-group">
            <inPipeBaseText>
              {{ $__("common.permission_error", "You don't have permission to access this component directly.") }}
            </inPipeBaseText>
            <inPipeBaseText>
              {{ $__("common.use_main_interface", "Please use the main application interface.") }}
            </inPipeBaseText>
          </div>
        </div>
      </inPipeBaseCard>
    </div>

    <div v-else class="settings-content">
      <!-- Header Card -->
      <inPipeBaseCard>
        <div class="text-center">
          <inPipeBaseText variant="title" tag="h2" class="main-title">
            {{ $__("components.settings.title", "General Settings") }}
          </inPipeBaseText>
          <div class="text-group">
            <inPipeBaseText variant="description">
              {{ $__("components.settings.description", "Configure your inPIPE free version settings") }}
            </inPipeBaseText>
          </div>
        </div>
      </inPipeBaseCard>

      <!-- UTM Processing Settings -->
      <inPipeBaseCard class="mt-6">
        <div class="card-header">
          <inPipeBaseText variant="title" tag="h3">
            {{ $__("components.settings.utm_processing.title", "UTM Processing") }}
          </inPipeBaseText>
          <inPipeBaseText variant="description">
            {{ $__("components.settings.utm_processing.description", "Enable or disable UTM parameter processing") }}
          </inPipeBaseText>
        </div>

        <div class="setting-item">
          <div class="setting-control">
            <inPipeBaseToggle
              v-model="utmProcessingEnabled"
              :disabled="isLoading || isToggling"
              @update:modelValue="handleUtmProcessingToggle"
            />
            <div class="setting-info">
              <inPipeBaseText class="setting-label">
                {{ $__("components.settings.utm_processing.enable_label", "Enable UTM Processing") }}
              </inPipeBaseText>
              <inPipeBaseText variant="description" class="setting-description">
                {{ $__("components.settings.utm_processing.enable_description", "Process and track UTM parameters from incoming traffic") }}
              </inPipeBaseText>
            </div>
          </div>

          <!-- UTM Processing Requirements -->
          <div v-if="showUtmWarning" class="utm-warning mt-4">
            <inPipeBaseText variant="warning">
              {{ $__("components.settings.utm_required", "At least one UTM parameter is needed before enabling processing") }}
            </inPipeBaseText>
          </div>
        </div>
      </inPipeBaseCard>

      <!-- Free Version Information -->
      <inPipeBaseCard class="mt-6">
        <div class="card-header">
          <inPipeBaseText variant="title" tag="h3">
            {{ $__("components.settings.version.title", "Version Information") }}
          </inPipeBaseText>
        </div>

        <div class="version-info">
          <div class="version-item">
            <inPipeBaseText class="version-label">
              {{ $__("components.settings.version.current", "Current Version:") }}
            </inPipeBaseText>
            <inPipeBaseText class="version-value">
              {{ $__("components.settings.version.free", "inPIPE Free") }}
            </inPipeBaseText>
          </div>

          <div class="version-item">
            <inPipeBaseText class="version-label">
              {{ $__("components.settings.version.features", "Available Features:") }}
            </inPipeBaseText>
            <ul class="feature-list">
              <li>{{ $__("components.settings.features.utm_generation", "UTM Parameter Generation") }}</li>
              <li>{{ $__("components.settings.features.utm_storage", "UTM Code Storage") }}</li>
              <li>{{ $__("components.settings.features.basic_tracking", "Basic URL Tracking") }}</li>
            </ul>
          </div>

          <div class="upgrade-info mt-4">
            <inPipeBaseText class="upgrade-header">
              {{ $__("components.settings.upgrade.header", "Upgrade to our Premium Transmute Engine™ service for WordPress") }}
            </inPipeBaseText>
            <inPipeBaseText class="mt-2 upgrade-description">
              {{ $__("components.settings.upgrade.description", "Managed through inPIPE plugin seamlessly send your event data to multiple endpoints like GA4, gAds, Facebook Ads, Klaviyo & Big Query all processed server side for maximum efficiency and reliability. No Google Tag Manager Required!") }}
              <a href="https://seresa.io/transmute-engine-free-trial" target="_blank" class="upgrade-link">
                {{ $__("components.settings.upgrade.trial_link", "Get a free trial today.") }}
              </a>
            </inPipeBaseText>
            <div class="upgrade-buttons">
              <inPipeBaseButton
                variant="primary"
                @click="handleLearnMoreClick"
                class="upgrade-button"
              >
                {{ $__("components.settings.upgrade.learn_more", "Learn More") }}
              </inPipeBaseButton>
              <inPipeBaseButton
                variant="primary"
                @click="handleFreeTrialClick"
                class="upgrade-button"
              >
                {{ $__("components.settings.upgrade.free_trial", "Free Trial") }}
              </inPipeBaseButton>
            </div>
          </div>
        </div>
      </inPipeBaseCard>

      <!-- Saved Message -->
      <div v-if="savedMessage" class="mt-6">
        <inPipeBaseCard>
          <div class="saved-message">
            <inPipeBaseText variant="success">
              ✅ {{ savedMessageText }}
            </inPipeBaseText>
          </div>
        </inPipeBaseCard>
      </div>
    </div>
  </div>
</template>

<script setup>
/**
 * Settings Component Script - Free Version
 * Simple state management with no premium dependencies
 */

import { ref, computed, watch, onBeforeMount, onMounted } from "vue";
import { useToast } from "vue-toastification";
import { $__ } from "@utils/inPipeTranslate.js";
import api from "@utils/inPipeAxios.js";
import API_ENDPOINTS, { PARAM_NAMES } from '@utils/inPipeApiEndpoints.js';

// Import clean base components
import inPipeBaseCard from "@base/inPipeBaseCard.vue";
import inPipeBaseText from "@base/inPipeBaseText.vue";
import inPipeBaseButton from "@base/inPipeBaseButton.vue";
import inPipeBaseToggle from "@base/inPipeBaseToggle.vue";

// Define emits for parent communication
const emit = defineEmits(['settings-saved']);

// Toast instance
const toast = useToast();

// Security check state
const securityCheckFailed = ref(false);

// Component state - simple reactive variables
const isLoading = ref(false);
const utmProcessingEnabled = ref(false);
const hasUtmRecords = ref(false);
const showUtmWarning = ref(false);
const savedMessage = ref(false);
const savedMessageText = ref("");
const toggleDebounceTimer = ref(null);
const isToggling = ref(false);

/**
 * Perform security check
 * 
 * @return {boolean} True if security check passes
 * @since 1.0.0
 */
const performSecurityCheck = () => {
  if (!window.inPipeData) {
    securityCheckFailed.value = true;
    return false;
  }
  return true;
};

/**
 * Check if UTM records exist
 * 
 * @return {boolean} True if UTM records exist
 * @since 1.0.0
 */
const checkUtmRecords = async () => {
  try {
    const response = await api.get(API_ENDPOINTS.UTM_FETCH);
    
    let utmRecords = [];
    if (response?.data?.data?.records && Array.isArray(response.data.data.records)) {
      utmRecords = response.data.data.records;
    }
    
    // Apply robust filtering to ensure we only count valid UTMs
    const validUtms = utmRecords.filter((utm) => {
      // Check for valid standard UTM params
      let hasValidParams = false;
      if (utm.params && typeof utm.params === "object") {
        hasValidParams = Object.values(utm.params).some(
          (value) => value && typeof value === "string" && value.trim() !== "",
        );
      }
      
      // Check for valid custom params
      let hasValidCustomParams = false;
      if (Array.isArray(utm.customParams)) {
        hasValidCustomParams = utm.customParams.some(
          (param) =>
            param &&
            typeof param === "object" &&
            param.key &&
            param.value &&
            String(param.key).trim() !== "" &&
            String(param.value).trim() !== ""
        );
      }
      
      return hasValidParams || hasValidCustomParams;
    });

    // DEBUG_START
    console.log("[inPipe Settings] UTM records check:", {
      rawCount: utmRecords.length,
      validCount: validUtms.length,
      hasValidRecords: validUtms.length > 0,
    });
    // DEBUG_END

    hasUtmRecords.value = validUtms.length > 0;
    return hasUtmRecords.value;
  } catch (error) {
    // DEBUG_START
    console.error("[inPipe Settings] Error checking UTM records:", error);
    // DEBUG_END
    
    hasUtmRecords.value = false;
    return false;
  }
};

/**
 * Handle UTM processing toggle with debouncing
 * 
 * @param {boolean} enabled - New toggle state
 * @since 1.0.0
 */
 const handleUtmProcessingToggle = async (enabled) => {
  // Clear any existing timer
  if (toggleDebounceTimer.value) {
    clearTimeout(toggleDebounceTimer.value);
  }

  // Prevent multiple rapid clicks
  if (isToggling.value) {
    // DEBUG_START
    console.log("[inPipe Settings] Toggle ignored - already processing");
    // DEBUG_END
    return;
  }

  // Set debounce timer
  toggleDebounceTimer.value = setTimeout(async () => {
    await performToggle(enabled);
  }, 300); // 300ms debounce delay
};

/**
 * Perform the actual toggle operation
 * 
 * @param {boolean} enabled - New toggle state
 * @since 1.0.0
 */
const performToggle = async (enabled) => {
  if (isToggling.value) return;
  
  try {
    isToggling.value = true;
    
    if (enabled) {
      // Re-check UTM records first to be absolutely sure
      const hasRecords = await checkUtmRecords();
      
      if (!hasRecords) {
        // DEBUG_START
        console.log("[inPipe Settings] Toggle failed - no UTM records found");
        // DEBUG_END

        toast.error($__("components.settings.utm_required", "At least one UTM parameter is needed"));
        utmProcessingEnabled.value = false;
        showUtmWarning.value = true;
        return;
      }
    }

    isLoading.value = true;
    showUtmWarning.value = false;

    const result = await api.post(API_ENDPOINTS.SETTINGS, {
      utm_processing_enabled: enabled ? 1 : 0,
    });

    // DEBUG_START
    console.log("[inPipe Settings] Settings update response:", result);
    // DEBUG_END

    if (result.data && (result.data.success || result.data.updated)) {
      utmProcessingEnabled.value = enabled;
      
      const message = enabled
        ? $__("components.settings.utm_enabled", "UTM processing has been enabled.")
        : $__("components.settings.utm_disabled", "UTM processing has been disabled.");
      
      toast.success(message);
      
      // Emit to parent
      emit('settings-saved', { utm_processing_enabled: enabled });
    } else {
      throw new Error(result.data?.message || "Settings update failed");
    }
  } catch (error) {
    // DEBUG_START
    console.error("[inPipe Settings] Toggle error:", error);
    // DEBUG_END

    toast.error($__("components.settings.save_error", "Error saving settings. Please try again later."));
    utmProcessingEnabled.value = !enabled; // Revert toggle
  } finally {
    isLoading.value = false;
    isToggling.value = false;
  }
};

/**
 * Handle Learn More button click
 *
 * @since 1.0.0
 * @since 1.0.2 Updated to new Transmute Engine URL
 */
const handleLearnMoreClick = () => {
  // DEBUG_START
  console.log("[inPipe Settings] Learn More button clicked");
  // DEBUG_END

  window.open("https://seresa.io/transmute-engine-by-seresa", "_blank");
};

/**
 * Handle Free Trial button click
 *
 * @since 1.0.0
 * @since 1.0.2 Updated to new free trial URL
 */
const handleFreeTrialClick = () => {
  // DEBUG_START
  console.log("[inPipe Settings] Free Trial button clicked");
  // DEBUG_END

  window.open("https://seresa.io/transmute-engine-free-trial", "_blank");
};

/**
 * Load current settings from server
 * 
 * @since 1.0.0
 */
const loadSettings = async () => {
  if (securityCheckFailed.value) {
    utmProcessingEnabled.value = false;
    return;
  }

  try {
    // Check UTM records first
    await checkUtmRecords();
    
    const response = await api.get(API_ENDPOINTS.SETTINGS);
    const responseData = response?.data?.data || response?.data || response;

    if (responseData && typeof responseData === "object") {
      let processingEnabled = false;

      if ("utm_processing_enabled" in responseData) {
        processingEnabled = !!responseData.utm_processing_enabled;
      } else if (responseData.settings && "utm_processing_enabled" in responseData.settings) {
        processingEnabled = !!responseData.settings.utm_processing_enabled;
      }

      // Only enable if we have UTM records
      if (hasUtmRecords.value) {
        utmProcessingEnabled.value = processingEnabled;
      } else {
        // Force OFF if no UTM records
        utmProcessingEnabled.value = false;
        
        // If setting was ON but no UTM records exist, update DB
        if (processingEnabled) {
          try {
            await api.post(API_ENDPOINTS.SETTINGS, {
              utm_processing_enabled: 0,
            });
            // DEBUG_START
            console.log("[inPipe Settings] Auto-disabled UTM processing - no records found");
            // DEBUG_END
          } catch (error) {
            // DEBUG_START  
            console.error("[inPipe Settings] Error auto-disabling:", error);
            // DEBUG_END
          }
        }
      }

      // DEBUG_START
      console.log("[inPipe Settings] Settings loaded:", { 
        enabled: utmProcessingEnabled.value,
        hasRecords: hasUtmRecords.value 
      });
      // DEBUG_END
    }
  } catch (error) {
    // DEBUG_START
    console.error("[inPipe Settings] Error loading settings:", error);
    // DEBUG_END

    toast.error($__("components.settings.load_error", "Failed to load settings. Please refresh the page."));
    utmProcessingEnabled.value = false;
  }
};

/**
 * Auto-disable UTM processing when no UTM records exist
 */
watch(hasUtmRecords, async (newHasRecords) => {
  if (!newHasRecords && utmProcessingEnabled.value) {
    // If we no longer have UTM records but processing was enabled, force it OFF
    utmProcessingEnabled.value = false;
    
    try {
      const result = await api.post(API_ENDPOINTS.SETTINGS, {
        utm_processing_enabled: 0,
      });

      if (result.data && (result.data.success || result.data.updated)) {
        toast.info($__("components.settings.auto_disabled", "UTM Processing has been switched OFF - no UTM records remaining"));
        
        // Emit to parent
        emit('settings-saved', { utm_processing_enabled: false });
      }
    } catch (error) {
      // DEBUG_START
      console.error("[inPipe Settings] Error auto-disabling UTM processing:", error);
      // DEBUG_END
    }
  }
});

// Lifecycle hooks
onBeforeMount(() => {
  performSecurityCheck();
});

onMounted(async () => {
  if (!securityCheckFailed.value) {
    try {
      // Check UTM records first
      await checkUtmRecords();
      
      // Then load settings
      await loadSettings();
    } catch (error) {
      // DEBUG_START
      console.error("[inPipe Settings] Initialization error:", error);
      // DEBUG_END
      
      toast.error($__("components.settings.init_error", "Failed to initialize settings. Please refresh the page."));
    }
  }
});
</script>

<style scoped>
/**
 * Settings Component Styles
 * Clean, simple styling for the free version
 *
 * @since 1.0.0
 * @since 1.0.2 Added upgrade header and button styles
 */

.settings-container {
  max-width: 800px;
  margin: 0 auto;
}

.settings-content {
  space-y: 1.5rem;
}

.card-header {
  margin-bottom: 1.5rem;
}

.setting-item {
  padding: 1rem 0;
}

.setting-control {
  display: flex;
  align-items: flex-start;
  gap: 1rem;
}

.setting-info {
  flex: 1;
}

.setting-label {
  font-weight: 600;
  margin-bottom: 0.25rem;
}

.setting-description {
  font-size: 0.875rem;
  color: #6b7280;
}

.utm-warning {
  padding: 0.75rem;
  background-color: #fef3c7;
  border: 1px solid #f59e0b;
  border-radius: 0.5rem;
}

.version-info {
  space-y: 1rem;
}

.version-item {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  flex-wrap: wrap;
}

.version-label {
  font-weight: 600;
  min-width: 120px;
}

.version-value {
  color: #059669;
  font-weight: 500;
}

.feature-list {
  list-style-type: disc;
  margin-left: 1.5rem;
  margin-top: 0.5rem;
}

.feature-list li {
  margin-bottom: 0.25rem;
}

.upgrade-info {
  padding: 1rem;
  background-color: #eff6ff;
  border: 1px solid #3b82f6;
  border-radius: 0.5rem;
}

.upgrade-header {
  font-weight: 600;
  margin-bottom: 0.5rem;
}

.upgrade-description {
  font-size: 0.875rem;
  line-height: 1.5;
}

.upgrade-link {
  color: #2563eb;
  text-decoration: underline;
  margin-left: 0.25rem;
}

.upgrade-link:hover {
  color: #1d4ed8;
}

.upgrade-buttons {
  display: flex;
  gap: 1rem;
  margin-top: 1rem;
  flex-wrap: wrap;
  justify-content: flex-start;
}

.upgrade-button {
  flex: 0 0 auto;
  min-width: 150px;
}

@media (max-width: 768px) {
  .upgrade-buttons {
    flex-direction: column;
  }

  .upgrade-button {
    width: 100%;
  }
}

.saved-message {
  padding: 1rem;
  background-color: #d1fae5;
  border: 1px solid #059669;
  border-radius: 0.5rem;
  text-align: center;
}

.security-warning {
  padding: 2rem;
}

.main-title {
  font-size: 2rem;
  margin-bottom: 1rem;
}

.text-center {
  text-align: center;
}

.text-group {
  margin-top: 1rem;
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.mt-2 { margin-top: 0.5rem; }
.mt-4 { margin-top: 1rem; }
.mt-6 { margin-top: 1.5rem; }
</style>