<script setup>
import { ref, computed, watch } from "vue";
import { storeToRefs } from "pinia";
import { useToast } from "primevue/usetoast";
import draggable from "vuedraggable";
import MediaPickerModal from "@/components/MediaPickerModal.vue";
import AccountSettingsSocials from "@/views/pages/account-settings/AccountSettingsSocials.vue";
import { useSettingStore } from "@/stores/settingStore";
import { useAuthStore } from "@/stores/authStore";

// Stores
const settingStore = useSettingStore();
const authStore = useAuthStore();
const { setting } = storeToRefs(settingStore);
const { user: authUser } = storeToRefs(authStore);
const toast = useToast();

// Reactive data
const footerForm = ref();
const drag = ref(false);

// Form data
const formData = ref({
  footer_logo: null,
});

// Media Picker State
const showMediaPicker = ref(false);
const selectedLogoData = ref(null); // Stores selected media object
const logoError = ref("");

// Footer data arrays
const footerMenuItems = ref([]);
const contactItems = ref([]);

// Footer settings
const contactHeading = ref("CONTACT US");
// "Contact Us" button shown in the site footer (label + link come from here)
const contactButtonText = ref("CONTACT US");
const contactButtonLink = ref("/contact-us");
const copyrightText = ref(
  "© COPYRIGHT 2023 COMPANY NAME. ALL RIGHTS RESERVED.",
);
const socialHeading = ref("");
const socialIcon = ref(true);

// Counter for unique IDs
let footerMenuIdCounter = 1;
let contactIdCounter = 1;

// ✅ FIXED: Social Links Configuration - Properly reactive
const socialLinksData = ref({
  facebook: "",
  instagram: "",
  twitter: "",
  linkedin: "",
  youtube: "",
  tiktok: "",
  enableSharing: false,
});

// Create individual refs for v-model binding
const facebook = computed({
  get: () => socialLinksData.value.facebook,
  set: (value) => {
    socialLinksData.value.facebook = value;
  },
});

const instagram = computed({
  get: () => socialLinksData.value.instagram,
  set: (value) => {
    socialLinksData.value.instagram = value;
  },
});

const twitter = computed({
  get: () => socialLinksData.value.twitter,
  set: (value) => {
    socialLinksData.value.twitter = value;
  },
});

const linkedin = computed({
  get: () => socialLinksData.value.linkedin,
  set: (value) => {
    socialLinksData.value.linkedin = value;
  },
});

const youtube = computed({
  get: () => socialLinksData.value.youtube,
  set: (value) => {
    socialLinksData.value.youtube = value;
  },
});

const tiktok = computed({
  get: () => socialLinksData.value.tiktok,
  set: (value) => {
    socialLinksData.value.tiktok = value;
  },
});

const enableSharing = computed({
  get: () => socialLinksData.value.enableSharing,
  set: (value) => {
    socialLinksData.value.enableSharing = value;
  },
});

// Check if user is super admin
const isSuperAdmin = computed(
  () => authUser.value?.data?.role === "super_admin",
);

// Count user-created menus (non-global)
const userMenuCount = computed(() => {
  return footerMenuItems.value.filter((item) => !item.is_globle).length;
});

// Check if user can add more menus
const canAddMoreMenus = computed(() => {
  if (isSuperAdmin.value) return true;
  return userMenuCount.value < 2;
});

// Use selected media from picker or existing footer logo
const currentFooterLogo = computed(() => {
  // Priority 1: Selected from media picker
  if (selectedLogoData.value?.url) {
    return selectedLogoData.value.url;
  }
  // Priority 2: Existing footer logo
  if (formData.value?.footer_logo) {
    return formData.value.footer_logo;
  }
  // Priority 3: No logo
  return null;
});

// Open Media Picker when logo is clicked
const openMediaPicker = () => {
  if (!settingStore.loading) {
    showMediaPicker.value = true;
  }
};

// Handle media selection from picker
const handleMediaSelect = (selectedMedia) => {
  if (selectedMedia) {
    selectedLogoData.value = {
      id: selectedMedia.id,
      url: selectedMedia.url,
      filename: selectedMedia.filename,
    };
    logoError.value = "";
  }

  // Modal will close automatically via v-model
  showMediaPicker.value = false;
};

// Add new footer menu item
// Update addNewFooterMenuItem function
const addNewFooterMenuItem = () => {
  if (!canAddMoreMenus.value) {
    toast.add({
      severity: "warning",
      summary: "Limit Reached",
      detail: "You can only add up to 2 footer menu items",
      life: 3000,
    });
    return;
  }

  const newItem = {
    id: footerMenuIdCounter++,
    name: "",
    url: "",
    protocol: "https", // Add default protocol
    access: isSuperAdmin.value ? true : "",
    status: true,
    is_globle: isSuperAdmin.value,
    order_no: footerMenuItems.value.length + 1,
  };

  footerMenuItems.value.push(newItem);
};

