
import React, { useState, useEffect, createContext, useContext, useRef, useCallback, FormEvent, MouseEvent, FC, ReactNode, RefObject, ChangeEvent } from 'react';
import ReactDOM from 'react-dom/client';
import { GoogleGenAI, Chat } from "@google/genai";
import { motion, AnimatePresence, Variants, useInView } from "framer-motion";

// ===== From types.ts =====
interface TechnologyStep {
  icon: string; 
  title: string;
  description: string;
}

interface Benefit {
  icon: string;
  title: string;
  description: string;
  progress?: {
    value: number;
    label: string;
    colorClass: string;
  };
  graph?: boolean;
}

interface NavLink {
    name: string;
    href: string;
}

interface GroundingSource {
    uri: string;
    title: string;
}
interface Message {
  id:string;
  text: string;
  sender: 'user' | 'ai';
  imagePreview?: string;
  sources?: GroundingSource[];
}

// ===== From contexts/ThemeContext.tsx =====
type Theme = 'light' | 'dark';

interface ThemeContextType {
  theme: Theme;
  setTheme: (theme: Theme) => void;
}

const getInitialTheme = (): Theme => {
    if (typeof window === 'undefined') return 'dark';
    const storedTheme = localStorage.getItem('theme') as Theme | null;
    if (storedTheme) return storedTheme;
    if (window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches) {
        return 'light';
    }
    return 'dark';
};

const ThemeContext = createContext<ThemeContextType | undefined>(undefined);

const ThemeProvider: FC<{ children: ReactNode }> = ({ children }) => {
  const [theme, setTheme] = useState<Theme>(getInitialTheme);

  useEffect(() => {
    const root = window.document.documentElement;
    localStorage.setItem('theme', theme);

    if (theme === 'dark') {
      root.classList.add('dark');
    } else {
      root.classList.remove('dark');
    }
  }, [theme]);

  return (
    <ThemeContext.Provider value={{ theme, setTheme }}>
      {children}
    </ThemeContext.Provider>
  );
};

const useTheme = () => {
  const context = useContext(ThemeContext);
  if (context === undefined) {
    throw new Error('useTheme must be used within a ThemeProvider');
  }
  return context;
};

// ===== From contexts/SectionContext.tsx =====
interface SectionContextType {
  visibleSection: string;
  setVisibleSection: (sectionId: string) => void;
}

const SectionContext = createContext<SectionContextType | undefined>(undefined);

const SectionProvider: FC<{ children: ReactNode }> = ({ children }) => {
  const [visibleSection, setVisibleSection] = useState<string>('home');

  const value = { visibleSection, setVisibleSection };

  return (
    <SectionContext.Provider value={value}>
      {children}
    </SectionContext.Provider>
  );
};

const useSection = (): SectionContextType => {
  const context = useContext(SectionContext);
  if (context === undefined) {
    throw new Error('useSection must be used within a SectionProvider');
  }
  return context;
};

// ===== NEW PageAnimationContext =====
interface PageAnimationContextType {
  isContactOpen: boolean;
  setIsContactOpen: (isOpen: boolean) => void;
}

const PageAnimationContext = createContext<PageAnimationContextType | undefined>(undefined);

const PageAnimationProvider: FC<{ children: ReactNode }> = ({ children }) => {
  const [isContactOpen, setIsContactOpen] = useState(false);
  return (
    <PageAnimationContext.Provider value={{ isContactOpen, setIsContactOpen }}>
      {children}
    </PageAnimationContext.Provider>
  );
};

const usePageAnimation = () => {
  const context = useContext(PageAnimationContext);
  if (!context) {
    throw new Error('usePageAnimation must be used within a PageAnimationProvider');
  }
  return context;
};


// ===== From hooks/useIntersectionObserver.ts =====
// This hook has been replaced by Framer Motion's `useInView` for smoother bi-directional animations.

// ===== Animation Variants =====
const sectionFadeIn: Variants = {
    hidden: { opacity: 0 },
    visible: { opacity: 1, transition: { duration: 1, ease: 'easeOut' } },
};

const sectionSlideUp: Variants = {
    hidden: { opacity: 0, y: 30 },
    visible: { opacity: 1, y: 0, transition: { duration: 0.7, ease: 'easeOut' } },
};

const popInTilt: Variants = {
    hidden: { opacity: 0, scale: 0.5, rotate: -15 },
    visible: {
        opacity: 1,
        scale: 1,
        rotate: -5,
        transition: { duration: 0.8, ease: [0.25, 0.46, 0.45, 0.94] }
    }
};

const staggeredContainer: Variants = {
    hidden: {},
    visible: { transition: { staggerChildren: 0.2, delayChildren: 0.1 } },
};

const cardScaleIn: Variants = {
    hidden: { opacity: 0, scale: 0.9 },
    visible: { opacity: 1, scale: 1, transition: { duration: 0.6, ease: 'easeOut' } },
};

// ===== From constants.tsx =====
const NAV_LINKS: NavLink[] = [
  { name: 'The Why', href: '#why' },
  { name: 'The How', href: '#technology' },
  { name: 'Benefits', href: '#benefits' },
  { name: 'Contact', href: '#contact' },
];

const TECHNOLOGY_STEPS: TechnologyStep[] = [
  {
    icon: 'fas fa-tint',
    title: 'Mist Delivery',
    description: 'Precision nutrient mist is delivered directly to plant roots at timed intervals.'
  },
  {
    icon: 'fas fa-seedling',
    title: 'Root Growth',
    description: 'Plants develop robust root systems in the oxygen-rich environment.'
  },
  {
    icon: 'fas fa-chart-line',
    title: 'Data Monitoring',
    description: 'Advanced sensors track growth metrics and optimize conditions in real-time.'
  }
];

const BENEFITS: Benefit[] = [
  {
    icon: 'fas fa-water',
    title: '95% Less Water',
    description: "Our closed-loop system recycles water, drastically reducing your environmental footprint.",
    progress: {
      value: 95,
      label: 'Water Efficiency',
      colorClass: 'bg-agri-green'
    }
  },
  {
    icon: 'fas fa-bolt',
    title: '3x Faster Growth',
    description: 'Optimized nutrient delivery accelerates plant growth, enabling more harvest cycles per year.',
     progress: {
      value: 75,
      label: 'Growth Rate',
      colorClass: 'bg-agri-blue'
    }
  },
  {
    icon: 'fas fa-microchip',
    title: 'Smart Control',
    description: 'Monitor and manage every aspect of your grow environment from anywhere with our proprietary software.',
    graph: true
  }
];

// ===== From services/geminiService.ts =====
let ai: GoogleGenAI | null = null;
try {
    if (typeof process !== 'undefined' && process.env.API_KEY) {
        ai = new GoogleGenAI({ apiKey: process.env.API_KEY });
    } else {
        console.warn("API_KEY environment variable not set. AI Assistant will not work.");
    }
} catch (error) {
    console.error("Failed to initialize GoogleGenAI:", error);
}

const SYSTEM_INSTRUCTION = "You are AgriBot, a friendly, conversational, and knowledgeable AI assistant for the AgriBlu company. Your expertise is in modern agriculture, intelligent aeroponics, sustainable farming, energy efficiency in controlled environment agriculture (CEA), and agricultural technology. Answer user questions concisely and helpfully, remembering the context of the conversation. Keep your answers to a few sentences. Do not use markdown formatting. If the user uploads an image, analyze it and incorporate your observations into the response.";

const createChat = (): Chat | null => {
    if (!ai) return null;
    return ai.chats.create({
        model: 'gemini-2.5-flash',
        config: {
          systemInstruction: SYSTEM_INSTRUCTION,
        }
    });
};

// ===== From components/ThemeToggle.tsx =====
const ThemeToggle: FC = () => {
    const { theme, setTheme } = useTheme();

    const toggleTheme = () => {
        setTheme(theme === 'light' ? 'dark' : 'light');
    };

    const iconVariants: Variants = {
        initial: { rotate: -90, opacity: 0, scale: 0.5 },
        animate: { rotate: 0, opacity: 1, scale: 1, transition: { duration: 0.3, ease: 'easeOut' } },
        exit: { rotate: 90, opacity: 0, scale: 0.5, transition: { duration: 0.3, ease: 'easeIn' } },
    };


    return (
        <button
            onClick={toggleTheme}
            className="w-10 h-10 rounded-full flex items-center justify-center transition-colors duration-300 bg-gray-200 dark:bg-gray-700 text-gray-600 dark:text-gray-300 hover:bg-gray-300 dark:hover:bg-gray-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-agri-blue dark:focus:ring-offset-agri-dark"
            aria-label={`Switch to ${theme === 'light' ? 'dark' : 'light'} mode`}
        >
            <AnimatePresence mode="wait" initial={false}>
                <motion.i
                    key={theme === 'dark' ? 'sun' : 'moon'}
                    className={`fas ${theme === 'dark' ? 'fa-sun text-yellow-400' : 'fa-moon text-indigo-400'} text-lg`}
                    variants={iconVariants}
                    initial="initial"
                    animate="animate"
                    exit="exit"
                />
            </AnimatePresence>
        </button>
    );
};

