import React, { useEffect, useState } from 'react';
import { motion } from 'framer-motion';
import { Link } from 'react-router-dom';
import { Gavel, Wallet, ShieldCheck, Smile, BookOpen, Landmark, Scale } from 'lucide-react'; // Appropriate icons for Freezone
import HeroSection from '../components/HeroSection';
import Section from '../components/Section';
import FeatureCard from '../components/FeatureCard';
import matter from 'gray-matter';

// Import images
const freezoneBackground = new URL('../assets/inthezone.png', import.meta.url).href;

// Use Vite's import.meta.glob to import all freezone markdown files and images
const freezoneModules = import.meta.glob('../content/freezone/*.md', { as: 'raw', eager: true });
const imageModules = import.meta.glob('../assets/*.jpg', { eager: true, import: 'default' });
const iconComponents = { Gavel, Wallet, ShieldCheck, Smile, BookOpen, Landmark, Scale };

const Freezone = () => {
  const [articles, setArticles] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const loadArticles = async () => {
      try {
        const loadedArticles = [];
        
        for (const path in freezoneModules) {
          const content = freezoneModules[path];
          const { data: frontmatter } = matter(content);
          
          const IconComponent = iconComponents[frontmatter.iconname];
          const imagePath = `../assets/${frontmatter.image}`; // Construct full path
          const importedImage = imageModules[imagePath];

          loadedArticles.push({
            icon: IconComponent ? <IconComponent size={32} /> : <Gavel size={32} />, // Default icon
            title: frontmatter.title,
            description: frontmatter.description,
            image: importedImage,
            order: frontmatter.order || 999,
            slug: frontmatter.slug || frontmatter.title.toLowerCase().replace(/&/g, 'and').replace(/[^a-z0-9\s-]/g, '').replace(/\s+/g, '-').replace(/^-+|-+$/g, '')
          });
        }

        // Sort by order (if order is defined in frontmatter)
        loadedArticles.sort((a, b) => a.order - b.order);
        setArticles(loadedArticles);
      } catch (error) {
        console.error('Error loading freezone articles:', error);
      } finally {
        setLoading(false);
      }
    };

    loadArticles();
  }, []);

  return (
    <div className="min-h-screen">
      {/* Hero Section */}
      <HeroSection
        subtitle="Operate from a Digital Freezone"
        title="HERO Freezone"
        description="A secure and independent environment for your digital assets and operations, with legal dispute resolution."
        backgroundImage={freezoneBackground}
        ctaText="Learn More"
        ctaLink="/freezone" // Link to the freezone page itself, or a sub-section if applicable
        showVideo={false}
      />

      {/* Freezone Articles Section */}
      <Section background="gradient" padding="xlarge">
        <div className="text-center mb-16">
          <motion.h2
            className="text-4xl md:text-5xl font-bold text-white mb-6"
            initial={{ opacity: 0, y: 20 }}
            whileInView={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.6 }}
            viewport={{ once: true }}
          >
            Why a Digital <span className="text-green-400">Freezone?</span>
          </motion.h2>
          <motion.p
            className="text-xl text-gray-300 max-w-4xl mx-auto"
            initial={{ opacity: 0, y: 20 }}
            whileInView={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.6, delay: 0.2 }}
            viewport={{ once: true }}
          >
            Explore the core benefits of operating your HERO from a digital freezone.
          </motion.p>
        </div>

        <div className="grid md:grid-cols-2 gap-8">
          {loading ? (
            // Loading skeleton
            Array.from({ length: 4 }).map((_, index) => (
              <motion.div
                key={index}
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                transition={{ duration: 0.3, delay: index * 0.05 }}
                className="glass-effect rounded-xl p-6 animate-pulse"
              >
                <div className="h-8 w-8 bg-gray-600 rounded mb-4"></div>
                <div className="h-6 bg-gray-600 rounded mb-3"></div>
                <div className="h-4 bg-gray-600 rounded mb-4"></div>
                <div className="h-32 bg-gray-600 rounded-lg"></div>
              </motion.div>
            ))
          ) : (
            articles.map((article, index) => (
              <Link key={index} to={`/freezone/${article.slug}`} className="block">
                <FeatureCard
                  icon={article.icon}
                  title={article.title}
                  description={article.description}
                  image={article.image}
                  delay={index * 0.2}
                />
              </Link>
            ))
          )}
        </div>
      </Section>
    </div>
  );
};

export default Freezone;