'use client';

import { useState, useEffect, useRef } from 'react';

interface HeroData {
  title: string;
  subtitle: string;
  description: string;
  primary_button_text: string;
  primary_button_link: string;
  secondary_button_text: string;
  secondary_button_link: string;
  background_image_url?: string;
  right_side_image_url?: string;
  right_side_video_full_url?: string;
  affiliation_image_url?: string;
  badge_1_icon?: string;
  badge_1_text?: string;
  badge_2_icon?: string;
  badge_2_text?: string;
}

const FALLBACK_VIDEO = 'https://agrivet.in/images/final.mp4';

export default function Hero() {
  const [heroData, setHeroData] = useState<HeroData | null>(null);
  const [loading, setLoading] = useState(true);
  const [typedTitle, setTypedTitle] = useState('');
  const [titleDone, setTitleDone] = useState(false);
  const [typedDesc, setTypedDesc] = useState('');
  const [typingDone, setTypingDone] = useState(false);
  const videoRef = useRef<HTMLVideoElement>(null);

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

  // Autoplay video once heroData is set
  useEffect(() => {
    const vid = videoRef.current;
    if (!vid) return;
    vid.muted = true;
    vid.play().catch(() => {});
  }, [heroData]);

  // Title typewriter — starts after badge entrance settles
  useEffect(() => {
    if (!heroData?.title) return;
    setTypedTitle('');
    setTitleDone(false);
    let i = 0;
    const text = heroData.title;
    const start = setTimeout(() => {
      const tick = setInterval(() => {
        i++;
        setTypedTitle(text.slice(0, i));
        if (i >= text.length) { clearInterval(tick); setTitleDone(true); }
      }, 38);
      return () => clearInterval(tick);
    }, 700);
    return () => clearTimeout(start);
  }, [heroData]);

  // Description typewriter — starts 350ms after title finishes
  useEffect(() => {
    if (!titleDone || !heroData?.description) return;
    setTypedDesc('');
    setTypingDone(false);
    let i = 0;
    const text = heroData.description;
    const start = setTimeout(() => {
      const tick = setInterval(() => {
        i++;
        setTypedDesc(text.slice(0, i));
        if (i >= text.length) { clearInterval(tick); setTypingDone(true); }
      }, 28);
      return () => clearInterval(tick);
    }, 350);
    return () => clearTimeout(start);
  }, [titleDone, heroData]);

  const fetchHeroData = async () => {
    try {
      const apiBaseUrl = process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost/agrivet_web/backend';
      const response = await fetch(`${apiBaseUrl}/api/homepage/hero`);
      const result = await response.json();
      if (result.success && result.data) {
        setHeroData(result.data);
      }
    } catch (error) {
      console.error('Error fetching hero data:', error);
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <section className="hero" id="home" style={{
        minHeight: '100vh',
        background: 'linear-gradient(135deg, #1b4332 0%, #2d6a4f 50%, #52b788 100%)',
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center'
      }}>
        <div style={{ textAlign: 'center', color: 'white' }}>
          <div style={{ fontSize: '4rem', animation: 'spin 1s linear infinite' }}>
            <i className="fas fa-spinner"></i>
          </div>
        </div>
        <style jsx>{`
          @keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
        `}</style>
      </section>
    );
  }

  if (!heroData) {
    return (
      <section className="hero" id="home" style={{
        minHeight: '100vh',
        background: 'linear-gradient(135deg, #1b4332 0%, #2d6a4f 50%, #52b788 100%)',
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center'
      }}>
        <div style={{ textAlign: 'center', color: 'white' }}>
          <div style={{ fontSize: '3rem', marginBottom: '1.5rem' }}>
            <i className="fas fa-exclamation-triangle"></i>
          </div>
          <p style={{ fontSize: '1.2rem', fontWeight: 500 }}>Hero section not available</p>
          <p style={{ fontSize: '0.9rem', opacity: 0.8, marginTop: '0.5rem' }}>Please configure hero section in admin panel</p>
        </div>
      </section>
    );
  }

  const videoSrc = heroData.right_side_video_full_url || FALLBACK_VIDEO;
  const primaryLink  = heroData.primary_button_link  || '#contact';
  const secondaryLink = heroData.secondary_button_link || '#about';
  const primaryText  = heroData.primary_button_text  || 'Get Started';
  const secondaryText = heroData.secondary_button_text || 'Know more about the company';

  return (
    <section className="hero hero-vid" id="home">
      {/* Full-background video */}
      <video
        ref={videoRef}
        className="hero-bg-video"
        src={videoSrc}
        autoPlay
        loop
        muted
        playsInline
        preload="metadata"
      />

      {/* Dark gradient overlay */}
      <div className="hero-video-overlay"></div>

      {/* Floating particles */}
      <div className="hero-particles" aria-hidden="true">
        <div className="particle"></div><div className="particle"></div>
        <div className="particle"></div><div className="particle"></div>
        <div className="particle"></div><div className="particle"></div>
      </div>

      {/* Grid lines overlay */}
      <div className="hero-grid-lines" aria-hidden="true"></div>

      <div className="hero-inner hero-fullvid">
        <div className="hero-left">

          {/* Badge — slides in from left */}
          {heroData.subtitle && (
            <div className="hero-badge h-anim h-slide-left h-d1">
              <span className="badge-dot"></span>
              {heroData.subtitle}
            </div>
          )}

          {/* Decorative divider that grows in */}
          <div className="hero-divider h-anim h-grow h-d2" aria-hidden="true"></div>

          {/* Title — typewriter */}
          <h1 className="hero-title h-anim h-slide-up h-d2">
            {typedTitle.split('\n').map((line, index, arr) => (
              <span key={index}>
                {line.includes('Smarter Future') ? (
                  <>
                    {line.split('Smarter Future')[0]}
                    <em>Smarter Future</em>
                    {line.split('Smarter Future')[1]}
                  </>
                ) : line}
                {index < arr.length - 1 && <br />}
              </span>
            ))}
            {!titleDone && <span className="hero-type-cursor">|</span>}
          </h1>

          {/* Description — typewriter */}
          {heroData.description && (
            <p className="hero-sub h-anim h-slide-up h-d3">
              {typedDesc}
              {!typingDone && <span className="hero-type-cursor">|</span>}
            </p>
          )}

          {/* Affiliation strip */}
          {heroData.affiliation_image_url && (
            <div className="hero-trust h-anim h-slide-up h-d4">
              <p className="hero-trust-label">Accreditations &amp; Affiliations</p>
              <img
                src={heroData.affiliation_image_url}
                alt="Agrivet Affiliations"
                className="hero-trust-img"
                onError={(e) => { (e.target as HTMLImageElement).style.display = 'none'; }}
              />
            </div>
          )}

          {/* Buttons — scale in */}
          <div className="hero-actions h-anim h-scale-in h-d5">
            <a href={primaryLink} className="btn-primary">
              <i className="fas fa-arrow-right"></i> {primaryText}
            </a>
            <a href={secondaryLink} className="btn-ghost-dark">
              <i className="fas fa-info-circle"></i> {secondaryText}
            </a>
          </div>
        </div>
      </div>

      {/* Scroll hint */}
      <div className="hero-scroll-hint">
        <div className="scroll-mouse">
          <div className="scroll-wheel"></div>
        </div>
      </div>
    </section>
  );
}