// ===== From components/Header.tsx =====
const Header: FC = () => {
  const [isScrolled, setIsScrolled] = useState(false);
  const [isMenuOpen, setIsMenuOpen] = useState(false);

  useEffect(() => {
    const handleScroll = () => {
      setIsScrolled(window.scrollY > 50);
    };
    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);
  
  const handleLinkClick = (e: MouseEvent<HTMLAnchorElement>, href: string) => {
      e.preventDefault();
      const target = document.querySelector(href);
      if (target) {
          window.scrollTo({
              top: target.getBoundingClientRect().top + window.scrollY - 80,
              behavior: 'smooth'
          });
          setIsMenuOpen(false);
      }
  };

  return (
    <header className={`fixed top-0 w-full z-50 transition-all duration-300 ${isScrolled ? 'shadow-lg bg-white/90 dark:bg-agri-dark/90 backdrop-blur-sm border-b border-gray-200 dark:border-gray-700' : 'bg-transparent border-b border-transparent'}`}>
      <nav className="container mx-auto px-6 py-3 flex justify-between items-center">
        <div className="flex items-center gap-4">
          <ThemeToggle />
          <a href="#" className="flex items-center space-x-2" onClick={(e) => handleLinkClick(e, '#home')}>
            <div className="w-10 h-10 rounded-full bg-gradient-to-br from-agri-green to-agri-blue flex items-center justify-center">
              <i className="fas fa-seedling text-white"></i>
            </div>
            <span className="font-heading text-xl font-bold text-gray-800 dark:text-white">AgriBlu</span>
          </a>
        </div>


        <div className="hidden md:flex items-center space-x-8">
          {NAV_LINKS.map(link => (
            <a key={link.name} href={link.href} onClick={(e) => handleLinkClick(e, link.href)} className="nav-link relative text-gray-700 dark:text-white hover:text-agri-green transition-colors duration-300">
              {link.name}
            </a>
          ))}
          <a href="#contact" onClick={(e) => handleLinkClick(e, "#contact")} className="bg-agri-green hover:bg-green-600 text-white font-medium py-2 px-6 rounded-full transition-colors duration-300 animate-pulse-once">
            Request a Demo
          </a>
        </div>
        
        <button className="md:hidden text-gray-800 dark:text-white focus:outline-none" onClick={() => setIsMenuOpen(!isMenuOpen)}>
          <i className={`fas ${isMenuOpen ? 'fa-times' : 'fa-bars'} text-xl`}></i>
        </button>
      </nav>

      {isMenuOpen && (
        <div className="md:hidden bg-white dark:bg-agri-dark bg-opacity-95 shadow-lg">
          <div className="px-6 py-4 space-y-3">
            {NAV_LINKS.map(link => (
              <a key={link.name} href={link.href} onClick={(e) => handleLinkClick(e, link.href)} className="block text-gray-700 dark:text-white hover:text-agri-green py-2">{link.name}</a>
            ))}
            <a href="#contact" onClick={(e) => handleLinkClick(e, "#contact")} className="bg-agri-green hover:bg-green-600 text-white font-medium py-2 px-6 rounded-full w-full text-center transition-colors duration-300 animate-pulse-once">
              Request a Demo
            </a>
          </div>
        </div>
      )}
    </header>
  );
};

// ===== From components/Hero.tsx =====
const Hero: FC = () => {
    const canvasRef = useRef<HTMLCanvasElement>(null);
    const { theme } = useTheme();
    const { setVisibleSection } = useSection();
    const sectionRef = useRef<HTMLDivElement>(null);
    const isVisible = useInView(sectionRef, { amount: 0.5 });
    const [showScrollIndicator, setShowScrollIndicator] = useState(true);

    useEffect(() => {
        if (isVisible) {
            setVisibleSection('home');
        }
    }, [isVisible, setVisibleSection]);

    useEffect(() => {
        const handleScroll = () => {
            setShowScrollIndicator(window.scrollY < 50);
        };
        window.addEventListener('scroll', handleScroll, { passive: true });
        return () => window.removeEventListener('scroll', handleScroll);
    }, []);

    useEffect(() => {
        const canvas = canvasRef.current;
        if (!canvas) return;
        const ctx = canvas.getContext('2d');
        if (!ctx) return;

        let animationFrameId: number;
        let lines: {
            x: number;
            y: number;
            length: number;
            width: number;
            speed: number;
            color: string;
        }[] = [];

        const resizeCanvas = () => {
            if (!canvas) return;
            canvas.width = document.documentElement.clientWidth;
            canvas.height = document.documentElement.clientHeight;
            lines = []; 
            initializeLines();
        };

        const initializeLines = () => {
            if (!canvas) return;
            const isMobile = window.innerWidth < 768;
            const lineCount = isMobile ? 75 : 150;
            const colors = theme === 'dark' 
                ? ['rgba(76, 175, 80, 0.7)', 'rgba(0, 188, 212, 0.7)']
                : ['rgba(76, 175, 80, 0.6)', 'rgba(0, 188, 212, 0.6)'];

            for (let i = 0; i < lineCount; i++) {
                const direction = Math.random() > 0.5 ? 1 : -1;
                lines.push({
                    x: Math.random() * canvas.width,
                    y: Math.random() * canvas.height,
                    length: 30 + Math.random() * 80,
                    width: 1 + Math.random() * 2,
                    speed: (0.2 + Math.random() * 0.3) * direction,
                    color: Math.random() > 0.5 ? colors[0] : colors[1],
                });
            }
        };

        const draw = () => {
            if (!ctx || !canvas) return;
            ctx.clearRect(0, 0, canvas.width, canvas.height);

            lines.forEach(line => {
                ctx.beginPath();
                ctx.lineWidth = line.width;
                ctx.strokeStyle = line.color;
                
                ctx.moveTo(line.x, line.y);
                ctx.lineTo(line.x, line.y - line.length);
                ctx.stroke();

                line.x += line.speed;

                if (line.speed > 0 && line.x > canvas.width + 50) {
                    line.x = -50;
                    line.y = Math.random() * canvas.height;
                } else if (line.speed < 0 && line.x < -50) {
                    line.x = canvas.width + 50;
                    line.y = Math.random() * canvas.height;
                }
            });

            animationFrameId = window.requestAnimationFrame(draw);
        };

        resizeCanvas();
        window.addEventListener('resize', resizeCanvas);
        
        draw();

        return () => {
            window.cancelAnimationFrame(animationFrameId);
            window.removeEventListener('resize', resizeCanvas);
        };
    }, [theme]);


    const handleLinkClick = (e: MouseEvent<HTMLAnchorElement>, href: string) => {
        e.preventDefault();
        const target = document.querySelector(href);
        if (target) {
            window.scrollTo({
                top: target.getBoundingClientRect().top + window.scrollY - 80,
                behavior: 'smooth'
            });
        }
    };

    return (
        <section id="home" ref={sectionRef} className="relative min-h-screen flex items-center justify-center pt-16">
            <canvas ref={canvasRef} className="absolute inset-0 z-0 pointer-events-none canvas-animated"></canvas>
            <motion.div 
                className="container mx-auto px-6 text-center relative z-10"
                initial="hidden"
                animate="visible"
                variants={staggeredContainer}
            >
                <motion.h1 variants={sectionSlideUp} className="font-heading text-4xl md:text-6xl font-bold mb-6 text-gray-900 dark:text-white">
                    AgriBlu: "Growing for you"
                </motion.h1>
                <motion.p variants={sectionSlideUp} className="font-body text-lg md:text-xl max-w-3xl mx-auto mb-4 text-gray-600 dark:text-gray-300">
                    The future of indoor CEA farming is here!
                </motion.p>
                <motion.p variants={sectionSlideUp} className="font-body text-lg md:text-xl max-w-3xl mx-auto mb-10 text-gray-600 dark:text-gray-300">
                    Indoor farming rebooted with unparalleled levels of efficiency.
                </motion.p>
                <motion.div variants={sectionSlideUp} className="flex flex-col sm:flex-row justify-center gap-6">
                    <a href="#contact" onClick={(e) => handleLinkClick(e, '#contact')} className="bg-green-500 hover:bg-green-600 text-white font-bold py-4 px-10 rounded-full transition-all duration-300 transform hover:scale-105">
                        Get Started
                    </a>
                    <a href="#technology" onClick={(e) => handleLinkClick(e, '#technology')} className="bg-gray-100 hover:bg-gray-200 dark:bg-gray-800 dark:hover:bg-gray-700 border border-gray-300 dark:border-gray-600 text-gray-800 dark:text-white font-bold py-4 px-10 rounded-full transition-all duration-300 transform hover:scale-105">
                        Learn More
                    </a>
                </motion.div>
            </motion.div>
            <AnimatePresence>
                {showScrollIndicator && (
                    <motion.a
                        href="#why"
                        onClick={(e) => handleLinkClick(e, '#why')}
                        className="absolute bottom-10 left-1/2 -translate-x-1/2 z-20 cursor-pointer"
                        initial={{ opacity: 0, y: 20 }}
                        animate={{ opacity: 1, y: 0, transition: { delay: 1.5, duration: 0.5 } }}
                        exit={{ opacity: 0, y: -20, transition: { duration: 0.3 } }}
                        aria-label="Scroll to next section"
                    >
                         <svg width="40" height="100" viewBox="0 0 40 100" className="overflow-visible">
                            <motion.path
                                d="M 20 0 C 20 20, 10 30, 20 80"
                                className="stroke-agri-green"
                                strokeWidth="3"
                                strokeLinecap="round"
                                fill="transparent"
                                initial={{ pathLength: 0, opacity: 0 }}
                                animate={{
                                    pathLength: [0, 1, 1, 1],
                                    opacity: [0, 1, 1, 0],
                                }}
                                transition={{
                                    duration: 2.5,
                                    repeat: Infinity,
                                    ease: "easeInOut",
                                    times: [0, 0.6, 0.9, 1],
                                }}
                            />
                            <motion.g
                                initial={{ opacity: 0 }}
                                animate={{
                                    opacity: [0, 0, 1, 1, 0],
                                    y: [0, 0, 5, 0, 0],
                                }}
                                transition={{
                                    duration: 2.5,
                                    repeat: Infinity,
                                    ease: "easeInOut",
                                    times: [0, 0.6, 0.75, 0.9, 1] 
                                }}
                            >
                                <path d="M 15 82 L 20 89 L 25 82" className="stroke-agri-green" strokeWidth="3" strokeLinecap="round" fill="transparent" />
                            </motion.g>
                        </svg>
                    </motion.a>
                )}
            </AnimatePresence>
        </section>
    );
};

// ===== From components/About.tsx (Reverted) =====
const Why: FC = () => {
    const { theme } = useTheme();
    const [energyState, setEnergyState] = useState<'before' | 'after'>('before');
    const [showSavingsBox, setShowSavingsBox] = useState(false);
    
    const sectionRef = useRef<HTMLDivElement>(null);
    const isInView = useInView(sectionRef, { once: false, amount: 0.1, margin: '-80px' });

    const { setVisibleSection } = useSection();
    const canvasRef = useRef<HTMLCanvasElement>(null);
    
    useEffect(() => {
        if (isInView) {
            setVisibleSection('why');
        }
    }, [isInView, setVisibleSection]);

    useEffect(() => {
        if (isInView) {
            const timer1 = setTimeout(() => setEnergyState('after'), 500);
            const timer2 = setTimeout(() => setShowSavingsBox(true), 1500);
            return () => {
                clearTimeout(timer1);
                clearTimeout(timer2);
            };
        } else {
            setEnergyState('before');
            setShowSavingsBox(false);
        }
    }, [isInView]);

    useEffect(() => {
        const canvas = canvasRef.current;
        const section = sectionRef.current;
        if (!canvas || !section) return;
        const ctx = canvas.getContext('2d');
        if (!ctx) return;

        let animationFrameId: number;

        interface StreakParticle { x: number; y: number; speed: number; length: number; opacity: number; color: string; }
        interface DotParticle { x: number; y: number; speed: number; radius: number; opacity: number; color: string; initialY: number; angle: number; }

        let streaks: StreakParticle[] = [];
        let dots: DotParticle[] = [];

        const initializeParticles = () => {
            if (!canvas) return;
            const isMobile = window.innerWidth < 768;
            streaks = [];
            dots = [];
            const streakCount = isMobile ? 30 : 75;
            const dotCount = isMobile ? 40 : 100;
            const streakColors = theme === 'dark' 
                ? ['rgba(34, 197, 94, 1)', 'rgba(0, 188, 212, 1)']
                : ['rgba(34, 197, 94, 0.9)', 'rgba(0, 188, 212, 0.9)'];
            const dotColors = theme === 'dark'
                ? ['rgba(34, 197, 94, 0.9)', 'rgba(0, 188, 212, 0.9)']
                : ['rgba(34, 197, 94, 0.8)', 'rgba(0, 188, 212, 0.8)'];

            for (let i = 0; i < streakCount; i++) {
                streaks.push({
                    x: Math.random() * canvas.width, y: Math.random() * canvas.height, speed: 0.5 + Math.random() * 1.5,
                    length: 15 + Math.random() * 25, opacity: 0.5 + Math.random() * 0.4, color: Math.random() > 0.4 ? streakColors[0] : streakColors[1],
                });
            }
            
            for (let i = 0; i < dotCount; i++) {
                const y = Math.random() * canvas.height;
                dots.push({
                    x: Math.random() * canvas.width, y: y, initialY: y, angle: Math.random() * Math.PI * 2, speed: 0.3 + Math.random() * 0.8,
                    radius: 0.5 + Math.random() * 1.5, opacity: 0.5 + Math.random() * 0.4, color: Math.random() > 0.4 ? dotColors[0] : dotColors[1],
                });
            }
        };

        const draw = () => {
            if (!ctx || !canvas) return;
            const bgColor = theme === 'dark' ? 'rgba(17, 24, 39, 0.1)' : 'rgba(209, 213, 219, 0.1)';
            ctx.fillStyle = bgColor;
            ctx.fillRect(0, 0, canvas.width, canvas.height);

            streaks.forEach(p => {
                p.x += p.speed;
                if (p.x > canvas.width) { p.x = 0; p.y = Math.random() * canvas.height; }
                const gradient = ctx.createLinearGradient(p.x - p.length, p.y, p.x, p.y);
                const baseColor = p.color.substring(p.color.indexOf('(') + 1, p.color.lastIndexOf(','));
                gradient.addColorStop(0, `rgba(${baseColor}, 0)`);
                gradient.addColorStop(1, `rgba(${baseColor}, ${p.opacity})`);
                ctx.strokeStyle = gradient; ctx.lineWidth = 1.5; ctx.beginPath(); ctx.moveTo(p.x - p.length, p.y); ctx.lineTo(p.x, p.y); ctx.stroke();
            });
            
            dots.forEach(p => {
                p.angle += 0.02; p.x += p.speed; p.y = p.initialY + Math.sin(p.angle + p.x / 50) * 20;
                if (p.x > canvas.width) { p.x = 0; p.y = Math.random() * canvas.height; p.initialY = p.y; }
                const baseColor = p.color.substring(p.color.indexOf('(') + 1, p.color.lastIndexOf(','));
                ctx.fillStyle = `rgba(${baseColor}, ${p.opacity})`;
                ctx.beginPath(); ctx.arc(p.x, p.y, p.radius, 0, Math.PI * 2, false); ctx.fill();
            });

            animationFrameId = window.requestAnimationFrame(draw);
        };
        
        const resizeObserver = new ResizeObserver(entries => {
            window.requestAnimationFrame(() => {
                if (!Array.isArray(entries) || !entries.length) return;
                for (let entry of entries) {
                    if(canvas) {
                        canvas.width = entry.contentRect.width; 
                        canvas.height = entry.contentRect.height; 
                        initializeParticles();
                    }
                }
            });
        });
        
        if(section) {
            resizeObserver.observe(section);
        }
        draw();

        return () => {
            window.cancelAnimationFrame(animationFrameId);
            resizeObserver.disconnect();
        };
    }, [theme, sectionRef]);

    const energyMeterWidth = energyState === 'before' ? '100%' : '50%';
    const energyMeterBg = energyState === 'before' ? 'linear-gradient(90deg, #ef4444, #dc2626)' : 'linear-gradient(90deg, #22c55e, #16a34a)';

    return (
        <section id="why" ref={sectionRef} className="py-20 bg-gray-300 dark:bg-gray-900 relative gradient-blend-top from-dark-to-gray overflow-x-hidden">
             <canvas ref={canvasRef} className="absolute inset-0 z-0 pointer-events-none opacity-50 dark:opacity-40 canvas-animated"></canvas>
            <div className="container mx-auto px-6 relative z-10">
                <motion.h2 variants={sectionFadeIn} initial="hidden" animate={isInView ? "visible" : "hidden"} className="font-heading text-3xl md:text-4xl font-bold text-center mb-16 text-gray-900 dark:text-white">
                    The Why: Vertical Farming's Energy Problem
                </motion.h2>
                
                <div className="max-w-4xl mx-auto">
                    <motion.div variants={sectionSlideUp} initial="hidden" animate={isInView ? "visible" : "hidden"} className="bg-white dark:bg-agri-dark rounded-xl p-8 border-l-4 border-agri-green shadow-lg">
                        <p className="font-body text-lg mb-6 leading-relaxed text-gray-700 dark:text-gray-300">
                            Indoor and vertical farming have struggled financially over the past two years, primarily because of high energy costs. These expenses make it difficult for farms to become profitable.
                        </p>
                        <p className="font-body text-lg leading-relaxed text-gray-700 dark:text-gray-300">
                            Having been involved in the indoor growing industry since its commercial beginnings in 2014, we've developed a unique approach that slashes energy consumption by up to 50%. Our solution addresses the core issue preventing many of these operations from succeeding.
                        </p>
                    </motion.div>
                    
                    <motion.div variants={sectionFadeIn} initial="hidden" animate={isInView ? "visible" : "hidden"} transition={{ delay: 0.3 }} className="mt-12 bg-white dark:bg-agri-dark rounded-xl p-8 shadow-lg border border-gray-200 dark:border-gray-700 relative">
                        <h3 className="font-heading text-2xl font-bold text-center mb-4 text-gray-900 dark:text-white">
                            Energy Consumption Reduction
                        </h3>
                        
                        <div className="flex justify-between items-center mb-4 text-gray-500 dark:text-gray-400">
                            <span className="text-lg font-semibold">After AgriBlu</span>
                            <span className="text-lg font-semibold">Before AgriBlu</span>
                        </div>
                        
                        <div className="relative h-12 bg-gray-400 dark:bg-gray-700 rounded-full overflow-hidden">
                            <div style={{ width: energyMeterWidth, background: energyMeterBg }} className="absolute top-0 left-0 h-full rounded-full transition-all duration-1000 ease-in-out"></div>
                            <div className="absolute inset-0 flex items-center justify-between px-4">
                                <span className={`text-white font-bold text-lg z-10 transition-opacity duration-500 ${energyState === 'after' ? 'opacity-100' : 'opacity-0'}`}>50%</span>
                                <span className={`text-white font-bold text-lg z-10 transition-opacity duration-500 ${energyState === 'before' ? 'opacity-100' : 'opacity-0'}`}>100%</span>
                            </div>
                        </div>

                        <div className="mt-12 flex justify-center items-start gap-12 md:gap-16">
                            <button
                                onClick={() => setEnergyState('before')}
                                className={`w-32 h-32 flex flex-col items-center justify-center pt-4 rounded-full transition-all duration-300 group focus:outline-none focus:ring-4 focus:ring-offset-2 ${energyState === 'before' ? 'bg-red-500 text-white shadow-lg scale-105 focus:ring-red-300' : 'bg-gray-100 dark:bg-gray-800 text-gray-500 dark:text-gray-400 hover:bg-red-500/10 dark:hover:bg-red-900/50 hover:text-red-500 dark:hover:text-white focus:ring-gray-400'}`}
                                aria-pressed={energyState === 'before'}
                            >
                                <i className="fas fa-bolt text-4xl"></i>
                                <div className="w-full h-10 mt-1 pointer-events-none">
                                    <svg viewBox="0 0 100 30" className="w-full h-full">
                                        <path id="curveBefore" d="M 10,20 C 30,5 70,5 90,20" fill="transparent"/>
                                        <text className="text-sm font-medium fill-current" >
                                            <textPath href="#curveBefore" startOffset="50%" textAnchor="middle">Traditional</textPath>
                                        </text>
                                    </svg>
                                </div>
                            </button>
                            
                            <button
                                onClick={() => setEnergyState('after')}
                                className={`w-32 h-32 flex flex-col items-center justify-center pt-4 rounded-full transition-all duration-300 group focus:outline-none focus:ring-4 focus:ring-offset-2 ${energyState === 'after' ? 'bg-agri-green text-white shadow-lg scale-105 focus:ring-green-300' : 'bg-gray-100 dark:bg-gray-800 text-gray-500 dark:text-gray-400 hover:bg-green-500/10 dark:hover:bg-green-900/50 hover:text-green-500 dark:hover:text-white focus:ring-gray-400'}`}
                                aria-pressed={energyState === 'after'}
                            >
                                <i className="fas fa-leaf text-4xl"></i>
                                <div className="w-full h-10 mt-1 pointer-events-none">
                                    <svg viewBox="0 0 100 30" className="w-full h-full">
                                        <path id="curveAfter" d="M 10,20 C 30,5 70,5 90,20" fill="transparent"/>
                                        <text className="text-sm font-medium fill-current">
                                            <textPath href="#curveAfter" startOffset="50%" textAnchor="middle">AgriBlu</textPath>
                                        </text>
                                    </svg>
                                </div>
                            </button>
                        </div>

                        <AnimatePresence>
                        {showSavingsBox && (
                             <motion.div 
                                variants={popInTilt}
                                initial="hidden"
                                animate="visible"
                                exit="hidden"
                                className="absolute -bottom-8 -right-8 md:-bottom-10 md:-right-10 bg-gradient-to-br from-green-400 to-agri-green text-white p-4 rounded-lg shadow-2xl"
                            >
                                <span className="block font-heading text-4xl font-bold">50%</span>
                                <span className="block font-body text-md">Energy Savings</span>
                            </motion.div>
                        )}
                        </AnimatePresence>
                        
                    </motion.div>
                </div>
            </div>
        </section>
    );
};

// ===== NEW DETAILED PLANT COMPONENT =====
const Plant: FC<{ x: number; y: number; scale: number; baseDelay: number; }> = ({ x, y, scale, baseDelay }) => {
    // A set of layered paths to create a detailed lettuce/cabbage head.
    // Ordered from back to front to ensure correct stacking.
    const leaves = [
        { d: "M-20 -15 C-50 -35 -45 -65 0 -75 C45 -65 50 -35 20 -15 Z", fill: "#388E3C" }, // Back-most, darkest leaf layer
        { d: "M-25 -20 C-45 -40 -50 -70 -10 -80 C30 -75 45 -45 25 -20 Z", fill: "#43A047" },
        { d: "M15 -15 C40 -35 35 -65 5 -75 C-30 -65 -35 -35 -15 -15 Z", fill: "#4CAF50" },
        { d: "M-15 -10 C-35 -25 -30 -55 0 -65 C30 -55 35 -25 15 -10 Z", fill: "#66BB6A" },
        { d: "M-10 -5 C-25 -20 -15 -45 0 -50 C15 -45 25 -20 10 -5 Z", fill: "#81C784" },   // Front-most leaf layer
        { d: "M0 -5 C-10 -15 -5 -30 0 -35 C5 -30 10 -15 0 -5 Z", fill: "#A5D6A7" }      // Core, lightest leaf
    ];

    return (
        <g transform={`translate(${x}, ${y}) scale(${scale})`}>
            {leaves.map((leaf, index) => (
                <path
                    key={index}
                    className="plant-leaf"
                    style={{ transitionDelay: `${baseDelay + index * 0.1}s` }}
                    d={leaf.d}
                    fill={leaf.fill}
                />
            ))}
        </g>
    );
};


// ===== From components/Features.tsx (Reverted) =====
const Technology: FC = () => {
    const { theme } = useTheme();
    const sectionRef = useRef<HTMLDivElement>(null);
    const isInView = useInView(sectionRef, { once: false, amount: 0.1, margin: '-80px' });
    const { setVisibleSection } = useSection();
    const canvasRef = useRef<HTMLCanvasElement>(null);

    useEffect(() => {
        if (isInView) {
            setVisibleSection('technology');
        }
    }, [isInView, setVisibleSection]);

     useEffect(() => {
        const canvas = canvasRef.current;
        const section = sectionRef.current;
        if (!canvas || !section) return;
        const ctx = canvas.getContext('2d');
        if (!ctx) return;

        let animationFrameId: number;
        let particles: { x: number; y: number; radius: number; color: string; speedY: number; }[] = [];

        const initializeParticles = () => {
             if (!canvas) return;
            const isMobile = window.innerWidth < 768;
            particles = [];
            const particleCount = isMobile ? 50 : 120;
            const colors = theme === 'dark' 
                ? ['rgba(0, 188, 212, 0.7)', 'rgba(255, 255, 255, 0.7)']
                : ['rgba(0, 188, 212, 0.8)', 'rgba(76, 175, 80, 0.8)'];

            for (let i = 0; i < particleCount; i++) {
                particles.push({
                    x: Math.random() * canvas.width, y: Math.random() * canvas.height, radius: 1 + Math.random() * 2,
                    color: Math.random() > 0.3 ? colors[0] : colors[1],
                    speedY: 0.2 + Math.random() * 0.5,
                });
            }
        };

        const draw = () => {
            if (!ctx || !canvas) return;
            ctx.clearRect(0, 0, canvas.width, canvas.height);

            particles.forEach(p => {
                ctx.beginPath(); ctx.arc(p.x, p.y, p.radius, 0, Math.PI * 2, false); ctx.fillStyle = p.color; ctx.fill();
                p.y += p.speedY;
                if (p.y > canvas.height) { p.y = 0 - p.radius; p.x = Math.random() * canvas.width; }
            });

            animationFrameId = window.requestAnimationFrame(draw);
        };

        const resizeObserver = new ResizeObserver(entries => {
            window.requestAnimationFrame(() => {
                if (!Array.isArray(entries) || !entries.length) return;
                for (let entry of entries) { 
                    if (canvas) {
                        canvas.width = entry.contentRect.width; 
                        canvas.height = entry.contentRect.height; 
                        initializeParticles(); 
                    }
                }
            });
        });
        
        if (section) {
            resizeObserver.observe(section);
        }
        draw();

        return () => {
            window.cancelAnimationFrame(animationFrameId);
            resizeObserver.disconnect();
        };
    }, [sectionRef, theme]);

    const rootSystems = [
        { main: "M 40,0 C 42,5 38,15 40,30 C 38,45 45,60 42,80", delay: 0.5, w: 1.5, branches: [
            { d: "M 39,20 c -5,5 -5,10 0,15", w: 0.8, delay: 0.2 },
            { d: "M 41,50 c 5,5 5,10 -2,15", w: 0.8, delay: 0.4 },
        ]},
        { main: "M 55,0 C 50,10 60,20 55,40 C 60,55 53,70 58,85", delay: 0.7, w: 1.5, branches: [
            { d: "M 56,30 c 6,8 3,15 -3,20", w: 0.8, delay: 0.3 },
        ]},
        { main: "M 75,0 C 80,15 70,25 75,50 C 70,65 77,75 75,90", delay: 0.6, w: 2, branches: [
            { d: "M 74,35 c -8,5 -10,15 -3,25", w: 1, delay: 0.2 },
            { d: "M 76,70 c 5,5 2,12 8,15", w: 1, delay: 0.5 },
        ]},
        { main: "M 95,0 C 90,5 100,20 95,45 C 100,60 92,80 98,95", delay: 0.9, w: 1.5, branches: [
            { d: "M 96,60 c 5,10 -5,15 -2,25", w: 0.8, delay: 0.4 },
        ]},
        { main: "M 115,0 C 120,10 110,30 115,50 C 110,65 118,80 115,92", delay: 0.8, w: 2, branches: [
            { d: "M 114,20 c -6,8 -3,15 3,20", w: 1, delay: 0.3 },
            { d: "M 116,55 c 5,5 5,12 0,20", w: 1, delay: 0.5 },
        ]},
        { main: "M 135,0 C 130,15 140,25 135,45 C 140,60 132,75 138,88", delay: 1.0, w: 1.5, branches: [] },
        { main: "M 155,0 C 160,5 150,20 155,40 C 150,60 158,70 155,85", delay: 1.1, w: 1.5, branches: [
             { d: "M 154,45 c -5,5 -2,12 3,18", w: 0.8, delay: 0.4 },
        ]},
    ];

    const nozzles = [ { x: 35 }, { x: 75 }, { x: 115 }, { x: 155 } ];

    const mistParticles = Array.from({length: 40}, (_, i) => {
        const nozzleIndex = i % 4;
        const startX = nozzles[nozzleIndex].x + (Math.random() - 0.5) * 5;
        return {
            startX: startX,
            delay: Math.random() * 2,
            duration: 2 + Math.random() * 2,
            endY: 100 + Math.random() * 40,
            sway: startX + (Math.random() - 0.5) * 20,
        }
    });

    const plantsData = [
        { x: 55, scale: 0.5, baseDelay: 0.8 },
        { x: 100, scale: 0.6, baseDelay: 1.0 },
        { x: 145, scale: 0.55, baseDelay: 1.2 }
    ];

    return (
        <section id="technology" ref={sectionRef} className="py-20 bg-white dark:bg-agri-dark relative gradient-blend-top from-gray-to-dark">
            <canvas ref={canvasRef} className="absolute inset-0 z-0 pointer-events-none opacity-60 dark:opacity-70 canvas-animated"></canvas>
            <div className="container mx-auto px-6 relative z-10">
                <motion.h2 variants={sectionFadeIn} initial="hidden" animate={isInView ? "visible" : "hidden"} className="font-heading text-3xl md:text-4xl font-bold text-center mb-16 text-gray-900 dark:text-white">
                    How It Works
                </motion.h2>
                
                <div className="flex flex-col lg:flex-row lg:items-center justify-between gap-16">
                    <motion.div 
                        className="w-full lg:w-1/2 grid grid-cols-1 gap-8"
                        variants={staggeredContainer}
                        initial="hidden"
                        animate={isInView ? "visible" : "hidden"}
                    >
                        {TECHNOLOGY_STEPS.map((step, index) => (
                            <motion.div key={index} variants={sectionSlideUp} className="flex items-start gap-4">
                                <div className="w-16 h-16 bg-agri-blue/10 dark:bg-agri-blue/20 rounded-full flex items-center justify-center flex-shrink-0 mt-1 transition-transform duration-300 hover:scale-110">
                                    <i className={`${step.icon} text-2xl ${step.icon.includes('tint') ? 'text-agri-blue' : 'text-agri-green'}`}></i>
                                 </div>
                                <div className="text-left">
                                    <h3 className="font-heading text-xl font-semibold mb-2 text-gray-800 dark:text-white">{step.title}</h3>
                                    <p className="text-gray-600 dark:text-gray-400">{step.description}</p>
                                </div>
                            </motion.div>
                        ))}
                    </motion.div>
                    
                    <motion.div 
                        className="w-full lg:w-1/2 flex justify-center items-center min-h-[400px]"
                        variants={sectionFadeIn}
                        initial="hidden"
                        animate={isInView ? "visible" : "hidden"}
                        transition={{ delay: 0.5 }}
                    >
                        <svg width="350" height="400" viewBox="0 -80 200 280" className={`plant-animation-container ${isInView ? 'is-visible' : ''}`}>
                             <defs>
                                <linearGradient id="rootGradient" x1="0%" y1="0%" x2="0%" y2="100%">
                                    <stop offset="0%" stopColor="#D2B48C" />
                                    <stop offset="100%" stopColor="#A0522D" />
                                </linearGradient>
                            </defs>
                            
                            <g className="aeroponics-part" style={{ transitionDelay: '0s' }}>
                                <rect x="10" y="100" width="180" height="120" rx="5" className="fill-gray-200/50 dark:fill-gray-700/50 stroke-gray-300 dark:stroke-gray-600 stroke-1" />
                            </g>

                            <g className="aeroponics-part" style={{ transitionDelay: '0.2s' }}>
                                <rect x="20" y="80" width="160" height="20" rx="3" className="fill-gray-400 dark:fill-gray-600"/>
                            </g>
                            
                            {plantsData.map((plant, pIndex) => (
                               <Plant
                                    key={pIndex}
                                    x={plant.x}
                                    y={80}
                                    scale={plant.scale}
                                    baseDelay={plant.baseDelay}
                                />
                            ))}
                           
                            <g transform="translate(0, 100)">
                                {rootSystems.map((system, i) => (
                                    <g key={i}>
                                        <path 
                                            className="root-path"
                                            d={system.main}
                                            stroke="url(#rootGradient)"
                                            strokeWidth={system.w}
                                            fill="none"
                                            strokeLinecap="round"
                                            style={{ transitionDelay: `${system.delay}s` }}
                                        />
                                        {system.branches.map((branch, j) => (
                                            <path 
                                                key={j}
                                                className="root-path"
                                                d={branch.d}
                                                stroke="url(#rootGradient)"
                                                strokeWidth={branch.w}
                                                fill="none"
                                                strokeLinecap="round"
                                                style={{ transitionDelay: `${system.delay + branch.delay}s` }}
                                            />
                                        ))}
                                    </g>
                                ))}
                            </g>

                            <g transform="translate(0, 215)">
                                {nozzles.map((nozzle, i) => (
                                    <rect key={i} x={nozzle.x - 5} y="0" width="10" height="5" rx="2" className="fill-gray-500 dark:fill-gray-400 aeroponics-part" style={{transitionDelay: `${1.5 + i * 0.1}s`}}/>
                                ))}
                            </g>
                            
                            <g className="mist-group">
                                {mistParticles.map((p, i) => (
                                    <circle key={i} cx={p.startX} cy="215" r="1.5" fill="#00BCD4" fillOpacity="0.7">
                                        <animate attributeName="cy" from="215" to={p.endY} dur={`${p.duration}s`} begin={`${p.delay}s`} repeatCount="indefinite" />
                                        <animate attributeName="cx" values={`${p.startX}; ${p.sway}; ${p.startX}`} dur={`${p.duration}s`} begin={`${p.delay}s`} repeatCount="indefinite" />
                                        <animate attributeName="r" from="1.5" to="3" dur={`${p.duration}s`} begin={`${p.delay}s`} repeatCount="indefinite" />
                                        <animate attributeName="fill-opacity" from="0.7" to="0" dur={`${p.duration}s`} begin={`${p.delay}s`} repeatCount="indefinite" />
                                    </circle>
                                ))}
                            </g>
                        </svg>
                    </motion.div>
                </div>
            </div>
        </section>
    );
};


// ===== From components/Testimonials.tsx =====
const Benefits: FC = () => {
    const { theme } = useTheme();
    const sectionRef = useRef<HTMLDivElement>(null);
    const isInView = useInView(sectionRef, { once: false, amount: 0.1, margin: '-80px' });
    const { setVisibleSection } = useSection();
    const canvasRef = useRef<HTMLCanvasElement>(null);
    const { isContactOpen } = usePageAnimation();

     useEffect(() => {
        if (isInView) {
            setVisibleSection('benefits');
        }
    }, [isInView, setVisibleSection]);

    useEffect(() => {
        const canvas = canvasRef.current;
        const section = sectionRef.current;
        if (!canvas || !section) return;
        const ctx = canvas.getContext('2d');
        if (!ctx) return;

        let animationFrameId: number;
        let nodes: { x: number; y: number; vx: number; vy: number; radius: number; }[] = [];
        
        const initializeNodes = () => {
            if (!canvas) return;
            const isMobile = window.innerWidth < 768;
            nodes = [];
            const nodeCount = isMobile ? 30 : 80;
            for (let i = 0; i < nodeCount; i++) {
                nodes.push({
                    x: Math.random() * canvas.width, y: Math.random() * canvas.height,
                    vx: (Math.random() - 0.5) * 0.4, vy: (Math.random() - 0.5) * 0.4,
                    radius: 1.5,
                });
            }
        };

        const draw = () => {
            if (!ctx || !canvas) return;
            ctx.clearRect(0, 0, canvas.width, canvas.height);

            const lineColor = theme === 'dark' ? 'rgba(76, 175, 80, 0.6)' : 'rgba(76, 175, 80, 0.8)';
            ctx.strokeStyle = lineColor;
            ctx.lineWidth = 0.5;
            for (let i = 0; i < nodes.length; i++) {
                for (let j = i + 1; j < nodes.length; j++) {
                    const dist = Math.sqrt((nodes[i].x - nodes[j].x) ** 2 + (nodes[i].y - nodes[j].y) ** 2);
                    if (dist < 100) {
                        ctx.beginPath(); ctx.moveTo(nodes[i].x, nodes[i].y); ctx.lineTo(nodes[j].x, nodes[j].y); ctx.stroke();
                    }
                }
            }

            const nodeColor = theme === 'dark' ? 'rgba(76, 175, 80, 0.9)' : 'rgba(76, 175, 80, 1.0)';
            ctx.fillStyle = nodeColor;
            nodes.forEach(node => {
                ctx.beginPath(); ctx.arc(node.x, node.y, node.radius, 0, Math.PI * 2); ctx.fill();
                node.x += node.vx; node.y += node.vy;
                if (node.x < 0 || node.x > canvas.width) node.vx *= -1;
                if (node.y < 0 || node.y > canvas.height) node.vy *= -1;
            });

            animationFrameId = requestAnimationFrame(draw);
        };

        const resizeObserver = new ResizeObserver(entries => {
            window.requestAnimationFrame(() => {
                if (!Array.isArray(entries) || !entries.length) return;
                for (let entry of entries) { 
                    if (canvas) {
                        canvas.width = entry.contentRect.width; 
                        canvas.height = entry.contentRect.height; 
                        initializeNodes(); 
                    }
                }
            });
        });
        
        if (section) {
            resizeObserver.observe(section);
        }
        draw();
        return () => {
            window.cancelAnimationFrame(animationFrameId);
            resizeObserver.disconnect();
        };
    }, [sectionRef, theme]);

    return (
        <motion.section 
            id="benefits" 
            ref={sectionRef} 
            className="py-20 bg-gray-300 dark:bg-gray-900 relative gradient-blend-top from-dark-to-gray z-30"
            animate={{ y: isContactOpen ? -150 : 0 }}
            transition={{ duration: 0.7, ease: [0.16, 1, 0.3, 1] }}
        >
            <canvas ref={canvasRef} className="absolute inset-0 z-0 pointer-events-none opacity-90 dark:opacity-70 canvas-animated"></canvas>
            <div className="container mx-auto px-6 relative z-10">
                <motion.h2 variants={sectionFadeIn} initial="hidden" animate={isInView ? "visible" : "hidden"} className="font-heading text-3xl md:text-4xl font-bold text-center mb-16 text-gray-900 dark:text-white">
                    Benefits Of AgriBlu
                </motion.h2>
                
                <motion.div 
                    className="grid grid-cols-1 md:grid-cols-3 gap-8"
                    variants={staggeredContainer}
                    initial="hidden"
                    animate={isInView ? "visible" : "hidden"}
                >
                    {BENEFITS.map((benefit, index) => (
                        <motion.div key={index} variants={cardScaleIn} className="bg-gray-50 dark:bg-agri-dark rounded-xl p-6 border-2 border-gray-200 dark:border-gray-800 card-hover">
                            <div className={`w-16 h-16 rounded-full flex items-center justify-center mb-4 bg-opacity-10 dark:bg-opacity-20 ${benefit.progress?.colorClass.replace('bg-', 'bg-') || 'bg-agri-green'}`}>
                                <i className={`${benefit.icon} text-2xl ${benefit.progress ? benefit.progress.colorClass.replace('bg-', 'text-') : 'text-agri-green'}`}></i>
                            </div>
                            <h3 className="font-heading text-2xl font-bold mb-3 text-gray-800 dark:text-white">{benefit.title}</h3>
                            <p className="text-gray-600 dark:text-gray-400 mb-4">{benefit.description}</p>
                            
                            {benefit.progress && (
                                <div className="mt-4">
                                    <div className="flex justify-between items-center text-gray-700 dark:text-gray-300">
                                        <div className={`flex items-center ${benefit.progress.colorClass.replace('bg-','text-')}`}>
                                            <span className="mr-2">{benefit.progress.label}</span>
                                            <i className="fas fa-arrow-up"></i>
                                        </div>
                                        <span className={`font-bold ${benefit.progress.colorClass.replace('bg-','text-')} ${isInView ? 'animate-number-change' : ''}`}>
                                            {benefit.progress.value}%
                                        </span>
                                    </div>
                                    <div className="w-full bg-gray-400 dark:bg-gray-700 rounded-full h-2 mt-2">
                                        <div className={`${benefit.progress.colorClass} h-2 rounded-full transition-all duration-[3000ms] ease-out`} style={{ width: isInView ? `${benefit.progress.value}%` : '0%', transitionDelay: `500ms` }}></div>
                                    </div>
                                </div>
                            )}

                            {benefit.graph && (
                                <div className="mt-4 h-24">
                                    <svg className="w-full h-full" viewBox="0 0 200 80">
                                        <polyline points="10,70 50,50 90,60 130,20 170,40 190,10" stroke="#4CAF50" strokeWidth="2" fill="none" className={isInView ? 'animate-draw-line' : ''} style={{strokeDasharray: 1000, strokeDashoffset: 1000, animationDelay: '1500ms'}}/>
                                    </svg>
                                </div>
                            )}
                        </motion.div>
                    ))}
                </motion.div>
            </div>
        </motion.section>
    );
};

// ===== From components/Contact.tsx =====
const Contact: FC = () => {
    const { theme } = useTheme();
    const [status, setStatus] = useState<'idle' | 'submitting' | 'success' | 'error'>('idle');
    const [errorMessage, setErrorMessage] = useState<string | null>(null);
    const canvasRef = useRef<HTMLCanvasElement>(null);
    const { setVisibleSection } = useSection();
    const sectionRef = useRef<HTMLDivElement>(null);
    const isInView = useInView(sectionRef, { once: false, amount: 0.1, margin: '-150px' });
    const formRef = useRef<HTMLFormElement>(null);

    const [isOpen, setIsOpen] = useState(false);
    const [showPostmark, setShowPostmark] = useState(false);
    const { setIsContactOpen } = usePageAnimation();


    useEffect(() => {
        if (isInView) {
            setVisibleSection('contact');
            if (status === 'idle' || status === 'error') {
                setIsOpen(true);
            }
        } else {
             if (status === 'idle' || status === 'error') {
                setIsOpen(false);
            }
        }
    }, [isInView, status, setVisibleSection]);

    useEffect(() => {
        setIsContactOpen(isOpen);
    }, [isOpen, setIsContactOpen]);

     useEffect(() => {
        const canvas = canvasRef.current;
        const section = sectionRef.current;
        if (!canvas || !section) return;
        const ctx = canvas.getContext('2d');
        if (!ctx) return;

        let animationFrameId: number;
        let lines: { x: number; y: number; height: number; targetHeight: number; speed: number; width: number; }[] = [];
        
        const initializeLines = () => {
            if (!canvas) return;
            const isMobile = window.innerWidth < 768;
            lines = [];
            const lineCount = isMobile ? 50 : 120;
            for (let i = 0; i < lineCount; i++) {
                lines.push({
                    x: Math.random() * canvas.width, y: canvas.height + Math.random() * 50, height: 0,
                    targetHeight: 50 + Math.random() * 100, speed: 0.3 + Math.random() * 0.4, width: 1 + Math.random() * 1.5,
                });
            }
        };

        const draw = () => {
            if (!ctx || !canvas) return;
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            
            ctx.strokeStyle = theme === 'dark' ? 'rgba(76, 175, 80, 0.7)' : 'rgba(76, 175, 80, 0.6)';
            lines.forEach(line => {
                if (line.height < line.targetHeight) { line.height += line.speed; }
                line.y -= line.speed * 0.5;
                
                if (line.y + line.height < 0) {
                    line.y = canvas.height + Math.random() * 50; line.height = 0; line.x = Math.random() * canvas.width;
                }

                ctx.lineWidth = line.width; ctx.beginPath(); ctx.moveTo(line.x, line.y); ctx.lineTo(line.x, line.y - line.height); ctx.stroke();
            });

            animationFrameId = requestAnimationFrame(draw);
        };

        const resizeObserver = new ResizeObserver(entries => {
            window.requestAnimationFrame(() => {
                if (!Array.isArray(entries) || !entries.length) return;
                for (let entry of entries) { 
                    if (canvas) {
                        canvas.width = entry.contentRect.width; 
                        canvas.height = entry.contentRect.height; 
                        initializeLines(); 
                    }
                }
            });
        });
        
        if (section) {
          resizeObserver.observe(section);
        }
        draw();
        return () => {
            window.cancelAnimationFrame(animationFrameId);
            resizeObserver.disconnect();
        };
    }, [theme, sectionRef]);

    const performSubmit = async () => {
        const form = formRef.current;
        if (!form) return;
        
        const formData = new FormData(form);
        const formJSON = Object.fromEntries(formData.entries());

        try {
            const response = await fetch('https://formspree.io/f/xnnzorpd', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
                body: JSON.stringify(formJSON)
            });

            if (response.ok) {
                setStatus('success');
                form.reset();
            } else {
                const errorData = await response.json();
                const specificError = errorData?.errors?.map((e: any) => e.message).join(' ') || 'An unexpected server error occurred.';
                setErrorMessage(specificError);
                setStatus('error');
                setIsOpen(true);
                setShowPostmark(false);
            }
        } catch (error) {
            setErrorMessage('A network error occurred. Please check your connection.');
            setStatus('error');
            setIsOpen(true);
            setShowPostmark(false);
        }
    };

    const handleSubmit = async (e: FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        if (!formRef.current?.checkValidity()) {
            formRef.current?.reportValidity();
            setErrorMessage("Please fill out all required fields.");
            return;
        }

        setStatus('submitting');
        setErrorMessage(null);
        setIsOpen(false);

        setTimeout(() => {
            setShowPostmark(true);
        }, 800);

        setTimeout(performSubmit, 1600);
    };

    const handleReset = () => {
        setStatus('idle');
        setErrorMessage(null);
        setShowPostmark(false);
        setIsOpen(isInView);
    }
    
    const envelopeVariants: Variants = {
        initial: { scale: 0.8, opacity: 0, y: 50 },
        animate: { scale: 1, opacity: 1, y: 0, transition: { duration: 0.7, ease: [0.16, 1, 0.3, 1] } },
        exit: { 
            y: -150, 
            x: 300, 
            rotate: 45, 
            scale: 0.5, 
            opacity: 0, 
            transition: { duration: 0.8, ease: 'easeInOut' } 
        },
    };
    
    const flapVariants: Variants = {
        closed: { rotateX: 0, transition: { duration: 0.7, ease: [0.16, 1, 0.3, 1] } },
        open: { rotateX: -180, transition: { duration: 0.7, ease: [0.16, 1, 0.3, 1], delay: 0.2 } },
    };

    const letterVariants: Variants = {
        closed: { y: "0%", opacity: 0, scale: 0.8, transition: { duration: 0.5, ease: 'easeOut' } },
        open: { y: "0%", opacity: 1, scale: 1, transition: { duration: 0.6, ease: [0.16, 1, 0.3, 1], delay: 0.4 } },
    }
    
    const titleVariants: Variants = {
        closed: { y: 0, opacity: 1, transition: { duration: 0.5, ease: 'easeOut' } },
        open: { y: -220, opacity: 1, transition: { duration: 0.7, ease: [0.16, 1, 0.3, 1], delay: 0.2 } },
    };

    const postmarkVariants: Variants = {
        initial: { scale: 2.5, opacity: 0, rotate: -30 },
        animate: { scale: 1, opacity: 1, rotate: -15, transition: { type: 'spring', stiffness: 400, damping: 15 } }
    };

  return (
    <section id="contact" ref={sectionRef} className="py-20 bg-white dark:bg-agri-dark relative gradient-blend-top from-gray-to-dark z-20">
        <canvas ref={canvasRef} className="absolute inset-0 z-0 pointer-events-none opacity-50 dark:opacity-50 canvas-animated"></canvas>
      <div className="container mx-auto px-6 relative z-10">
        <motion.div className="max-w-4xl mx-auto flex flex-col items-center text-center">
            <motion.div
                variants={titleVariants}
                animate={isOpen && status !== 'success' ? 'open' : 'closed'}
                initial="closed"
            >
                <h2 className="font-heading text-3xl md:text-4xl font-bold mb-4 text-gray-900 dark:text-white">Grow With Us</h2>
                <p className="text-gray-600 dark:text-gray-400 max-w-2xl mx-auto">
                    Get in touch to learn how AgriBlu can transform your agricultural operations.
                </p>
            </motion.div>
          
            <div className="relative w-full mt-12" style={{ minHeight: '480px' }}>
             <AnimatePresence>
                {status !== 'success' && (
                     <motion.div
                        key="envelope"
                        variants={envelopeVariants}
                        initial="initial"
                        animate="animate"
                        exit="exit"
                        className="absolute inset-0 h-full max-w-xl mx-auto"
                        style={{ perspective: 1000, transformStyle: 'preserve-3d' }}
                     >
                        <div className="envelope-back"></div>
                        <motion.div
                            className="letter-form"
                            variants={letterVariants}
                            animate={isOpen ? 'open' : 'closed'}
                        >
                            <div className="bg-white dark:bg-brand-gray-darker w-full h-full rounded-md shadow-inner overflow-hidden flex flex-col">
                                <form ref={formRef} onSubmit={handleSubmit} className="p-2 md:p-3 space-y-2 flex-grow flex flex-col" noValidate>
                                     <div className="flex items-center justify-between border-b dark:border-gray-700 pb-2 mb-2 px-4 pt-2 flex-shrink-0">
                                        <div className="flex items-center space-x-2">
                                            <div className="w-8 h-8 rounded-full bg-gradient-to-br from-agri-green to-agri-blue flex items-center justify-center flex-shrink-0">
                                                <i className="fas fa-seedling text-white text-sm"></i>
                                            </div>
                                            <span className="font-heading font-bold text-gray-700 dark:text-gray-200">AgriBlu</span>
                                        </div>
                                        <p className="text-xs text-gray-500 dark:text-gray-400">Official Correspondence</p>
                                    </div>
                                    <div className="px-4 space-y-3 flex-grow flex flex-col">
                                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                                          <div>
                                            <label htmlFor="fullName" className="sr-only">Full Name</label>
                                            <input type="text" id="fullName" name="fullName" required placeholder="Full Name" className="w-full bg-gray-100 dark:bg-gray-700 border border-gray-300 dark:border-gray-700 rounded-lg px-3 py-2 text-sm text-gray-800 dark:text-white focus:outline-none focus:ring-2 focus:ring-agri-green" />
                                          </div>
                                          <div>
                                            <label htmlFor="companyName" className="sr-only">Company Name</label>
                                            <input type="text" id="companyName" name="companyName" required placeholder="Company Name" className="w-full bg-gray-100 dark:bg-gray-700 border border-gray-300 dark:border-gray-700 rounded-lg px-3 py-2 text-sm text-gray-800 dark:text-white focus:outline-none focus:ring-2 focus:ring-agri-green" />
                                          </div>
                                        </div>
                                        <div>
                                          <label htmlFor="email" className="sr-only">Email</label>
                                          <input type="email" id="email" name="email" required placeholder="Email Address" className="w-full bg-gray-100 dark:bg-gray-700 border border-gray-300 dark:border-gray-700 rounded-lg px-3 py-2 text-sm text-gray-800 dark:text-white focus:outline-none focus:ring-2 focus:ring-agri-green" />
                                        </div>
                                        <div className="flex-grow">
                                          <label htmlFor="message" className="sr-only">Message</label>
                                          <textarea id="message" name="message" rows={4} required placeholder="Your message..." className="w-full h-full bg-gray-100 dark:bg-gray-700 border border-gray-300 dark:border-gray-700 rounded-lg px-3 py-2 text-sm text-gray-800 dark:text-white focus:outline-none focus:ring-2 focus:ring-agri-green resize-none"></textarea>
                                        </div>
                                    </div>
                                    <div className="text-center pt-2 flex-shrink-0">
                                        <button type="submit" disabled={status === 'submitting'} className="bg-agri-green hover:bg-green-600 text-white font-medium py-2 px-6 rounded-full transition-all duration-300 transform hover:scale-105 disabled:bg-gray-400 disabled:scale-100 disabled:cursor-not-allowed w-40">
                                            {status === 'submitting' ? 'Sending...' : 'Send'}
                                        </button>
                                        {status === 'error' && <p className="text-red-500 text-xs mt-2">{errorMessage}</p>}
                                    </div>
                                </form>
                            </div>
                        </motion.div>
                        <motion.div
                            className="envelope-flap"
                            variants={flapVariants}
                            initial="closed"
                            animate={isOpen ? 'open' : 'closed'}
                        >
                            <div className="flap-visual">
                            </div>
                            <div className="stamp">
                                <i className="fas fa-leaf text-agri-green text-2xl opacity-70"></i>
                            </div>
                        </motion.div>
                        <AnimatePresence>
                            {showPostmark && (
                                <motion.div
                                    className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 text-red-600/70 border-4 border-red-600/70 rounded-full w-28 h-28 flex items-center justify-center pointer-events-none"
                                    variants={postmarkVariants}
                                    initial="initial"
                                    animate="animate"
                                >
                                    <span className="font-black text-lg tracking-wider -rotate-12">SENT</span>
                                </motion.div>
                            )}
                        </AnimatePresence>
                     </motion.div>
                )}
             </AnimatePresence>

             <AnimatePresence>
                {status === 'success' && (
                    <motion.div
                        key="success-message"
                        initial={{ opacity: 0, scale: 0.8 }}
                        animate={{ opacity: 1, scale: 1, transition: { delay: 0.5 } }}
                        exit={{ opacity: 0, scale: 0.8 }}
                        className="text-center absolute inset-0 flex flex-col items-center justify-center"
                    >
                         <div className="inline-flex items-center px-6 py-4 bg-agri-green/10 dark:bg-agri-green/20 text-agri-green rounded-lg text-lg">
                            <i className="fas fa-check-circle mr-3"></i>
                            <span>Thank you! We'll be in touch soon.</span>
                        </div>
                        <button onClick={handleReset} className="mt-6 text-sm text-gray-500 dark:text-gray-400 hover:underline">
                            Send another message
                        </button>
                    </motion.div>
                )}
             </AnimatePresence>
          </div>

          <div className="mt-12 text-center flex flex-wrap items-center justify-center gap-6">
              <a 
                  href="https://wa.me/447557785640"
                  target="_blank"
                  rel="noopener noreferrer"
                  className="inline-flex items-center justify-center bg-green-500 hover:bg-green-600 text-white font-bold py-3 px-8 rounded-full transition-all duration-300 transform hover:scale-105"
              >
                  <i className="fab fa-whatsapp text-xl mr-3"></i>
                  Chat on WhatsApp
              </a>
              <a
                  href="https://t.me/+447557785640"
                  target="_blank"
                  rel="noopener noreferrer"
                  className="inline-flex items-center justify-center bg-blue-500 hover:bg-blue-600 text-white font-bold py-3 px-8 rounded-full transition-all duration-300 transform hover:scale-105"
              >
                  <i className="fab fa-telegram text-xl mr-3"></i>
                  Chat on Telegram
              </a>
              <a 
                  href="mailto:mark@agriblu.co.uk"
                  className="inline-flex items-center justify-center bg-agri-blue hover:bg-cyan-600 text-white font-bold py-3 px-8 rounded-full transition-all duration-300 transform hover:scale-105"
              >
                  <i className="fas fa-envelope text-xl mr-3"></i>
                  Email Us
              </a>
          </div>

        </motion.div>
      </div>
    </section>
  );
};

