import { Head, Link } from '@inertiajs/react';
import { motion, useMotionValue, useSpring, useTransform } from 'framer-motion';
import { useState } from 'react';
import { LandingHeader } from '@/Components/Layout/LandingHeader';
import { LandingFooter } from '@/Components/Layout/LandingFooter';
import { SchoolCarousel } from '@/Components/Landing/SchoolCarousel';
import { CountUp } from '@/Components/Landing/CountUp';
import { HeroConstellation } from '@/Components/Landing/HeroConstellation';

const eO  = 'easeOut' as const;
const eIO = 'easeInOut' as const;
const fadeUp  = { hidden: { opacity: 0, y: 24 }, show: { opacity: 1, y: 0 } };
const stagger = { hidden: {}, show: { transition: { staggerChildren: 0.08 } } };

type PartnerSchool = { name: string; address: string | null };
type HeroStat = { key: string; label: string; value: number };
interface Props { partnerSchools?: PartnerSchool[]; heroStats?: HeroStat[] }

const statIcons: Record<string, string> = {
  schools: 'bi-buildings',
  students: 'bi-people-fill',
  teachers: 'bi-person-workspace',
  classrooms: 'bi-door-open-fill',
};

function FloatingStatCard({ stat, index }: { stat: HeroStat; index: number }) {
  const pointerX = useMotionValue(0);
  const pointerY = useMotionValue(0);
  const rotateX = useSpring(useTransform(pointerY, [-0.5, 0.5], [8, -8]), { stiffness: 170, damping: 18 });
  const rotateY = useSpring(useTransform(pointerX, [-0.5, 0.5], [-10, 10]), { stiffness: 170, damping: 18 });

  const resetTilt = () => {
    pointerX.set(0);
    pointerY.set(0);
  };

  return (
    <motion.div
      className="lp-orb-float-frame"
      animate={{ y: [0, index % 2 === 0 ? -11 : -8, 0] }}
      transition={{ duration: 4.4 + index * 0.35, repeat: Infinity, ease: eIO, delay: index * -0.7 }}
    >
      <motion.div
        className="lp-orb"
        style={{ rotateX, rotateY, transformPerspective: 850, transformStyle: 'preserve-3d' }}
        whileHover={{ scale: 1.08, y: -8 }}
        onPointerMove={(event) => {
          const bounds = event.currentTarget.getBoundingClientRect();
          pointerX.set((event.clientX - bounds.left) / bounds.width - 0.5);
          pointerY.set((event.clientY - bounds.top) / bounds.height - 0.5);
        }}
        onPointerLeave={resetTilt}
        onPointerCancel={resetTilt}
      >
        <i className={`bi ${statIcons[stat.key] ?? 'bi-bar-chart-fill'} lp-orb-icon`} aria-hidden="true" />
        <span className="lp-orb-copy">
          <strong className="lp-num"><CountUp to={stat.value} /></strong>
          <span className="lp-orb-label">{stat.label}</span>
        </span>
      </motion.div>
    </motion.div>
  );
}

function WaveDown({ fill }: { fill: string }) {
  return (
    <div className="lp-wave-wrap" aria-hidden="true">
      <svg viewBox="0 0 1440 80" preserveAspectRatio="none" xmlns="http://www.w3.org/2000/svg">
        <path d="M0,0 C360,80 1080,0 1440,60 L1440,80 L0,80 Z" fill={fill} />
      </svg>
    </div>
  );
}

