// Home Form Handler - Convert form inputs to JSON before submission
document.addEventListener('DOMContentLoaded', function() {
  const form = document.querySelector('form[action="/admin/home/update"]');
  if (!form) return;

  form.addEventListener('submit', function(e) {
    e.preventDefault();

    try {
      // Hero
      const heroData = {
        title: document.getElementById('heroTitle')?.value || '',
        subtitle: document.getElementById('heroSubtitle')?.value || '',
        description: document.getElementById('heroDescription')?.value || '',
        primaryButton: {
          label: document.getElementById('heroPrimaryButtonLabel')?.value || '',
          href: document.getElementById('heroPrimaryButtonHref')?.value || '',
        },
        secondaryButton: {
          label: document.getElementById('heroSecondaryButtonLabel')?.value || '',
          href: document.getElementById('heroSecondaryButtonHref')?.value || '',
        },
        backgroundImage: document.getElementById('heroBackgroundImage')?.value || '',
        videoUrl: document.getElementById('heroVideoUrl')?.value || '',
      };
      document.getElementById('heroJson').value = JSON.stringify(heroData);

      // Why Choose Us
      const whyChooseUsItems = [];
      let index = 0;
      while (document.getElementById(`whyChooseUsIcon_${index}`)) {
        whyChooseUsItems.push({
          icon: document.getElementById(`whyChooseUsIcon_${index}`)?.value || '',
          title: document.getElementById(`whyChooseUsTitle_${index}`)?.value || '',
          description: document.getElementById(`whyChooseUsItemDescription_${index}`)?.value || '',
        });
        index++;
      }

      const whyChooseUsFeatures = [];
      index = 0;
      while (document.getElementById(`whyChooseUsFeature_${index}`)) {
        const feature = document.getElementById(`whyChooseUsFeature_${index}`)?.value;
        if (feature) whyChooseUsFeatures.push(feature);
        index++;
      }

      const whyChooseUsData = {
        heading: document.getElementById('whyChooseUsHeading')?.value || '',
        subheading: document.getElementById('whyChooseUsSubheading')?.value || '',
        description: document.getElementById('whyChooseUsDescription')?.value || '',
        items: whyChooseUsItems,
        features: whyChooseUsFeatures,
        ctaButton: {
          label: document.getElementById('whyChooseUsCtaLabel')?.value || '',
          href: document.getElementById('whyChooseUsCtaHref')?.value || '',
        },
      };
      document.getElementById('whyChooseUsJson').value = JSON.stringify(whyChooseUsData);

      // Visa Solutions
      const visaSolutionsItems = [];
      index = 0;
      while (document.getElementById(`visaSolutionsNumber_${index}`)) {
        visaSolutionsItems.push({
          number: document.getElementById(`visaSolutionsNumber_${index}`)?.value || '',
          title: document.getElementById(`visaSolutionsTitle_${index}`)?.value || '',
          description: document.getElementById(`visaSolutionsDescription_${index}`)?.value || '',
          link: document.getElementById(`visaSolutionsLink_${index}`)?.value || '',
        });
        index++;
      }

      const visaSolutionsData = {
        heading: document.getElementById('visaSolutionsHeading')?.value || '',
        subheading: document.getElementById('visaSolutionsSubheading')?.value || '',
        items: visaSolutionsItems,
      };
      document.getElementById('visaSolutionsJson').value = JSON.stringify(visaSolutionsData);

      // Visa Countries
      const visaCountriesItems = [];
      index = 0;
      while (document.getElementById(`visaCountriesName_${index}`)) {
        const visaTypesStr = document.getElementById(`visaCountriesVisaTypes_${index}`)?.value || '';
        const visaTypes = visaTypesStr.split(',').map(v => v.trim()).filter(v => v);

        visaCountriesItems.push({
          name: document.getElementById(`visaCountriesName_${index}`)?.value || '',
          code: document.getElementById(`visaCountriesCode_${index}`)?.value || '',
          flag: document.getElementById(`visaCountriesFlag_${index}`)?.value || '',
          link: document.getElementById(`visaCountriesLink_${index}`)?.value || '',
          visaTypes: visaTypes,
        });
        index++;
      }

      const visaCountriesData = {
        heading: document.getElementById('visaCountriesHeading')?.value || '',
        subheading: document.getElementById('visaCountriesSubheading')?.value || '',
        description: document.getElementById('visaCountriesDescription')?.value || '',
        countries: visaCountriesItems,
        ctaButton: {
          label: document.getElementById('visaCountriesCtaLabel')?.value || '',
          href: document.getElementById('visaCountriesCtaHref')?.value || '',
        },
      };
      document.getElementById('visaCountriesJson').value = JSON.stringify(visaCountriesData);

      // Testimonials
      const testimonialsItems = [];
      index = 0;
      while (document.getElementById(`testimonialsName_${index}`)) {
        testimonialsItems.push({
          name: document.getElementById(`testimonialsName_${index}`)?.value || '',
          role: document.getElementById(`testimonialsRole_${index}`)?.value || '',
          country: document.getElementById(`testimonialsCountry_${index}`)?.value || '',
          rating: parseInt(document.getElementById(`testimonialsRating_${index}`)?.value || 5),
          comment: document.getElementById(`testimonialsComment_${index}`)?.value || '',
          avatar: document.getElementById(`testimonialsAvatar_${index}`)?.value || '',
        });
        index++;
      }

      const testimonialsData = {
        heading: document.getElementById('testimonialsHeading')?.value || '',
        subheading: document.getElementById('testimonialsSubheading')?.value || '',
        videoUrl: document.getElementById('testimonialsVideoUrl')?.value || '',
        videoThumbnail: document.getElementById('testimonialsVideoThumbnail')?.value || '',
        items: testimonialsItems,
      };
      document.getElementById('testimonialsJson').value = JSON.stringify(testimonialsData);

      // Video Gallery
      const videoGalleryData = {
        heading: document.getElementById('videoGalleryHeading')?.value || '',
        videoUrl: document.getElementById('videoGalleryVideoUrl')?.value || '',
        thumbnail: document.getElementById('videoGalleryThumbnail')?.value || '',
      };
      document.getElementById('videoGalleryJson').value = JSON.stringify(videoGalleryData);

      // FAQ
      const faqItems = [];
      index = 0;
      while (document.getElementById(`faqQuestion_${index}`)) {
        faqItems.push({
          question: document.getElementById(`faqQuestion_${index}`)?.value || '',
          answer: document.getElementById(`faqAnswer_${index}`)?.value || '',
        });
        index++;
      }

      const faqData = {
        heading: document.getElementById('faqHeading')?.value || '',
        subheading: document.getElementById('faqSubheading')?.value || '',
        description: document.getElementById('faqDescription')?.value || '',
        ctaButton: {
          label: document.getElementById('faqCtaLabel')?.value || '',
          href: document.getElementById('faqCtaHref')?.value || '',
        },
        items: faqItems,
      };
      document.getElementById('faqJson').value = JSON.stringify(faqData);

      // Achievements
      const achievementsItems = [];
      index = 0;
      while (document.getElementById(`achievementsValue_${index}`)) {
        achievementsItems.push({
          value: document.getElementById(`achievementsValue_${index}`)?.value || '',
          suffix: document.getElementById(`achievementsSuffix_${index}`)?.value || '',
          label: document.getElementById(`achievementsLabel_${index}`)?.value || '',
          description: document.getElementById(`achievementsDescription_${index}`)?.value || '',
        });
        index++;
      }

      const achievementsData = {
        heading: document.getElementById('achievementsHeading')?.value || '',
        subheading: document.getElementById('achievementsSubheading')?.value || '',
        items: achievementsItems,
      };
      document.getElementById('achievementsJson').value = JSON.stringify(achievementsData);

      // Partners
      const visaConsultancyItems = [];
      document.querySelectorAll('.visa-consultancy-item').forEach((item) => {
        const name = item.querySelector('.visa-consultancy-name')?.value || '';
        const icon = item.querySelector('.visa-consultancy-icon')?.value || '';
        const year = item.querySelector('.visa-consultancy-year')?.value || '';
        
        if (name || icon || year) {
          visaConsultancyItems.push({ name, icon, year });
        }
      });

      const brandItems = [];
      document.querySelectorAll('.brand-item').forEach((item) => {
        const logo = item.querySelector('.brand-logo')?.value || '';
        if (logo) {
          brandItems.push({ logo });
        }
      });

      const partnersData = {
        visaConsultancy: {
          heading: document.getElementById('partnersVisaConsultancyHeading')?.value || '',
          items: visaConsultancyItems,
        },
        brands: {
          items: brandItems,
        },
      };
      
      document.getElementById('partnersJson').value = JSON.stringify(partnersData);

      // Blog Preview
      const blogPreviewItems = [];
      index = 0;
      while (document.getElementById(`blogPreviewTitle_${index}`)) {
        blogPreviewItems.push({
          title: document.getElementById(`blogPreviewTitle_${index}`)?.value || '',
          excerpt: document.getElementById(`blogPreviewExcerpt_${index}`)?.value || '',
          category: document.getElementById(`blogPreviewCategory_${index}`)?.value || '',
          date: document.getElementById(`blogPreviewDate_${index}`)?.value || '',
          author: {
            name: document.getElementById(`blogPreviewAuthorName_${index}`)?.value || '',
            avatar: document.getElementById(`blogPreviewAuthorAvatar_${index}`)?.value || '',
          },
          comments: parseInt(document.getElementById(`blogPreviewComments_${index}`)?.value || 0),
          link: document.getElementById(`blogPreviewLink_${index}`)?.value || '',
          thumbnail: document.getElementById(`blogPreviewThumbnail_${index}`)?.value || '',
        });
        index++;
      }

      const blogPreviewData = {
        heading: document.getElementById('blogPreviewHeading')?.value || '',
        subheading: document.getElementById('blogPreviewSubheading')?.value || '',
        ctaButton: {
          label: document.getElementById('blogPreviewCtaLabel')?.value || '',
          href: document.getElementById('blogPreviewCtaHref')?.value || '',
        },
        items: blogPreviewItems,
      };
      document.getElementById('blogPreviewJson').value = JSON.stringify(blogPreviewData);

      console.log('All JSON data prepared, submitting form...');
      // Submit form
      form.submit();
    } catch (error) {
      console.error('Error processing form:', error);
      alert('Error processing form. Please check console for details.');
    }
  });
});
