import React, { useEffect, useState } from 'react';
import { motion } from 'framer-motion';
import { Link } from 'react-router-dom'; // Import Link
import { Shield, Database, Network, Key, Cpu, Globe, Lock, Zap } from 'lucide-react';
import HeroSection from '../components/HeroSection';
import Section from '../components/Section';
import FeatureCard from '../components/FeatureCard';
import matter from 'gray-matter'; // Import matter

// Import images
import techBackground from '../assets/herotech.jpg'; // HERO Technology background

// Use Vite's import.meta.glob to import all tech markdown files and images
const techModules = import.meta.glob('../content/tech/*.md', { as: 'raw', eager: true });
const imageModules = import.meta.glob('../assets/*.jpg', { eager: true, import: 'default' });
const iconComponents = { Shield, Database, Network, Key, Cpu, Globe, Lock, Zap };

console.log('Tech Modules:', techModules);

const Technology = () => {
  const [technologies, setTechnologies] = useState([]);
  const [loading, setLoading] = useState(true);

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

          console.log('Loading technology:', frontmatter.title);
          console.log('IconComponent:', frontmatter.iconname, IconComponent);
          console.log('ImagePath:', imagePath, 'ImportedImage:', importedImage);

          loadedTechnologies.push({
            icon: IconComponent ? <IconComponent size={32} /> : <Shield size={32} />,
            title: frontmatter.title,
            description: frontmatter.description,
            image: importedImage,
            order: frontmatter.order || 999,
            slug: frontmatter.slug || frontmatter.title.toLowerCase().replace(/\s+/g, '-')
          });
        }

        // Sort by order
        loadedTechnologies.sort((a, b) => a.order - b.order);
        setTechnologies(loadedTechnologies);
      } catch (error) {
        console.error('Error loading technologies:', error);
        setTechnologies([]); // Ensure technologies is empty on error
        // Optionally, set an error state to display a message to the user
        // setError('Failed to load technologies. Please try again later.');
      } finally {
        setLoading(false);
      }
    };

    loadTechnologies();
  }, []);

  const comparisonData = [
    {
      feature: "Ownership",
      hero: "Fully owned and run by the individual user",
      traditional: "Owned and operated by corporations"
    },
    {
      feature: "Data Privacy",
      hero: "Encrypted, user-controlled, and geo-sovereign",
      traditional: "Stored and processed by companies, often without transparency"
    },
    {
      feature: "Communication",
      hero: "Peer-to-peer between HEROs",
      traditional: "Routed through centralized servers"
    },
    {
      feature: "AI Integration",
      hero: "You choose which AI agents to use",
      traditional: "You depend on closed AI services with unknown behavior"
    },
    {
      feature: "Memory",
      hero: "Dispersed, quantum-safe, cannot be lost",
      traditional: "Centralized, at risk of breaches or deletion"
    },
    {
      feature: "Identity & Reputation",
      hero: "Blockchain-authenticated and user-controlled",
      traditional: "Managed by third-party login or opaque identity providers"
    },
    {
      feature: "Sovereignty",
      hero: "Operates in a digital freezone under your legal control",
      traditional: "Bound to corporate policies and jurisdictions"
    },
    {
      feature: "Trust Layer",
      hero: "Verified through zero-knowledge proofs and peer links",
      traditional: "No built-in trust mechanism"
    }
  ];

  const architectureFeatures = [
    {
      title: "Distributed Memory System",
      description: "Your data is split into encrypted fragments and stored across multiple geographic locations, ensuring it can never be lost or compromised."
    },
    {
      title: "Local AI Processing",
      description: "AI computations happen on your device or trusted infrastructure, ensuring your data never leaves your control."
    },
    {
      title: "Geographic Sovereignty",
      description: "Choose where your data is stored and processed, ensuring compliance with local laws and regulations."
    },
    {
      title: "Quantum-Resistant Encryption",
      description: "Built with post-quantum cryptographic algorithms that remain secure even against quantum computer attacks."
    },
    {
      title: "Zero-Trust Security Model",
      description: "Every interaction is verified and encrypted, with no implicit trust relationships or single points of failure."
    },
    {
      title: "Interoperable Protocols",
      description: "Open standards ensure your HERO can communicate with other systems while maintaining security and privacy."
    }
  ];

  return (
    <div className="min-h-screen">
      {/* Hero Section */}
      <HeroSection
        subtitle="The Technology Behind Digital Sovereignty"
        title="HERO Technology"
        description="Built on cutting-edge cryptography, distributed systems, and blockchain technology to deliver true digital sovereignty and privacy."
        backgroundImage={techBackground}
        ctaText="See How It Works"
        ctaLink="/how"
        showVideo={false}
      />

      {/* Technical Specifications 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 }}
          >
            Core <span className="text-blue-400">Technologies</span>
          </motion.h2>
          <motion.p
            className="text-xl text-gray-300 max-w-6xl mx-auto"
            initial={{ opacity: 0, y: 20 }}
            whileInView={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.6, delay: 0.2 }}
            viewport={{ once: true }}
          >
            HERO is built on a foundation of advanced technologies that ensure your digital sovereignty, privacy, and security
          </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>
            ))
          ) : technologies.length > 0 ? (
            technologies.map((spec, index) => (
              <Link key={index} to={`/technology/${spec.slug}`} className="block">
                <FeatureCard
                  icon={spec.icon}
                  title={spec.title}
                  description={spec.description}
                  image={spec.image}
                  delay={index * 0.2}
                />
              </Link>
            ))
          ) : (
            <div className="col-span-full text-center text-gray-400 text-xl">
              Failed to load technologies. Please check the console for errors.
            </div>
          )}
        </div>
      </Section>

      {/* HERO vs Traditional Comparison */}
      <Section background="dark" 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 }}
          >
            HERO vs <span className="text-red-400">Traditional AI Platforms</span>
          </motion.h2>
          <motion.p
            className="text-xl text-gray-300 max-w-6xl mx-auto"
            initial={{ opacity: 0, y: 20 }}
            whileInView={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.6, delay: 0.2 }}
            viewport={{ once: true }}
          >
            See how HERO's Personal Agent approach compares to traditional corporate AI platforms
          </motion.p>
        </div>

        <div className="max-w-6xl mx-auto">
          <motion.div
            initial={{ opacity: 0, y: 30 }}
            whileInView={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.8 }}
            viewport={{ once: true }}
            className="glass-effect rounded-2xl overflow-hidden"
          >
            <div className="grid grid-cols-3 bg-gray-900/50 p-4 border-b border-white/10">
              <div className="text-gray-400 font-semibold">Feature</div>
              <div className="text-green-400 font-semibold text-center">HERO (Personal Agent)</div>
              <div className="text-red-400 font-semibold text-center">Traditional AI Platforms</div>
            </div>
            
            {comparisonData.map((row, index) => (
              <motion.div
                key={index}
                initial={{ opacity: 0, x: -20 }}
                whileInView={{ opacity: 1, x: 0 }}
                transition={{ duration: 0.6, delay: index * 0.1 }}
                viewport={{ once: true }}
                className="grid grid-cols-3 p-4 border-b border-white/5 hover:bg-white/5 transition-colors duration-300"
              >
                <div className="text-white font-medium">{row.feature}</div>
                <div className="text-gray-300 text-sm px-2">{row.hero}</div>
                <div className="text-gray-400 text-sm px-2">{row.traditional}</div>
              </motion.div>
            ))}
          </motion.div>
        </div>
      </Section>

      {/* Architecture Deep Dive */}
      <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 }}
          >
            Technical <span className="text-purple-400">Architecture</span>
          </motion.h2>
          <motion.p
            className="text-xl text-gray-300 max-w-6xl mx-auto"
            initial={{ opacity: 0, y: 20 }}
            whileInView={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.6, delay: 0.2 }}
            viewport={{ once: true }}
          >
            Deep dive into the technical foundations that make HERO's digital sovereignty possible
          </motion.p>
        </div>

        <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-8">
          {architectureFeatures.map((feature, index) => (
            <motion.div
              key={index}
              initial={{ opacity: 0, y: 30 }}
              whileInView={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.6, delay: index * 0.1 }}
              viewport={{ once: true }}
              className="glass-effect rounded-xl p-6 hover:border-purple-400/30 transition-all duration-300 hover-lift"
            >
              <h3 className="text-xl font-semibold text-white mb-3">{feature.title}</h3>
              <p className="text-gray-300 leading-relaxed">{feature.description}</p>
            </motion.div>
          ))}
        </div>
      </Section>

      {/* Security Standards Section */}
      <Section background="dark" padding="xlarge">
        <div className="grid lg:grid-cols-2 gap-12 items-center">
          <motion.div
            initial={{ opacity: 0, x: -30 }}
            whileInView={{ opacity: 1, x: 0 }}
            transition={{ duration: 0.8 }}
            viewport={{ once: true }}
          >
            <h2 className="text-4xl md:text-5xl font-bold text-white mb-6">
              Military-Grade <span className="text-cyan-400">Security Standards</span>
            </h2>
            <p className="text-xl text-gray-300 mb-8 leading-relaxed">
              HERO implements the highest security standards used by governments and military organizations,
              adapted for personal use to ensure your digital sovereignty.
            </p>
            
            <div className="space-y-6">
              {[
                {
                  icon: <Lock size={24} />,
                  title: "AES-256 Encryption",
                  description: "Industry-standard encryption used by governments worldwide"
                },
                {
                  icon: <Shield size={24} />,
                  title: "Post-Quantum Cryptography",
                  description: "Future-proof against quantum computing threats"
                },
                {
                  icon: <Key size={24} />,
                  title: "Zero-Knowledge Proofs",
                  description: "Verify identity without revealing personal information"
                },
                {
                  icon: <Globe size={24} />,
                  title: "Distributed Architecture",
                  description: "No single point of failure or attack"
                }
              ].map((item, index) => (
                <motion.div
                  key={index}
                  initial={{ opacity: 0, y: 20 }}
                  whileInView={{ opacity: 1, y: 0 }}
                  transition={{ duration: 0.6, delay: index * 0.1 }}
                  viewport={{ once: true }}
                  className="flex items-start space-x-4"
                >
                  <div className="text-cyan-400 mt-1">{item.icon}</div>
                  <div>
                    <h3 className="text-lg font-semibold text-white mb-1">{item.title}</h3>
                    <p className="text-gray-300">{item.description}</p>
                  </div>
                </motion.div>
              ))}
            </div>
          </motion.div>
          
          <motion.div
            initial={{ opacity: 0, x: 30 }}
            whileInView={{ opacity: 1, x: 0 }}
            transition={{ duration: 0.8 }}
            viewport={{ once: true }}
            className="relative"
          >
            <img
              src={imageModules['../assets/person.jpg']}
              alt="Security Architecture"
              className="w-full rounded-2xl shadow-2xl hover-lift"
            />
            <div className="absolute inset-0 rounded-2xl"></div>
          </motion.div>
        </div>
      </Section>
    </div>
  );
};

export default Technology;