// Remove footer menu item
const removeFooterMenuItem = (index) => {
  const item = footerMenuItems.value[index];

  // Prevent removing global menus for non-super admin
  if (!isSuperAdmin.value && item.is_globle) {
    toast.add({
      severity: "warning",
      summary: "Cannot Remove",
      detail: "Global footer menus can only be removed by administrators",
      life: 3000,
    });
    return;
  }

  footerMenuItems.value.splice(index, 1);
  updateFooterMenuOrder();
};

// Add new contact item
const addNewContactItem = () => {
  contactItems.value.push({
    id: contactIdCounter++,
    name: "",
    value: "",
    status: true,
    is_globle: isSuperAdmin.value,
    order_no: contactItems.value.length + 1,
  });
};

// Remove contact item
const removeContactItem = (index) => {
  const item = contactItems.value[index];

  // Prevent removing global contacts for non-super admin
  if (!isSuperAdmin.value && item.is_globle) {
    toast.add({
      severity: "warning",
      summary: "Cannot Remove",
      detail:
        "Global contact information can only be removed by administrators",
      life: 3000,
    });
    return;
  }

  contactItems.value.splice(index, 1);
  updateContactOrder();
};

// Update footer menu order after drag/drop or removal
const updateFooterMenuOrder = () => {
  footerMenuItems.value.forEach((item, index) => {
    item.order_no = index + 1;
  });
};

// Update contact order after drag/drop or removal
const updateContactOrder = () => {
  contactItems.value.forEach((item, index) => {
    item.order_no = index + 1;
  });
};
// Add these protocol options (same as header)
const protocolOptions = [
  { text: "https://", value: "https" },
  { text: "Relative (/)", value: "relative" },
];

// URL validation function for footer (same as header)
const validateFooterUrl = (url, item) => {
  if (!url || !url.trim()) return true; // Allow empty URLs

  const trimmedUrl = url.trim();
  const protocol = item?.protocol || "https";

  if (protocol === "relative") {
    // Validate relative paths
    if (!trimmedUrl.startsWith("/")) {
      return "Relative URLs must start with /";
    }
    // Check for valid relative path pattern
    if (!/^\/[\w\-\.\/]*$/.test(trimmedUrl)) {
      return "Invalid relative URL format";
    }
    return true;
  } else {
    // Validate HTTPS URLs (without protocol prefix)
    if (trimmedUrl.startsWith("http://") || trimmedUrl.startsWith("https://")) {
      return "Please enter domain only (e.g., example.com)";
    }
    // Basic domain validation
    const domainPattern =
      /^[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?)*$/;
    if (!domainPattern.test(trimmedUrl)) {
      return "Please enter a valid domain name";
    }
    return true;
  }
};

// ✅ FIXED: Save footer settings with proper social links data
const saveFooterSettings = async () => {
  try {
    // Update orders before saving
    updateFooterMenuOrder();
    updateContactOrder();

    // Prepare menu items in exact format
    // In saveFooterSettings function, update this part:
    const validMenuItems = footerMenuItems.value
      .filter((item) => item.name.trim())
      .map((item) => {
        let finalUrl = item.url.trim();

        // Construct proper URL based on protocol selection
        if (item.protocol === "https" && finalUrl) {
          // Only add https:// if it's not already there
          if (!finalUrl.startsWith("https://")) {
            finalUrl = `https://${finalUrl}`;
          }
        } else if (item.protocol === "relative" && finalUrl) {
          // Ensure relative URLs start with /
          if (!finalUrl.startsWith("/")) {
            finalUrl = `/${finalUrl}`;
          }
        }

        return {
          name: item.name.trim(),
          url: finalUrl,
          access: isSuperAdmin.value ? item.access || "" : "",
          status: item.status || "",
          is_globle: item.is_globle,
          order_no: item.order_no,
        };
      });

    const validContactItems = contactItems.value
      .filter((item) => item.name.trim() && item.value.trim())
      .map((item) => ({
        name: item.name.trim(),
        value: item.value.trim(),
        status: item.status || "",
        is_globle: item.is_globle,
        order_no: item.order_no,
      }));

    // ✅ FIXED: Use current social links data
    const socialLinksConfig = {
      facebook: socialLinksData.value.facebook || "",
      instagram: socialLinksData.value.instagram || "",
      twitter: socialLinksData.value.twitter || "",
      linkedin: socialLinksData.value.linkedin || "",
      youtube: socialLinksData.value.youtube || "",
      tiktok: socialLinksData.value.tiktok || "",
      enable_sharing: socialLinksData.value.enableSharing || false,
    };

    // Debug log to check social link
    // Handle selected media from picker or use existing logo
    const payload = {
      footer_settings: {
        // Use selected logo, existing logo, or empty string
        logo: selectedLogoData.value?.url || formData.value.footer_logo || "",
        footer_menu: validMenuItems,
        contact_info: {
          heading: contactHeading.value,
          items: validContactItems,
          button: {
            text: contactButtonText.value?.trim() || "",
            link: contactButtonLink.value?.trim() || "",
          },
        },
        copyright_text: copyrightText.value,
        social_heading: socialHeading.value,
        social_icon: socialIcon.value,
        social_links_configuration: socialLinksConfig,
      },
    };

    // Include logo ID if selected from media picker
    if (selectedLogoData.value?.id) {
      payload.footer_settings.logo_id = selectedLogoData.value.id;
    }

    const response = await settingStore.saveSettings(payload);

    if (response.status === true) {
      // Update formData with new logo from API response
      if (response.data?.footer_settings?.logo) {
        formData.value.footer_logo = response.data.footer_settings.logo;
      }

      // Reset selected media after successful save
      selectedLogoData.value = null;
    }
  } catch (error) {
    console.error("Error saving footer settings:", error);
  }
};