export default function Home({ partnerSchools = [], heroStats = [] }: Props) {

  const [focusIndex, setFocusIndex] = useState<number | null>(null);

  const statsByKey = new Map(heroStats.map((stat) => [stat.key, stat]));
  const leftStats = ['students', 'schools']
    .map((key) => statsByKey.get(key))
    .filter((stat): stat is HeroStat => Boolean(stat));
  const rightStats = ['classrooms', 'teachers']
    .map((key) => statsByKey.get(key))
    .filter((stat): stat is HeroStat => Boolean(stat));

  const scrollToSchools = () => {
    document.getElementById('partner-schools')?.scrollIntoView({ behavior: 'smooth' });
  };

  return (
    <div className="lp">
      <Head title="خانه">
        <meta name="description" content="دانشیار من؛ هوشمندترین پنل مدیریت مدرسه. امتحان، نمره، پیامک و رأی‌گیری در یک سامانه فارسی." />
      </Head>

      <LandingHeader transparent topMode="dark" />

      {/* ══════════════════════════════════ HERO ══════════════════════════════════ */}
      <section className={`lp-hero${focusIndex !== null ? ' is-focused' : ''}`} id="home">
        <div className="lp-aurora" aria-hidden="true">
          <span className="lp-aurora-blob lp-aurora-blob--1" />
          <span className="lp-aurora-blob lp-aurora-blob--2" />
          <span className="lp-aurora-blob lp-aurora-blob--3" />
        </div>

        <motion.div
          className="lp-hero-titlebar"
          initial={{ opacity: 0, y: -16 }}
          animate={{ opacity: focusIndex !== null ? 0 : 1, y: focusIndex !== null ? -16 : 0 }}
          transition={{ duration: 0.5, ease: eO }}
        >
          <span className="lp-hero-titlebar-kicker">اتوماسیون هوشمند مدارس</span>
          <span className="lp-hero-titlebar-sub">سامانه مدیریت هوشمند مدرسه</span>
        </motion.div>

        <HeroConstellation
          focusIndex={focusIndex}
          onFocus={setFocusIndex}
          onExit={() => setFocusIndex(null)}
        />

        <div className="lp-hero-stats" aria-label="آمار سامانه">
          <motion.div className="lp-hero-stats-group lp-hero-stats-group--left" variants={stagger} initial="hidden" animate="show">
            {leftStats.map((stat, index) => (
              <motion.div key={stat.key} variants={fadeUp} transition={{ duration: 0.55, ease: eO }}>
                <FloatingStatCard stat={stat} index={index} />
              </motion.div>
            ))}
          </motion.div>

          <motion.div className="lp-hero-stats-group lp-hero-stats-group--right" variants={stagger} initial="hidden" animate="show">
            {rightStats.map((stat, index) => (
              <motion.div key={stat.key} variants={fadeUp} transition={{ duration: 0.55, ease: eO }}>
                <FloatingStatCard stat={stat} index={index + 2} />
              </motion.div>
            ))}
          </motion.div>
        </div>

        <motion.button
          type="button"
          className="lp-scroll-btn"
          aria-label="رفتن به بخش مدارس"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ delay: 2.2, duration: 0.6 }}
          onClick={scrollToSchools}
        >
          <motion.i
            className="bi bi-chevron-double-down"
            animate={{ y: [0, 7, 0] }}
            transition={{ duration: 1.8, repeat: Infinity, ease: eIO, delay: 2.4 }}
          />
        </motion.button>
      </section>

      {/* ══════════════════════ SCHOOL SHOWCASE CAROUSEL ═════════════════════════ */}
      <section className="lp-ticker-section" id="partner-schools" aria-label="مدارس همراه ما">
        <div className="lp-ticker-wave lp-ticker-wave--top" aria-hidden="true">
          <svg viewBox="0 0 1440 82" preserveAspectRatio="none" xmlns="http://www.w3.org/2000/svg">
            <defs>
              <linearGradient id="heroWaveFill" x1="0" y1="0" x2="1" y2="0">
                <stop offset="0%" stopColor="#06141A" />
                <stop offset="45%" stopColor="#0A2233" />
                <stop offset="100%" stopColor="#06141A" />
              </linearGradient>
            </defs>
            <path d="M0,0 H1440 V42 C1190,82 980,18 720,52 C430,90 210,22 0,66 Z" fill="url(#heroWaveFill)" />
          </svg>
        </div>

        <SchoolCarousel schools={partnerSchools} />

      </section>

      {/* ══════════════════════════════════ CTA ══════════════════════════════════ */}
      <section className="lp-cta" id="about">
        <div className="lp-cta-wave-top" aria-hidden="true">
          <svg viewBox="0 0 1440 82" preserveAspectRatio="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M0,82 H1440 V28 C1190,-2 980,64 720,32 C430,-4 210,58 0,18 Z" fill="#0C9E72" />
          </svg>
        </div>
        <motion.div
          className="lp-cta-inner"
          initial={{ opacity: 0, y: 26 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true, amount: 0.35 }}
          transition={{ duration: 0.65, ease: eO }}
        >
          <h2>مدرسه‌تان را هوشمند و یکپارچه مدیریت کنید</h2>
          <p>
            دانشیار من برای یک هدف ساخته شده: کارهای پراکنده مدرسه را در یک پنل فارسی،
            روشن و قابل کنترل جمع کند تا زمان مدیر و کادر آموزشی صرف آموزش شود.
          </p>
          <div className="lp-cta-btns">
            <Link href="/demo" className="lp-btn lp-btn--white lp-btn--lg">
              <i className="bi bi-play-circle-fill" />
              ورود به دمو
            </Link>
            <Link href="/contact" className="lp-btn lp-btn--white lp-btn--lg">
              <i className="bi bi-calendar-check-fill" />
              درخواست دمو
            </Link>
          </div>
        </motion.div>
        <WaveDown fill="#0F2337" />
      </section>

      {/* ══════════════════════════════════ FOOTER ══════════════════════════════════ */}
      <LandingFooter />
    </div>
  );
}