// ===== From components/Footer.tsx =====
const Footer: FC = () => {
  return (
    <footer className="bg-gray-300 dark:bg-gray-900 text-gray-700 dark:text-gray-300 gradient-blend-top from-dark-to-gray">
      <div className="container mx-auto px-6 pt-16 pb-8">
        <div className="grid grid-cols-1 md:grid-cols-3 gap-12 text-center md:text-left">
          <div>
            <div className="flex items-center justify-center md:justify-start space-x-3 mb-4">
              <div className="w-10 h-10 rounded-full bg-gradient-to-br from-agri-green to-agri-blue flex items-center justify-center">
                <i className="fas fa-seedling text-white"></i>
              </div>
              <span className="font-heading text-xl font-bold text-gray-800 dark:text-white">AgriBlu</span>
            </div>
            <p className="text-sm text-gray-600 dark:text-gray-400">
              Revolutionizing agriculture with intelligent aeroponics for a sustainable future.
            </p>
          </div>

          <div>
            <h3 className="font-heading text-lg font-semibold text-gray-800 dark:text-white mb-4">Company Information</h3>
            <p className="text-sm font-semibold text-gray-700 dark:text-gray-200">AGRIBLU LIMITED</p>
            <p className="text-sm text-gray-600 dark:text-gray-400">Company number: 16481432</p>
            <p className="text-sm text-gray-600 dark:text-gray-400">SIC: 01610 - Support activities for crop production</p>
            <address className="text-sm text-gray-600 dark:text-gray-400 mt-2 not-italic">
              Registered Address:<br />
              Unit 7 Acorn Industrial Estate,<br />
              Riverview Road, Beverley,<br />
              England, HU17 0LD
            </address>
          </div>

          <div>
            <h3 className="font-heading text-lg font-semibold text-gray-800 dark:text-white mb-4">Follow Us</h3>
            <div className="flex justify-center md:justify-start space-x-6">
              <a href="#" aria-label="Twitter" className="text-gray-500 dark:text-gray-400 hover:text-agri-green transition-transform duration-300 hover:scale-110">
                <i className="fab fa-twitter text-xl"></i>
              </a>
              <a href="#" aria-label="LinkedIn" className="text-gray-500 dark:text-gray-400 hover:text-agri-green transition-transform duration-300 hover:scale-110">
                <i className="fab fa-linkedin text-xl"></i>
              </a>
              <a href="#" aria-label="Instagram" className="text-gray-500 dark:text-gray-400 hover:text-agri-green transition-transform duration-300 hover:scale-110">
                <i className="fab fa-instagram text-xl"></i>
              </a>
            </div>
          </div>
        </div>

        <div className="mt-12 border-t border-gray-400 dark:border-gray-700 pt-6 text-center text-sm text-gray-500 dark:text-gray-400">
          <p>&copy; {new Date().getFullYear()} AgriBlu. All rights reserved.</p>
        </div>
      </div>
    </footer>
  );
};