// Reset form
const resetForm = () => {
  if (isSuperAdmin.value) {
    selectedLogoData.value = null;
    formData.value.footer_logo = null;
    footerMenuItems.value = [];
    contactItems.value = [];
  } else {
    footerMenuItems.value = footerMenuItems.value.filter(
      (item) => item.is_globle,
    );
    contactItems.value = contactItems.value.filter((item) => item.is_globle);
  }

  contactHeading.value = "CONTACT US";
  contactButtonText.value = "CONTACT US";
  contactButtonLink.value = "/contact-us";
  copyrightText.value = "© COPYRIGHT 2023 COMPANY NAME. ALL RIGHTS RESERVED.";
  socialHeading.value = "";
  socialIcon.value = true;
  footerMenuIdCounter = 1;
  contactIdCounter = 1;

  // ✅ FIXED: Reset social links
  socialLinksData.value = {
    facebook: "",
    instagram: "",
    twitter: "",
    linkedin: "",
    youtube: "",
    tiktok: "",
    enableSharing: false,
  };
};

// Load existing footer settings from store
const loadFooterSettings = (settingsData) => {
  if (settingsData?.footer_settings) {
    const footerData = settingsData.footer_settings;

    // Load logo preview if exists
    if (footerData.logo && footerData.logo.trim() !== "") {
      formData.value.footer_logo = footerData.logo;
    }

    // Load footer menu items
    // In loadFooterSettings function, update the footer menu section:
    if (footerData.footer_menu && Array.isArray(footerData.footer_menu)) {
      footerMenuItems.value = footerData.footer_menu.map((menuItem, index) => {
        footerMenuIdCounter = Math.max(
          footerMenuIdCounter,
          (menuItem.id || index) + 1,
        );

        // Parse URL to determine protocol and clean URL
        let protocol = "https";
        let cleanUrl = menuItem.url || "";

        if (cleanUrl.startsWith("https://")) {
          protocol = "https";
          cleanUrl = cleanUrl.replace("https://", "");
        } else if (cleanUrl.startsWith("/")) {
          protocol = "relative";
        }

        return {
          id: menuItem.id || ++footerMenuIdCounter,
          name: menuItem.name || "",
          url: cleanUrl,
          protocol: protocol, // Add protocol field
          access: menuItem.access || "",
          status:
            menuItem.status === "true" ||
            menuItem.status === true ||
            menuItem.status === "",
          is_globle: menuItem.is_globle || false,
          order_no: menuItem.order_no || index + 1,
        };
      });

      // Sort by order_no
      footerMenuItems.value.sort((a, b) => a.order_no - b.order_no);
    }

    // Load contact information
    if (footerData.contact_info) {
      contactHeading.value = footerData.contact_info.heading || "CONTACT US";

      // Load footer "Contact Us" button (label + link)
      contactButtonText.value =
        footerData.contact_info.button?.text || "CONTACT US";
      contactButtonLink.value =
        footerData.contact_info.button?.link || "/contact-us";

      if (
        footerData.contact_info.items &&
        Array.isArray(footerData.contact_info.items)
      ) {
        contactItems.value = footerData.contact_info.items.map(
          (contactItem, index) => {
            contactIdCounter = Math.max(
              contactIdCounter,
              (contactItem.id || index) + 1,
            );

            return {
              id: contactItem.id || ++contactIdCounter,
              name: contactItem.name || "",
              value: contactItem.value || "",
              status:
                contactItem.status === "true" ||
                contactItem.status === true ||
                contactItem.status === "",
              is_globle: contactItem.is_globle || false,
              order_no: contactItem.order_no || index + 1,
            };
          },
        );

        // Sort by order_no
        contactItems.value.sort((a, b) => a.order_no - b.order_no);
      }
    }

    // Load additional settings
    copyrightText.value = footerData.copyright_text || copyrightText.value;
    socialHeading.value = footerData.social_heading || "";
    socialIcon.value =
      footerData.social_icon === "true" || footerData.social_icon === true;

    // ✅ FIXED: Load social links configuration
    if (footerData.social_links_configuration) {
      socialLinksData.value = {
        facebook: footerData.social_links_configuration.facebook || "",
        instagram: footerData.social_links_configuration.instagram || "",
        twitter: footerData.social_links_configuration.twitter || "",
        linkedin: footerData.social_links_configuration.linkedin || "",
        youtube: footerData.social_links_configuration.youtube || "",
        tiktok: footerData.social_links_configuration.tiktok || "",
        enableSharing:
          footerData.social_links_configuration.enable_sharing || false,
      };
    }
  }

  // ✅ ADDED: Also load from main social_links_configuration if exists
  if (settingsData?.social_links_configuration) {
    socialLinksData.value = {
      facebook:
        settingsData.social_links_configuration.facebook ||
        socialLinksData.value.facebook,
      instagram:
        settingsData.social_links_configuration.instagram ||
        socialLinksData.value.instagram,
      twitter:
        settingsData.social_links_configuration.twitter ||
        socialLinksData.value.twitter,
      linkedin:
        settingsData.social_links_configuration.linkedin ||
        socialLinksData.value.linkedin,
      youtube:
        settingsData.social_links_configuration.youtube ||
        socialLinksData.value.youtube,
      tiktok:
        settingsData.social_links_configuration.tiktok ||
        socialLinksData.value.tiktok,
      enableSharing:
        settingsData.social_links_configuration.enable_sharing ||
        socialLinksData.value.enableSharing,
    };
  }
};

