import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';
import Navbar from '../components/Navbar';
import Footer from '../components/Footer';

export default function Home() {
  const [latestNotices, setLatestNotices] = useState([]);
  const [latestEvents, setLatestEvents] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchLatestData();
  }, []);

  const fetchLatestData = async () => {
    try {
      setLoading(true);
      // Fetch notices
      const noticesRes = await axios.get('http://localhost:5000/api/notices');
      setLatestNotices(noticesRes.data.slice(0, 2));

      // Fetch events
      const eventsRes = await axios.get('http://localhost:5000/api/events');
      setLatestEvents(eventsRes.data.filter(e => e.image).slice(0, 2));
    } catch (err) {
      console.error("Failed to fetch latest home data:", err);
      // Fallback fallback values
      setLatestNotices([
        { _id: '1', title: 'Mid-Term Exam Timetable Out', category: 'Exam', date: new Date().toISOString() },
        { _id: '2', title: 'School Winter Trip Registration', category: 'Academic', date: new Date().toISOString() }
      ]);
      setLatestEvents([
        { 
          _id: 'e1', 
          title: 'Robotics Team Wins Silver at Nationals', 
          description: 'Our Robotics Sparks team secured 2nd place at the national finals!', 
          image: 'https://lh3.googleusercontent.com/aida-public/AB6AXuCzavXstEIEo__mWPga-XMrOLcf59ZMNB_CPxAfsVdCGDe8AmLqXoiBRBe_-emhvW67vD-ruDCtE5TxBO2snzRC-_iedpmTSTt1_AErr0cVn0Or4uD9gqnoVbiBqgjiRCw3PJIelnQH_Xw2nIbLePzCM8Lov2zAThxzJBIJP1oSp_Dlq5VPOH8-_iujfki20m0Coivr6qsvwPgJ6EHzCUbLJNst2n90H4s-UPl12n6NmZT4H5Gz9hJFYg',
          date: new Date().toISOString()
        }
      ]);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen pt-16">
      <Navbar />
      <main className="overflow-x-hidden">
        
        {/* Hero Section */}
        <section className="relative h-[100vh] flex items-center justify-center pt-0">
          <div className="absolute inset-0 z-0">
            <div className="w-full h-full bg-cover bg-center" style={{"backgroundImage":"url('https://lh3.googleusercontent.com/aida-public/AB6AXuBAWTy7jm3MRuHI5YHAH24anHgOI7U55lHiIXe5a7rmZDj3fOK9hN9glEiQpkIYegflhDxK7qzsY92_DGRC5nektT4hCwFnDmoHLQgkKLIbkVpgYsQLSKweXDx42L_l5Ffu3qDgC0bUna4Sn7KurP3vRjS6OvMLDMuzZpzQJRreycrr6AQLAxCeV7ecWsxDDPR03z7j6bMLQlFfLwe1-0w9Z1vJnkd-PwkugLxvJIrAmucx5Dr_GpmoeA')"}}></div>
            <div className="absolute inset-0 bg-gradient-to-b from-white/10 via-transparent to-surface"></div>
          </div>
          <div className="relative z-10 text-center px-margin-mobile max-w-4xl mx-auto space-y-8">
            <div className="inline-block px-4 py-1.5 rounded-full bg-white/30 backdrop-blur-md border border-white/40 text-primary font-label-md text-label-md animate-bounce">
              Welcome to St. Andrews Academy
            </div>
            <h1 className="font-headline-xl text-[40px] md:text-headline-xl text-primary drop-shadow-lg leading-tight">
              Where Learning Becomes <br/> an <span className="text-tertiary">Adventure</span>
            </h1>
            <p className="font-body-lg text-body-lg text-on-surface-variant max-w-2xl mx-auto leading-relaxed">
              Nurturing curiosity through a curriculum designed for wonder, discovery, and the magic of childhood.
            </p>
            <div className="flex flex-col sm:flex-row gap-4 justify-center items-center">
              <Link to="/about" className="bg-primary text-on-primary px-8 py-4 rounded-full font-label-md text-label-md hover:scale-105 transition-all shadow-lg hover:shadow-primary/30 flex items-center gap-2 group">
                Explore Our School
                <span className="material-symbols-outlined group-hover:translate-x-1 transition-transform">arrow_forward</span>
              </Link>
              <Link to="/admissions" className="bg-white/90 backdrop-blur-sm text-primary px-8 py-4 rounded-full font-label-md text-label-md border-2 border-primary/20 hover:bg-white transition-all shadow-md">
                Apply for Admission
              </Link>
            </div>
          </div>

          <div className="absolute top-1/4 left-10 animate-float opacity-40 hidden lg:block">
            <span className="material-symbols-outlined text-[64px] text-primary" style={{"fontVariationSettings":"'FILL' 1"}}>auto_awesome</span>
          </div>
          <div className="absolute bottom-1/4 right-10 animate-float-slow opacity-40 hidden lg:block">
            <span className="material-symbols-outlined text-[64px] text-tertiary" style={{"fontVariationSettings":"'FILL' 1"}}>palette</span>
          </div>
        </section>

        {/* About Section */}
        <section className="py-section-gap px-margin-mobile md:px-margin-desktop bg-surface relative overflow-hidden">
          <div className="grid lg:grid-cols-2 gap-16 items-center max-w-7xl mx-auto">
            <div className="relative">
              <div className="w-full aspect-square cloud-shape bg-primary-container/20 flex items-center justify-center p-8 overflow-hidden">
                <img className="rounded-xl w-full h-full object-cover" src="https://lh3.googleusercontent.com/aida-public/AB6AXuAUpnzpLSeH93kXlZVIn6RcxAkEyKyOSP1geXCyANc74MzeUN7kTVzW_oHvQ_YwD_IZddUH5X-8Mnb36jS7jqgP84cXek02daYwVYKKsxbCul8rbibFFWiKklR9yY6Z_9acANK3qGyzdR_AoPW-pOjswSd3U5-EG9WRFF9CLqC9wlpHDgyPA1E7FtXrTO9OTXvgdlZdBsgDV1aKoKPHTbu0gdwi_6xJxwqDnIkDozuvQWe1iBiWhBwPwA" alt="Children playing" />
              </div>
              <div className="absolute -bottom-10 -right-10 w-48 h-48 bg-secondary-container cloud-shape -z-10 animate-pulse opacity-50"></div>
            </div>
            <div className="space-y-6">
              <h2 className="font-headline-lg text-headline-lg text-primary">Unlocking the Spark of Creativity</h2>
              <p className="font-body-lg text-body-lg text-on-surface-variant leading-relaxed">
                At St. Andrews Academy, we believe every child is a natural-born explorer. Our campus is a canvas where curiosity is encouraged and failure is just a stepping stone to discovery. 
              </p>
              <div className="grid sm:grid-cols-2 gap-6">
                <div className="p-6 bg-white rounded-lg border border-surface-variant shadow-sm hover:shadow-md transition-shadow group">
                  <span className="material-symbols-outlined text-primary text-[32px] mb-3 group-hover:scale-110 transition-transform">self_improvement</span>
                  <h4 className="font-headline-md text-label-md mb-1">Confidence First</h4>
                  <p className="text-sm opacity-80">Building social and emotional foundations for life.</p>
                </div>
                <div className="p-6 bg-white rounded-lg border border-surface-variant shadow-sm hover:shadow-md transition-shadow group">
                  <span className="material-symbols-outlined text-tertiary text-[32px] mb-3 group-hover:scale-110 transition-transform">lightbulb</span>
                  <h4 className="font-headline-md text-label-md mb-1">Innovative Minds</h4>
                  <p className="text-sm opacity-80">Integrating technology with hands-on play.</p>
                </div>
              </div>
            </div>
          </div>
        </section>

        <svg className="wavy-divider" preserveAspectRatio="none" viewBox="0 0 1200 120" style={{ width: '100%', height: '80px', fill: '#e6f0ff', display: 'block', marginBottom: '-1px' }}>
          <path d="M0,110V0c200,80,400,80,600,0s400-80,600,0v110H0Z"></path>
        </svg>

        {/* Dynamic Latest Updates Section */}
        <section className="py-16 bg-gradient-to-b from-[#e6f0ff] to-surface px-4 md:px-8 border-b border-outline-variant/10">
          <div className="max-w-7xl mx-auto">
            <h2 className="font-headline font-bold text-3xl text-primary text-center mb-12">Latest School Updates</h2>
            
            <div className="grid md:grid-cols-2 gap-12">
              {/* Recent Notices */}
              <div className="bg-white p-8 rounded-2xl shadow-md border border-primary/10">
                <div className="flex justify-between items-center mb-6">
                  <h3 className="font-headline font-bold text-xl text-primary flex items-center gap-2">
                    <span className="material-symbols-outlined">campaign</span> Notice Board
                  </h3>
                  <Link to="/notices" className="text-sm text-secondary hover:underline font-semibold">View All</Link>
                </div>
                <div className="space-y-4">
                  {latestNotices.map((notice) => (
                    <div key={notice._id} className="p-4 rounded-xl bg-surface hover:bg-primary-container/10 transition-colors border-l-4 border-primary">
                      <span className="text-xs text-tertiary font-bold">{notice.category}</span>
                      <h4 className="font-semibold text-on-surface text-base mb-1">{notice.title}</h4>
                      <span className="text-xs text-on-surface-variant">
                        {new Date(notice.date).toLocaleDateString()}
                      </span>
                    </div>
                  ))}
                </div>
              </div>

              {/* Recent News & Events */}
              <div className="bg-white p-8 rounded-2xl shadow-md border border-primary/10">
                <div className="flex justify-between items-center mb-6">
                  <h3 className="font-headline font-bold text-xl text-primary flex items-center gap-2">
                    <span className="material-symbols-outlined">event</span> Latest News
                  </h3>
                  <Link to="/news" className="text-sm text-secondary hover:underline font-semibold">View All</Link>
                </div>
                <div className="space-y-4">
                  {latestEvents.map((evt) => (
                    <div key={evt._id} className="flex gap-4 items-center p-2 rounded-xl hover:bg-surface transition-colors">
                      {evt.image && (
                        <img src={evt.image} className="w-16 h-16 object-cover rounded-lg" alt="" />
                      )}
                      <div>
                        <span className="text-xs text-tertiary font-bold">{evt.category}</span>
                        <h4 className="font-semibold text-on-surface text-base leading-tight mb-1">{evt.title}</h4>
                        <p className="text-xs text-on-surface-variant line-clamp-2">{evt.description}</p>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </div>
        </section>

        {/* Why Families Love Us */}
        <section className="py-section-gap px-margin-mobile md:px-margin-desktop bg-primary-container/20">
          <div className="max-w-7xl mx-auto text-center mb-16">
            <h2 className="font-headline-lg text-headline-lg text-on-primary-container">Why Families Love Us</h2>
            <div className="w-24 h-1 bg-primary mx-auto mt-4 rounded-full"></div>
          </div>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-gutter max-w-7xl mx-auto">
            <div className="bg-white p-8 rounded-lg shadow-primary/5 shadow-xl hover:-translate-y-2 transition-all duration-500 border border-primary/10">
              <div className="w-16 h-16 bg-blue-100 rounded-full flex items-center justify-center mb-6">
                <span className="material-symbols-outlined text-primary text-[40px]">rocket_launch</span>
              </div>
              <h3 className="font-headline-md text-headline-md text-primary mb-3">Science &amp; Discovery</h3>
              <p className="text-on-surface-variant">Exploring the universe through interactive labs and outdoor stargazing sessions.</p>
            </div>

            <div className="bg-white p-8 rounded-lg shadow-primary/5 shadow-xl hover:-translate-y-2 transition-all duration-500 border border-primary/10">
              <div className="w-16 h-16 bg-orange-100 rounded-full flex items-center justify-center mb-6">
                <span className="material-symbols-outlined text-tertiary text-[40px]">palette</span>
              </div>
              <h3 className="font-headline-md text-headline-md text-tertiary mb-3">Visual Arts</h3>
              <p className="text-on-surface-variant">Painting, sculpting, and digital media in our light-filled campus studios.</p>
            </div>

            <div className="bg-white p-8 rounded-lg shadow-primary/5 shadow-xl hover:-translate-y-2 transition-all duration-500 border border-primary/10">
              <div className="w-16 h-16 bg-yellow-100 rounded-full flex items-center justify-center mb-6">
                <span className="material-symbols-outlined text-secondary text-[40px]">music_note</span>
              </div>
              <h3 className="font-headline-md text-headline-md text-secondary mb-3">Musical Theatre</h3>
              <p className="text-on-surface-variant">Developing performance skills and stage confidence through yearly productions.</p>
            </div>
          </div>
        </section>

        {/* Moments of Wonder */}
        <section className="py-section-gap px-margin-mobile md:px-margin-desktop bg-surface-container-low overflow-hidden">
          <div className="max-w-7xl mx-auto text-center mb-12">
            <h2 className="font-headline-lg text-headline-lg text-primary">Moments of Wonder</h2>
            <p className="text-on-surface-variant">A glimpse into daily life at St. Andrews</p>
          </div>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-8 max-w-7xl mx-auto py-12">
            <div className="polaroid-frame rotate-[-3deg]">
              <img className="w-full aspect-square object-cover" src="https://lh3.googleusercontent.com/aida-public/AB6AXuC4_xIe9XbrCIu-SP50en8vmLGNGI5Bmp4bmMwM_qOQN4hICA4CgxNhyxLP7NckoP05buF9Vx5XB_3yiAzxskEhuxzedqq-j0jO0I1Gn-J0Tz9Tnsl2wFAmAZeUGwhUvoErUpOKjxF6NgqUMjeOBbS_gILnz4v6ZlIlS7YpiBG3q42WvpSXLRrBe4wOUZZKbprbjK0lt9Zz5_E9X7ycFsZCeu0d6gB4yUfeF4BYI82R5NpVm2JTwNsXww" alt="Painting" />
            </div>
            <div className="polaroid-frame rotate-[2deg] mt-8 md:mt-0">
              <img className="w-full aspect-square object-cover" src="https://lh3.googleusercontent.com/aida-public/AB6AXuDKxNoGLRlAwPRC10vCbhMZJUo5XHr_amf-qarGIDQYLdVDd5FUGAqc3yPHMpjXYziuduEgwQbDAQzKZkEbyyXhPnk2UG8g3jNjAdvVGl0KA5xdS3dtQcWLBKn-MkgDlgQN-Vq4HneKsLxK6uJ_vAsFz-DBLJ4KMyyfT_mLEdeKG24GhUTCBvRWL8hYok0wdncOdx-VQV2fa_yhf3O6JXNJEKQmMywHsjLc82OKogmusIxcjy13ZOL7IA" alt="School Garden" />
            </div>
            <div className="polaroid-frame rotate-[-1deg]">
              <img className="w-full aspect-square object-cover" src="https://lh3.googleusercontent.com/aida-public/AB6AXuCBKRRFmi8go-K91x8PNMzwfYwJnT1_Gt13blPZ1aJ0rebPj8MO3OjYXEJYHPSZcvgW6K-STCgJscVbK2XEjKxmfRKhlTKCbIDmVIGmPgYWMIncAM6XjdHKUF83p8NdpfvtPVWwSa3phoYhlsI0NOf-5uln17P6WDulMJqOPpO7I1htvTu-HYyNfpbAPL4_dM9vvS7Rcnv5UQsSQDQArB1QGy_AV4l3WUQjOTr398bZe1dfqr2kIEun_Q" alt="Storytime" />
            </div>
            <div className="polaroid-frame rotate-[4deg] mt-8 md:mt-0">
              <img className="w-full aspect-square object-cover" src="https://lh3.googleusercontent.com/aida-public/AB6AXuBBjn8QFh6r6YAUIHLDLJDPAhwyLenu7vUI8ewyPGjHHG27tTnB7W7dU1iwoMQ5KVvNj4JA1fOuSMTMUJ59vpVVDA6CbT9aOLqsXZqZ9_75qhHtekx7FO9EwW0frdXu00EIjyTfl7deXXXKk7YbtMBlaDoHuRqahIplSV9hfggkxSihhMRtJsNHaZsB1a7raEPC-0eb3TTNPBL2AtS8AkRqHUHEhGKEu7KZEfnmXyQxb9AJBBZcRBW1vA" alt="Science Experiment" />
            </div>
          </div>
        </section>

        {/* Testimonials */}
        <section className="py-section-gap px-margin-mobile md:px-margin-desktop bg-white">
          <div className="max-w-6xl mx-auto">
            <h2 className="font-headline-lg text-headline-lg text-center mb-16">Parent Perspectives</h2>
            <div className="grid md:grid-cols-2 gap-12">
              <div className="relative group">
                <div className="bg-primary-container/30 p-10 rounded-3xl rounded-bl-none relative shadow-sm hover:shadow-md transition-all">
                  <p className="font-body-lg italic text-on-primary-container">"Sending our daughter here was the best decision. She doesn't just learn math and science; she learns how to dream and question the world around her. Every day is a new adventure!"</p>
                </div>
                <div className="flex items-center gap-4 mt-6 ml-4">
                  <div className="w-12 h-12 rounded-full bg-surface-variant overflow-hidden">
                    <img className="w-full h-full object-cover" src="https://lh3.googleusercontent.com/aida-public/AB6AXuD4Jb6K3Ue65umglQSAbR9mZD4LhAm1Eeom3GHW64G71pwx3KzuWGqU2uNrps546cPpHvSwQWcQb3gvghAynF-nXMtTSmIyMVj1LuKmC0veHR3XTjjRugH-IYta4LCNYEtm2J-he4qf-QF8sYK18svbVBkFfbchUpr4HbvGFJMUfxra8IDRp2IIK7uFZhXMLmQHBl5HNYoNlzS69VSzD-kLenZSDS-Cs7MPof4o4ZXTtnFhwTVKkpWsEg" alt="Parent Sarah" />
                  </div>
                  <div>
                    <h4 className="font-label-md">Sarah Jenkins</h4>
                    <p className="text-xs text-on-surface-variant">Mother of Emily (Grade 2)</p>
                  </div>
                </div>
              </div>

              <div className="relative group">
                <div className="bg-primary-container/30 p-10 rounded-3xl rounded-bl-none relative shadow-sm hover:shadow-md transition-all">
                  <p className="font-body-lg italic text-on-primary-container">"The curriculum is incredible. It integrates storytelling and technology seamlessly. Our son comes home talking about robots and forest trips. Exceptional educators!"</p>
                </div>
                <div className="flex items-center gap-4 mt-6 ml-4">
                  <div className="w-12 h-12 rounded-full bg-surface-variant overflow-hidden">
                    <img className="w-full h-full object-cover" src="https://lh3.googleusercontent.com/aida-public/AB6AXuB0ulTZpwesW_KFjm3lTRKFOQnaKMOJtJQzaYTtG-9XuJs36Kd5haxy52s0az5C-PTQZUnbirMf1G2coQUhcCFht9pBbkDcz_gGChnweuV4gPgJEyFU30Iybv_XZvZOkkjvMRTspWTtHzAmgDZZjlPllf-aOOJfKO44GLqOuArqPaECMmxdMrDDBrTrEE7gMWR8lTvh47YP9vadibW2lGM1y9zjhQLHI2jaaGHghGPP-iwTokiskWKyYA" alt="Parent David" />
                  </div>
                  <div>
                    <h4 className="font-label-md">David Miller</h4>
                    <p className="text-xs text-on-surface-variant">Father of Toby (Kindergarten)</p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </section>
      </main>
      <Footer />
    </div>
  );
}