const SourcePill: FC<{source: GroundingSource}> = ({ source }) => (
    <a 
        href={source.uri} 
        target="_blank" 
        rel="noopener noreferrer"
        className="inline-flex items-center gap-1.5 bg-gray-200 dark:bg-gray-600 text-gray-700 dark:text-gray-300 text-xs px-2 py-1 rounded-full transition-colors hover:bg-gray-300 dark:hover:bg-gray-500"
    >
        <i className="fas fa-link text-gray-500 dark:text-gray-400"></i>
        <span>{source.title || new URL(source.uri).hostname}</span>
    </a>
);

// ===== From components/AIAssistant.tsx =====
const ChatBubble: FC<{ message: Message }> = ({ message }) => {
  const isUser = message.sender === 'user';
  return (
    <motion.div 
        className={`flex items-start gap-2.5 ${isUser ? 'justify-end' : 'justify-start'}`}
        initial={{ opacity: 0, y: 10 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.3 }}
    >
      {!isUser && <span className="text-2xl mt-1">🌱</span>}
      <div
        className={`max-w-xs md:max-w-md rounded-2xl px-4 py-3 shadow-sm ${
          isUser 
            ? 'bg-agri-blue text-white rounded-br-none' 
            : 'bg-gray-200 dark:bg-gray-700 text-gray-800 dark:text-gray-200 rounded-bl-none'
        }`}
      >
        {message.imagePreview && (
            <img src={message.imagePreview} alt="User upload" className="mb-2 rounded-lg" />
        )}
        <p className="text-sm break-words whitespace-pre-wrap">{message.text}</p>
        {message.sources && message.sources.length > 0 && (
            <div className="mt-3 pt-2 border-t border-gray-300 dark:border-gray-600">
                <p className="text-xs font-bold mb-2 text-gray-500 dark:text-gray-400">Sources:</p>
                <div className="flex flex-wrap gap-2">
                    {message.sources.map((source, i) => <SourcePill key={i} source={source} />)}
                </div>
            </div>
        )}
      </div>
    </motion.div>
  );
};