// Watch for settings changes and prefill form
watch(
  setting,
  (val) => {
    if (val) {
      loadFooterSettings(val);
    }
  },
  { immediate: true },
);
</script>

<template>
  <VCard class="mb-6">
    <VCardItem class="pb-6">
      <VCardTitle class="d-flex align-center">
        <VIcon icon="bx-dock-bottom" class="me-3" size="24" />
        Footer Settings
      </VCardTitle>
      <VCardSubtitle
        >Configure your website footer logo, menu links, and contact
        information</VCardSubtitle
      >
    </VCardItem>

    <VCardText>
      <VForm ref="footerForm">
        <!-- Footer Logo Section - Only for Super Admin -->
        <div class="mb-8" v-if="isSuperAdmin">
          <h6 class="text-h6 mb-4">Footer Logo</h6>
          <VRow>
            <VCol cols="12" md="6">
              <div class="logo-image-container">
                <div
                  class="logo-image-selector"
                  :class="{ loading: settingStore.loading }"
                  @click="openMediaPicker"
                >
                  <!-- Always show image (selected, existing, or placeholder) -->
                  <img
                    v-if="currentFooterLogo"
                    :src="currentFooterLogo"
                    alt="Footer Logo"
                    class="logo-img"
                  />

                  <!-- Placeholder when no logo -->
                  <div v-else class="logo-placeholder">
                    <VIcon icon="bx-image" size="48" color="grey-lighten-1" />
                    <p class="text-grey-darken-1 mt-2">Click to select logo</p>
                  </div>

                  <!-- Edit Icon Overlay -->
                  <div class="edit-overlay">
                    <svg
                      width="20"
                      height="20"
                      viewBox="0 0 24 24"
                      fill="currentColor"
                    >
                      <path
                        d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04c.39-.39.39-1.02 0-1.41l-2.34-2.34c-.39-.39-1.02-.39-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"
                      />
                    </svg>
                  </div>
                </div>
              </div>

              <!-- Error message -->
              <div v-if="logoError" class="error-message mt-2">
                {{ logoError }}
              </div>

              <!-- Help text -->
              <small v-else class="text-muted d-block mt-2"
                >Click on the image to select from media library (Max
                5MB)</small
              >
            </VCol>
            <VCol cols="12" md="6">
              <!-- Empty column for layout alignment -->
            </VCol>
          </VRow>
        </div>

        <!-- Show existing logo for non-super admin (read-only) -->
        <div class="mb-8" v-else-if="formData.footer_logo">
          <h6 class="text-h6 mb-4">Current Footer Logo</h6>
          <div class="logo-preview">
            <img
              :src="formData.footer_logo"
              alt="Current Footer Logo"
              class="preview-image"
            />
            <p class="text-muted mt-2">
              Contact administrator to change footer logo
            </p>
          </div>
        </div>

        <VDivider class="mb-6" />

        <!-- Footer Menu Section -->
        <div class="mb-8 account-footer-menu">
          <div class="d-flex justify-space-between align-center mb-4">
            <h6 class="text-h6">Footer Menu Links</h6>
            <VBtn
              color="primary"
              @click="addNewFooterMenuItem"
              prepend-icon="bx-plus"
              :disabled="!canAddMoreMenus"
            >
              Add Menu Link
              <span v-if="!isSuperAdmin" class="ml-1"
                >({{ userMenuCount }}/2)</span
              >
            </VBtn>
          </div>

          <!-- Show limit message for non-super admin -->
          <VAlert
            v-if="!isSuperAdmin && userMenuCount >= 2"
            type="info"
            variant="tonal"
            class="mb-4"
          >
            You can only add up to 2 footer menu items. Contact administrator
            for more.
          </VAlert>

          <div v-if="footerMenuItems.length === 0" class="text-center py-6">
            <VIcon
              icon="bx-link"
              size="48"
              color="grey-lighten-1"
              class="mb-3"
            />
            <p class="text-grey-darken-1">No footer menu links added yet</p>
            <VBtn
              color="primary"
              variant="outlined"
              @click="addNewFooterMenuItem"
              prepend-icon="bx-plus"
              :disabled="!canAddMoreMenus"
            >
              Add First Menu Link
            </VBtn>
          </div>

          <div v-else class="menu-items-container">
            <!-- Table Header -->
            <VRow class="menu-header mb-3" align="center">
              <VCol cols="1" class="d-flex justify-center">
                <span class="text-subtitle-2 text-grey-darken-2 text-center"
                  >Order</span
                >
              </VCol>
              <VCol :cols="isSuperAdmin ? 3 : 4" class="d-flex justify-center">
                <span class="text-subtitle-2 text-grey-darken-2 text-center"
                  >Menu Name</span
                >
              </VCol>
              <VCol :cols="isSuperAdmin ? 3 : 4" class="d-flex justify-center">
                <span class="text-subtitle-2 text-grey-darken-2 text-center"
                  >URL</span
                >
              </VCol>
              <VCol cols="2" v-if="isSuperAdmin" class="d-flex justify-center">
                <span class="text-subtitle-2 text-grey-darken-2 text-center"
                  >Access</span
                >
              </VCol>
              <VCol cols="2" class="d-flex justify-center">
                <span class="text-subtitle-2 text-grey-darken-2 text-center"
                  >Status</span
                >
              </VCol>
              <VCol cols="1" class="d-flex justify-center">
                <span class="text-subtitle-2 text-grey-darken-2 text-center"
                  >Action</span
                >
              </VCol>
            </VRow>

            <!-- Draggable Footer Menu Items -->
            <draggable
              v-model="footerMenuItems"
              item-key="id"
              group="footer-menu-items"
              @start="drag = true"
              @end="drag = false"
              @change="updateFooterMenuOrder"
              handle=".drag-handle"
              animation="200"
              ghost-class="ghost-item"
              chosen-class="chosen-item"
              drag-class="drag-item"
            >
              <template #item="{ element: item, index }">
                <div class="menu-item-row mb-3">
                  <VCard
                    variant="outlined"
                    class="pa-3 draggable-card"
                    :class="{ 'global-menu': item.is_globle }"
                  >
                    <VRow align="center">
                      <!-- Drag Handle -->
                      <VCol cols="1" class="d-flex justify-center">
                        <VBtn
                          variant="text"
                          size="small"
                          class="drag-handle"
                          style="cursor: grab"
                        >
                          <VIcon icon="bx-menu" size="18" color="grey" />
                        </VBtn>
                      </VCol>

                      <!-- Menu Name -->
                      <VCol
                        :cols="isSuperAdmin ? 3 : 4"
                        class="d-flex justify-center"
                      >
                        <VTextField
                          v-model="item.name"
                          placeholder="Menu Name"
                          density="compact"
                          hide-details
                          variant="outlined"
                          class="mx-auto"
                          style="max-width: 200px"
                        />
                      </VCol>

                      <!-- URL with Protocol Dropdown -->
                      <VCol
                        :cols="isSuperAdmin ? 3 : 4"
                        class="d-flex justify-center"
                      >
                        <div class="url-input-wrapper d-flex">
                          <!-- Protocol Dropdown -->
                          <VSelect
                            v-model="item.protocol"
                            :items="protocolOptions"
                            item-title="text"
                            item-value="value"
                            density="compact"
                            hide-details
                            variant="outlined"
                            class="protocol-dropdown"
                            style="max-width: 100px"
                            :disabled="!isSuperAdmin && item.is_globle"
                          />
                          <!-- URL Input -->
                          <VTextField
                            v-model="item.url"
                            :placeholder="
                              item.protocol === 'relative'
                                ? '/home'
                                : 'example.com'
                            "
                            density="compact"
                            hide-details
                            variant="outlined"
                            :disabled="!isSuperAdmin && item.is_globle"
                            :rules="[(val) => validateFooterUrl(val, item)]"
                            class="url-input mx-auto"
                            style="max-width: 200px"
                          />
                        </div>
                      </VCol>

                      <!-- Access Toggle - Only for Super Admin -->
                      <VCol
                        cols="2"
                        v-if="isSuperAdmin"
                        class="d-flex justify-center"
                      >
                        <VSwitch
                          v-model="item.access"
                          color="primary"
                          density="compact"
                          hide-details
                          :label="item.access ? 'Public' : 'Private'"
                        />
                      </VCol>

                      <!-- Active/Inactive Toggle -->
                      <VCol cols="2" class="d-flex justify-center">
                        <VSwitch
                          v-model="item.status"
                          color="primary"
                          density="compact"
                          hide-details
                          :label="item.status ? 'Active' : 'Inactive'"
                          :disabled="!isSuperAdmin && item.is_globle"
                        />
                      </VCol>

                      <!-- Remove Button -->
                      <VCol cols="1" class="d-flex justify-center">
                        <VBtn
                          v-if="isSuperAdmin || !item.is_globle"
                          color="primary"
                          variant="text"
                          size="small"
                          icon="bx-trash"
                          @click="removeFooterMenuItem(index)"
                        />
                        <VTooltip v-else>
                          <template #activator="{ props }">
                            <VBtn
                              v-bind="props"
                              color="grey"
                              variant="text"
                              size="small"
                              icon="bx-lock"
                              disabled
                            />
                          </template>
                          <span
                            >Global menu - Contact administrator to remove</span
                          >
                        </VTooltip>
                      </VCol>
                    </VRow>
                  </VCard>
                </div>
              </template>
            </draggable>
          </div>
        </div>

        <VDivider class="mb-6" />

        <!-- Social Links Configuration -->
        <AccountSettingsSocials
          v-model:facebook="facebook"
          v-model:instagram="instagram"
          v-model:twitter="twitter"
          v-model:linkedin="linkedin"
          v-model:youtube="youtube"
          v-model:tiktok="tiktok"
          v-model:enableSharing="enableSharing"
        />

        <VDivider class="mb-6" />

        <!-- Contact Information Section -->
        <div class="mb-8">
          <div class="d-flex justify-space-between align-center mb-4">
            <h6 class="text-h6">Contact Information</h6>
            <VBtn
              color="primary"
              @click="addNewContactItem"
              prepend-icon="bx-plus"
            >
              Add Contact Info
            </VBtn>
          </div>

          <!-- Contact Section Heading -->
          <VRow class="mb-4">
            <VCol cols="12" md="6">
              <VTextField
                v-model="contactHeading"
                label="Contact Section Heading"
                placeholder="CONTACT US"
                variant="outlined"
                density="comfortable"
                class="pt-3"
              />
            </VCol>
          </VRow>

          <!-- Footer "Contact Us" Button -->
          <VRow class="mb-4">
            <VCol cols="12" md="6">
              <VTextField
                v-model="contactButtonText"
                label="Contact Us Button Text"
                placeholder="CONTACT US"
                variant="outlined"
                density="comfortable"
                hint="Label shown on the Contact Us button in the site footer"
                persistent-hint
              />
            </VCol>
            <VCol cols="12" md="6">
              <VTextField
                v-model="contactButtonLink"
                label="Contact Us Button Link"
                placeholder="/contact-us"
                variant="outlined"
                density="comfortable"
                hint="Page the button links to (e.g. /contact-us)"
                persistent-hint
              />
            </VCol>
          </VRow>

          <div v-if="contactItems.length === 0" class="text-center py-6">
            <VIcon
              icon="bx-phone"
              size="48"
              color="grey-lighten-1"
              class="mb-3 "
            />
            <p class="text-grey-darken-1">No contact information added yet</p>
            <VBtn
              color="primary"
              variant="outlined"
              @click="addNewContactItem"
              prepend-icon="bx-plus"
            >
              Add Contact Info
            </VBtn>
          </div>

          <div v-else class="contact-container">
            <!-- Contact Header -->
            <VRow class="contact-header mb-3" align="center">
              <VCol cols="1" class="d-flex justify-center"
                ><span class="text-subtitle-2 text-grey-darken-2 text-center"
                  >Order</span
                ></VCol
              >
              <VCol cols="4" class="d-flex justify-center"
                ><span class="text-subtitle-2 text-grey-darken-2 text-center"
                  >Name</span
                ></VCol
              >
              <VCol cols="5" class="d-flex justify-center"
                ><span class="text-subtitle-2 text-grey-darken-2 text-center"
                  >Value</span
                ></VCol
              >
              <VCol cols="1" class="d-flex justify-center"
                ><span class="text-subtitle-2 text-grey-darken-2 text-center"
                  >Status</span
                ></VCol
              >
              <VCol cols="1" class="d-flex justify-center"
                ><span class="text-subtitle-2 text-grey-darken-2 text-center"
                  >Action</span
                ></VCol
              >
            </VRow>

            <!-- Draggable Contact Items -->
            <draggable
              v-model="contactItems"
              item-key="id"
              group="contact-items"
              handle=".contact-drag-handle"
              animation="200"
              @end="updateContactOrder"
              ghost-class="ghost-item"
              chosen-class="chosen-item"
              drag-class="drag-item"
            >
              <template #item="{ element: item, index }">
                <div class="contact-item-row mb-3">
                  <VCard
                    variant="outlined"
                    class="pa-3 draggable-card"
                    :class="{ 'global-menu': item.is_globle }"
                  >
                    <VRow align="center">
                      <!-- Drag Handle -->
                      <VCol cols="1" class="d-flex justify-center">
                        <VBtn
                          variant="text"
                          size="small"
                          class="contact-drag-handle"
                          style="cursor: grab"
                        >
                          <VIcon icon="bx-menu" size="18" color="grey" />
                        </VBtn>
                      </VCol>

                      <!-- Name -->
                      <VCol cols="4" class="d-flex justify-center">
                        <VTextField
                          v-model="item.name"
                          placeholder="e.g., Phone, Email"
                          density="compact"
                          hide-details
                          variant="outlined"
                          :disabled="!isSuperAdmin && item.is_globle"
                          class="mx-auto contact-name-field"
                        />
                      </VCol>

                      <!-- Value -->
                      <VCol cols="5" class="d-flex justify-center">
                        <VTextField
                          v-model="item.value"
                          placeholder="Enter contact value"
                          density="compact"
                          hide-details
                          variant="outlined"
                          :disabled="!isSuperAdmin && item.is_globle"
                          class="mx-auto contact-value-field"
                        />
                      </VCol>

                      <!-- Status Toggle -->
                      <VCol cols="1" class="d-flex justify-center">
                        <VSwitch
                          v-model="item.status"
                          color="primary"
                          density="compact"
                          hide-details
                          :disabled="!isSuperAdmin && item.is_globle"
                        />
                      </VCol>

                      <!-- Remove Button -->
                      <VCol cols="1" class="d-flex justify-center">
                        <VBtn
                          v-if="isSuperAdmin || !item.is_globle"
                          color="primary"
                          variant="text"
                          size="small"
                          icon="bx-trash"
                          @click="removeContactItem(index)"
                        />
                        <VTooltip v-else>
                          <template #activator="{ props }">
                            <VBtn
                              v-bind="props"
                              color="grey"
                              variant="text"
                              size="small"
                              icon="bx-lock"
                              disabled
                            />
                          </template>
                          <span
                            >Global contact - Contact administrator to
                            remove</span
                          >
                        </VTooltip>
                      </VCol>
                    </VRow>
                  </VCard>
                </div>
              </template>
            </draggable>
          </div>
        </div>

        <VDivider class="mb-6" />

        <!-- Additional Footer Settings -->
        <div class="mb-6">
          <h6 class="text-h6 mb-4">Additional Footer Settings</h6>
          <VRow>
            <VCol cols="12">
              <VTextarea
                v-model="copyrightText"
                label="Copyright Text"
                placeholder="© COPYRIGHT 2023 COMPANY NAME. ALL RIGHTS RESERVED."
                rows="2"
                variant="outlined"
              />
            </VCol>
            <VCol cols="12" md="6">
              <VTextField
                v-model="socialHeading"
                label="Social Media Heading"
                placeholder="FOLLOW US"
                variant="outlined"
                density="comfortable"
              />
            </VCol>
            <VCol cols="12" md="6">
              <VSwitch
                v-model="socialIcon"
                label="Show Social Media Icons"
                color="primary"
              />
            </VCol>
          </VRow>
        </div>

        <!-- Save Actions -->
        <VRow class="mt-6">
          <VCol>
            <VBtn
              color="primary"
              class="me-3"
              @click="saveFooterSettings"
              :loading="settingStore.loading"
            >
              <VIcon icon="bx-save" class="me-2" />
              Save Footer Settings
            </VBtn>
            <VBtn color="secondary" variant="tonal" @click="resetForm">
              <VIcon icon="bx-refresh" class="me-2" />
              Reset All
            </VBtn>
          </VCol>
        </VRow>
      </VForm>
    </VCardText>
  </VCard>

  <!-- Media Picker Modal -->
  <MediaPickerModal
    v-model="showMediaPicker"
    :multiple="false"
    filter-type="image"
    @select="handleMediaSelect"
  />
</template>

<style scoped>
.logo-preview {
  border: 2px dashed rgba(var(--v-theme-primary), 0.3);
  border-radius: 8px;
  padding: 16px;
  text-align: center;
  background-color: rgba(var(--v-theme-primary), 0.05);
}

.preview-image {
  max-width: 200px;
  max-height: 100px;
  object-fit: contain;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* Logo Image Selector */
.logo-image-container {
  display: flex;
  justify-content: flex-start;
  margin-bottom: 12px;
  position: relative;
}

.logo-image-selector {
  position: relative;
  width: 200px;
  height: 120px;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  border: 2px solid #e5e7eb;
  transition: all 0.3s ease;
  background: linear-gradient(135deg, #e5e7eb, #d1d5db);
  display: flex;
  align-items: center;
  justify-content: center;
}

.logo-image-selector:hover {
  border-color: #003b6f;
  box-shadow: 0 4px 12px rgba(0, 59, 111, 0.2);
}

.logo-image-selector.loading {
  cursor: not-allowed;
  opacity: 0.6;
}

.logo-img {
  width: 100%;
  height: 100%;
  object-fit: contain;
  display: block;
  padding: 8px;
}

.logo-placeholder {
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.logo-placeholder p {
  margin: 0;
  font-size: 12px;
}

/* Edit Icon Overlay */
.edit-overlay {
  position: absolute;
  top: 8px;
  right: 8px;
  width: 28px;
  height: 28px;
  background: #1f2937;
  border: 2px solid white;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  transition: all 0.3s ease;
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.3);
  z-index: 1000;
  cursor: pointer;
}

.edit-overlay:hover {
  background: #374151;
  transform: scale(1.05);
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.4);
}

.edit-overlay svg {
  width: 14px;
  height: 14px;
  flex-shrink: 0;
}

/* Error Message */
.error-message {
  color: #ef4444;
  font-size: 12px;
  margin-top: 8px;
}

.menu-items-container {
  max-height: 500px;
  overflow-y: auto;
  overflow-x: auto;
}

.menu-header {
  border-bottom: 1px solid rgba(var(--v-border-color), 0.12);
  padding-bottom: 8px;
  min-width: 1100px;
}

.menu-item-row {
  transition: all 0.2s ease;
  min-width: 1100px;
}

.menu-item-row:hover {
  transform: translateY(-1px);
}

.draggable-card {
  transition: all 0.2s ease;
}

.global-menu {
  background-color: rgba(var(--v-theme-primary), 0.05);
  border-left: 4px solid rgba(var(--v-theme-primary), 0.5);
}

.drag-handle {
  cursor: grab !important;
}

.drag-handle:active {
  cursor: grabbing !important;
}

/* URL Input Wrapper - Horizontal Layout */
.url-input-wrapper {
  display: flex;
  gap: 0;
  align-items: stretch;
  width: 100%;
  max-width: 100%;
}

.protocol-dropdown {
  width: 110px;
  min-width: 110px;
  max-width: 110px;
  flex-shrink: 0;
}

.url-input {
  flex: 1;
  min-width: 140px;
  max-width: 200px;
}

/* Remove border radius to connect fields */
.protocol-dropdown :deep(.v-field) {
  border-top-right-radius: 0 !important;
  border-bottom-right-radius: 0 !important;
  border-right: none !important;
}

.url-input :deep(.v-field) {
  border-top-left-radius: 0 !important;
  border-bottom-left-radius: 0 !important;
}

/* Ensure proper spacing for all columns */
.menu-item-row .v-col {
  padding: 4px 6px !important;
  flex-shrink: 0;
}

/* Prevent overlap between URL and Access columns */
.menu-item-row .v-col:has(.url-input-wrapper) {
  max-width: 320px;
  overflow: visible;
}

.menu-item-row .v-col:has(.v-switch) {
  padding-left: 12px !important;
}

/* Dragging states */
.ghost-item {
  opacity: 0.5;
  transform: rotate(2deg);
}

.chosen-item {
  transform: scale(1.02);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.drag-item {
  transform: rotate(2deg);
  transition: none;
}

/* Custom scrollbar for menu items container */
.menu-items-container::-webkit-scrollbar {
  width: 6px;
  height: 4px;
}

.menu-items-container::-webkit-scrollbar-track {
  background: rgba(0, 0, 0, 0.05);
  border-radius: 3px;
}

.menu-items-container::-webkit-scrollbar-thumb {
  background: rgba(var(--v-theme-primary), 0.4);
  border-radius: 3px;
}

.menu-items-container::-webkit-scrollbar-thumb:hover {
  background: rgba(var(--v-theme-primary), 0.6);
}

/* Mobile responsiveness */
@media (max-width: 960px) {
  .menu-header,
  .menu-item-row .v-row {
    flex-direction: column;
  }

  .menu-header .v-col,
  .menu-item-row .v-col {
    max-width: 100% !important;
    flex-basis: 100% !important;
  }

  .menu-header {
    display: none;
  }

  .protocol-dropdown {
    width: 100px;
    min-width: 100px;
    max-width: 100px;
  }

  .url-input {
    min-width: 120px;
    max-width: none;
  }

  .menu-item-row .v-col:has(.url-input-wrapper) {
    max-width: 100%;
  }
}

/* Responsive preview image */
@media (max-width: 600px) {
  .preview-image {
    max-width: 150px;
    max-height: 75px;
  }
}

.account-footer-menu .v-row.align-center.menu-header.mb-3 {
    background: #b6c7d6;
    padding: 0px 10px;
    border-radius: 4px;
    margin-top: 0;
    margin-left: 0;
    margin-bottom: 8px !important;
}
.account-footer-menu .menu-item-row.mb-3:first-child  {
    padding-top: 8px;
    border-top: 2px solid #22303e33;
}
.account-footer-menu .text-subtitle-2 {
    font-weight: 600;
    color: #003b6f;
}
.v-card.v-theme--light.global-menu {
    background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
    border-left: 4px solid #003b6f;
    border-radius: 8px;
    margin-bottom: 8px;
}
textarea#input-50 {
    padding-top: 14px;
}
input#input-47 {
    padding-top: 10px !important;
}
.contact-container .v-row.align-center.contact-header.mb-3 {
    background: #b6c7d6;
    padding: 0px 10px;
    border-radius: 4px;
    width: 100%;
    margin: auto;
    margin-top: -12px;
    margin-bottom: 8px!important;
}
.contact-container span.text-subtitle-2 {
    font-weight: 600;
    color: #003b6f;
}
.contact-container .v-card.v-theme--light.global-menu {
    padding: 5px 0!important;
}
.contact-container .contact-item-row.mb-3:first-child {
    padding-top: 8px;
    border-top: 2px solid #22303e33;
}
</style>