const TypingIndicator: FC = () => (
    <div className="flex items-start gap-2.5">
        <span className="text-2xl mt-1">🌱</span>
        <div className="bg-gray-200 dark:bg-gray-700 rounded-2xl px-4 py-3 rounded-bl-none shadow-sm">
            <div className="flex items-center space-x-1.5 h-[20px]">
                <div className="w-2 h-2 bg-gray-400 dark:bg-gray-500 rounded-full animate-bounce"></div>
                <div className="w-2 h-2 bg-gray-400 dark:bg-gray-500 rounded-full animate-bounce [animation-delay:-.3s]"></div>
                <div className="w-2 h-2 bg-gray-400 dark:bg-gray-500 rounded-full animate-bounce [animation-delay:-.5s]"></div>
            </div>
        </div>
    </div>
);


const AIAssistant: FC = () => {
    const [isOpen, setIsOpen] = useState(false);
    const [messages, setMessages] = useState<Message[]>([
        { id: 'initial', text: "Hello! I'm AgriBot. I can answer your questions about AgriBlu's technology. You can even upload an image of your plants or setup! How can I help?", sender: 'ai' }
    ]);
    const [input, setInput] = useState('');
    const [isLoading, setIsLoading] = useState(false);
    const [chat, setChat] = useState<Chat | null>(null);
    const [image, setImage] = useState<{b64: string, preview: string, mimeType: string} | null>(null);
    const fileInputRef = useRef<HTMLInputElement>(null);
    const chatEndRef = useRef<HTMLDivElement>(null);
    const { visibleSection } = useSection();

    const scrollToBottom = useCallback(() => {
        chatEndRef.current?.scrollIntoView({ behavior: 'smooth' });
    },[]);

    useEffect(() => {
        if(isOpen) {
            setTimeout(scrollToBottom, 100);
        }
    }, [messages, isOpen, scrollToBottom]);
    
    useEffect(() => {
        if (isOpen && !chat) {
            setChat(createChat());
        }
    }, [isOpen, chat]);

    const SUGGESTED_PROMPTS: { [key: string]: string[] } = {
        'home': ["What is AgriBlu?", "Latest trends in CEA farming?", "Tell me about aeroponics."],
        'why': ["How much energy does AgriBlu save?", "Calculate ROI for a small farm.", "Why is energy efficiency important?"],
        'technology': ["How does mist delivery work?", "What kind of data do you monitor?", "Who invented aeroponics?"],
        'benefits': ["What are the main benefits?", "How much water is saved?", "Explain the faster growth benefit."],
        'contact': ["How do I request a demo?", "Can I partner with AgriBlu?"],
        'default': ["What is vertical farming?", "Is aeroponics sustainable?", "Tell me a fun fact about plants."]
    };

    const handleSendMessage = useCallback(async (messageText: string) => {
        const textToSend = messageText.trim();
        if ((!textToSend && !image) || isLoading || !chat) return;
        
        const userMessage: Message = { id: Date.now().toString(), text: textToSend, sender: 'user', imagePreview: image?.preview };
        setMessages(prev => [...prev, userMessage]);
        setIsLoading(true);
        setImage(null);

        const SEARCH_KEYWORDS = ['who', 'what is the latest', 'latest trends', 'news', 'invented'];
        const needsSearch = SEARCH_KEYWORDS.some(kw => textToSend.toLowerCase().includes(kw));

        const parts: any[] = [{ text: textToSend }];
        if (image) {
            parts.unshift({ inlineData: { data: image.b64, mimeType: image.mimeType } });
        }
        
        try {
            const stream = await chat.sendMessageStream({
                message: parts,
                config: {
                    ...(needsSearch && { tools: [{ googleSearch: {} }]})
                }
            });
            
            let aiResponseText = '';
            let aiMessageId = '';
            let sources: GroundingSource[] = [];

            for await (const chunk of stream) {
                aiResponseText += chunk.text;
                
                const chunkSources = chunk.candidates?.[0]?.groundingMetadata?.groundingChunks?.map((c: any) => c.web) || [];
                if (chunkSources.length > 0) {
                    sources.push(...chunkSources);
                }

                if (!aiMessageId) {
                    aiMessageId = `${Date.now()}-ai`;
                     setMessages(prev => [...prev, { id: aiMessageId, text: aiResponseText, sender: 'ai', sources }]);
                } else {
                     setMessages(prev => prev.map(m => 
                        m.id === aiMessageId ? { ...m, text: aiResponseText, sources } : m
                    ));
                }
            }
        } catch (error) {
            console.error("Error sending message:", error);
            const errorMessage: Message = { id: `${Date.now()}-err`, text: "Sorry, I couldn't connect to my brain right now. Please try again later.", sender: 'ai' };
            setMessages(prev => [...prev, errorMessage]);
        } finally {
            setIsLoading(false);
        }
    }, [chat, isLoading, image]);
    
    const handleSubmit = (e: FormEvent) => {
        e.preventDefault();
        handleSendMessage(input);
        setInput('');
    };
    
    const handlePromptClick = (prompt: string) => {
        handleSendMessage(prompt);
        setInput('');
    }

    const handleImageChange = (e: ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0];
        if (!file) return;

        const reader = new FileReader();
        reader.onloadend = () => {
            const dataUrl = reader.result as string;
            const b64 = dataUrl.split(',')[1];
            setImage({ b64, preview: dataUrl, mimeType: file.type });
        };
        reader.readAsDataURL(file);
    };

    const currentPrompts = SUGGESTED_PROMPTS[visibleSection] || SUGGESTED_PROMPTS.default;

    return (
        <>
            <div className="fixed bottom-6 right-6 z-50">
                <button
                    onClick={() => setIsOpen(!isOpen)}
                    className="bg-agri-blue text-white w-16 h-16 rounded-full shadow-lg flex items-center justify-center hover:bg-cyan-500 transition-transform duration-300 hover:scale-110 focus:outline-none focus:ring-4 focus:ring-cyan-300 dark:focus:ring-offset-agri-dark"
                    aria-label="Toggle AI Assistant"
                >
                     <AnimatePresence>
                        <motion.span
                            key={isOpen ? 'close' : 'chat'}
                            className="text-3xl absolute"
                            initial={{ opacity: 0, scale: 0.5, rotate: -90 }}
                            animate={{ opacity: 1, scale: 1, rotate: 0 }}
                            exit={{ opacity: 0, scale: 0.5, rotate: 90 }}
                            transition={{ duration: 0.3 }}
                        >
                            {isOpen ? '✕' : '💬'}
                        </motion.span>
                     </AnimatePresence>
                </button>
            </div>
            
            <AnimatePresence>
            {isOpen && (
                <motion.div 
                    initial={{ opacity: 0, y: 20, scale: 0.95 }}
                    animate={{ opacity: 1, y: 0, scale: 1 }}
                    exit={{ opacity: 0, y: 20, scale: 0.95 }}
                    transition={{ duration: 0.3, ease: 'easeOut' }}
                    className="fixed bottom-24 right-6 w-[calc(100vw-3rem)] max-w-sm h-[70vh] max-h-[600px] z-50 bg-white dark:bg-brand-gray-darker rounded-2xl shadow-2xl flex flex-col overflow-hidden border border-gray-200 dark:border-gray-700"
                >
                    <header className="p-4 bg-gray-50 dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 flex-shrink-0">
                        <h3 className="font-bold text-gray-800 dark:text-white text-lg flex items-center gap-2">
                           <span className="text-2xl">🌱</span> AgriBot Assistant
                        </h3>
                    </header>

                    <main className="flex-1 p-4 overflow-y-auto space-y-4 bg-gray-50 dark:bg-brand-gray-darker">
                       <AnimatePresence>
                            {messages.map(msg => <ChatBubble key={msg.id} message={msg} />)}
                        </AnimatePresence>
                        
                        {isLoading && <TypingIndicator />}
                        <div ref={chatEndRef} />

                        {messages.length === 1 && !isLoading && (
                            <div className="mt-4 border-t border-gray-200 dark:border-gray-600 pt-3">
                              <p className="text-sm font-medium text-gray-600 dark:text-gray-400 mb-2">Suggestions for you:</p>
                              <div className="flex flex-wrap gap-2">
                                  {currentPrompts.map(prompt => (
                                      <button 
                                        key={prompt} 
                                        onClick={() => handlePromptClick(prompt)}
                                        className="px-3 py-1.5 bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-full text-sm hover:bg-gray-300 dark:hover:bg-gray-600 transition-colors"
                                      >
                                        {prompt}
                                      </button>
                                  ))}
                              </div>
                            </div>
                        )}
                    </main>

                    <footer className="p-3 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800 flex-shrink-0">
                        {image && (
                            <div className="p-2 relative">
                                <img src={image.preview} alt="upload preview" className="h-16 w-16 object-cover rounded-md" />
                                <button onClick={() => setImage(null)} className="absolute top-0 right-0 bg-black/50 text-white rounded-full w-5 h-5 flex items-center justify-center text-xs">&times;</button>
                            </div>
                        )}
                        <form onSubmit={handleSubmit} className="flex items-center gap-2">
                            <input ref={fileInputRef} type="file" accept="image/*" onChange={handleImageChange} className="hidden" />
                            <button type="button" onClick={() => fileInputRef.current?.click()} className="text-gray-500 hover:text-agri-blue dark:text-gray-400 dark:hover:text-agri-blue transition-colors p-2 rounded-full" aria-label="Upload image">
                                <i className="fas fa-paperclip"></i>
                            </button>
                            <input
                                type="text"
                                value={input}
                                onChange={(e) => setInput(e.target.value)}
                                placeholder="Ask about farming..."
                                className="flex-1 bg-gray-200 dark:bg-gray-700 text-gray-800 dark:text-white rounded-full py-2 px-4 focus:outline-none focus:ring-2 focus:ring-agri-blue border-transparent"
                                disabled={isLoading}
                                aria-label="Chat input"
                            />
                            <button type="submit" disabled={isLoading || (!input.trim() && !image)} className="bg-agri-blue text-white rounded-full w-10 h-10 flex items-center justify-center flex-shrink-0 disabled:bg-gray-400 dark:disabled:bg-gray-500 disabled:cursor-not-allowed hover:bg-cyan-500 transition-all focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-agri-blue" aria-label="Send message">
                                <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="22" y1="2" x2="11" y2="13"></line><polygon points="22 2 15 22 11 13 2 9 22 2"></polygon></svg>
                            </button>
                        </form>
                    </footer>
                </motion.div>
            )}
            </AnimatePresence>
        </>
    );
};

// ===== From App.tsx =====
const App: FC = () => {
  return (
    <div className="font-body relative bg-white dark:bg-agri-dark text-gray-800 dark:text-gray-200">
      <Header />
      <main id="main-content">
        <Hero />
        <Why />
        <Technology />
        <Benefits />
        <Contact />
      </main>
      <Footer />
      <AIAssistant />
    </div>
  );
};

// ===== Main Render Call =====
const rootElement = document.getElementById('root');
if (!rootElement) {
  throw new Error("Could not find root element to mount to");
}

const root = ReactDOM.createRoot(rootElement);
root.render(
  <React.StrictMode>
    <ThemeProvider>
      <SectionProvider>
        <PageAnimationProvider>
          <App />
        </PageAnimationProvider>
      </SectionProvider>
    </ThemeProvider>
  </React.StrictMode>
);
