import React, { useState, useEffect, useRef } from 'react';
import ReactDOM from 'react-dom/client';
import { X, Instagram, Linkedin } from 'lucide-react';

// --- Hooks ---
const useFadeIn = <T extends HTMLElement,>(): [React.RefObject<T>, boolean] => {
  const [isVisible, setIsVisible] = useState(false);
  const ref = useRef<T>(null);

  useEffect(() => {
    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          setIsVisible(true);
          if (ref.current) {
            observer.unobserve(ref.current);
          }
        }
      },
      {
        threshold: 0.1,
      }
    );

    if (ref.current) {
      observer.observe(ref.current);
    }

    return () => {
      if (ref.current) {
        // eslint-disable-next-line react-hooks/exhaustive-deps
        observer.unobserve(ref.current);
      }
    };
  }, []);

  return [ref, isVisible];
};

// --- TopBar Component ---
const TopBar: React.FC = () => {
  const [menuOpen, setMenuOpen] = useState(false);

  return (
    <>
      <div className="w-full bg-white shadow-sm fixed top-0 z-50">
        <div className="max-w-7xl mx-auto px-4 py-2 flex items-center justify-between">
          <div className="flex items-center space-x-2">
            <a href="/" aria-label="Home">
              <img
                src="../logoslabirintar/Labirintar_Bubble.webp"
                alt="Logo Labirintar"
                className="h-10"
              />
            </a>
          </div>

          <div className="hidden md:flex items-center space-x-4">
            <a href="/para-escolas" className="text-secondary px-3 py-2 hover:text-secondary-dark font-medium">Para escolas</a>
            <a href="/experiences" className="text-secondary px-3 py-2 hover:text-secondary-dark font-medium">Experiências</a>
            <span className="text-secondary px-3 py-2 font-medium cursor-default">Quem somos</span>
            <span className="text-secondary px-3 py-2 font-medium cursor-default">Rede</span>
            <a href="https://blog.labirintar.com.br/" className="text-secondary px-3 py-2 hover:text-secondary-dark font-medium">Blog</a>
            <a href="#contato" className="text-secondary px-3 py-2 hover:text-secondary-dark font-medium">Contato</a>
            <a
              href="https://app.labirintar.com.br/admin"
              className="bg-white text-secondary border border-secondary px-4 py-2 rounded font-bold hover:bg-secondary hover:text-white transition"
            >
              Entrar
            </a>
          </div>

          <div className="md:hidden">
            <button
              onClick={() => setMenuOpen(!menuOpen)}
              aria-label="Abrir menu mobile"
            >
              {menuOpen ? (
                <X className="w-6 h-6 text-text-main" />
              ) : (
                <svg
                  className="w-6 h-6 text-text-main"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth={2}
                  viewBox="0 0 24 24"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    d="M4 6h16M4 12h16M4 18h16"
                  />
                </svg>
              )}
            </button>
          </div>
        </div>
      </div>

      {menuOpen && (
        <div className="fixed inset-0 bg-white z-40 p-6 flex flex-col items-start gap-6 shadow-xl transition-all">
          <div className="flex items-center justify-between w-full">
            <div className="flex items-center space-x-2">
                <a href="/" aria-label="Home">
                  <img
                    src="../logoslabirintar/Labirintar_RGB.png"
                    alt="Logo"
                    className="h-6"
                  />
                </a>
                <span className="font-bold text-secondary">LABIRINTAR</span>
              </div>
            <button
              onClick={() => setMenuOpen(false)}
              aria-label="Fechar menu mobile"
            >
              <X className="w-6 h-6 text-gray-500" />
            </button>
          </div>

          <a href="/para-escolas" className="w-full text-center bg-white text-secondary px-4 py-2 rounded font-bold hover:bg-secondary hover:text-white transition">Para escolas</a>

          <a href="/experiences" className="w-full text-center bg-white text-secondary px-4 py-2 rounded font-bold hover:bg-secondary hover:text-white transition">Experiências</a>

          <span className="w-full text-center bg-white text-secondary px-4 py-2 rounded font-bold cursor-default">Quem somos</span>

          <span className="w-full text-center bg-white text-secondary px-4 py-2 rounded font-bold cursor-default">Rede</span>

          <a href="https://blog.labirintar.com.br/" className="w-full text-center bg-white text-secondary px-4 py-2 rounded font-bold hover:bg-secondary hover:text-white transition">Blog</a>

          <a href="#contato" className="w-full text-center bg-white text-secondary px-4 py-2 rounded font-bold hover:bg-secondary hover:text-white transition">Contato</a>

          <a href="https://app.labirintar.com.br/admin" className="w-full text-center border border-secondary text-secondary font-bold py-2 rounded">Entrar</a>
        </div>
      )}
    </>
  );
};

// --- Hero Section ---
const Hero: React.FC = () => {
  const [titleRef, isTitleVisible] = useFadeIn<HTMLHeadingElement>();
  const [subtitleRef, isSubtitleVisible] = useFadeIn<HTMLParagraphElement>();

  const getFadeInClass = (isVisible: boolean) =>
    `transition-all duration-1000 ease-out ${isVisible ? 'opacity-100 translate-y-0' : 'opacity-0 translate-y-8'}`;

  return (
    <header
      className="relative h-[60vh] flex flex-col items-center justify-center text-center p-4 overflow-hidden"
      style={{
        backgroundImage: `url(../imagensFundo/img_fundo.jpg)`,
        backgroundSize: 'cover',
        backgroundPosition: 'center 30%',
      }}
    >
      <div className="absolute inset-0 bg-white/70"></div>
      
      <h1
        ref={titleRef}
        className={`relative font-raleway text-[clamp(2.5rem,6vw,4rem)] leading-tight ${getFadeInClass(isTitleVisible)}`}
        style={{
          transitionDelay: '100ms',
          color: '#000000ff'
        }}
      >
        Para Escolas
      </h1>

      <p
        ref={subtitleRef}
        className={`relative font-raleway text-2xl font-light tracking-wider mt-4 ${getFadeInClass(isSubtitleVisible)}`}
        style={{
          transitionDelay: '300ms',
          color: '#000000ff'
        }}
      >
        Construindo parcerias que fazem sentido
      </p>
    </header>
  );
};

// --- Section 1: Partnership Flow ---
const PartnershipFlowSection: React.FC = () => {
  const [sectionRef, isVisible] = useFadeIn<HTMLElement>();

  const getFadeInClass = (isVisible: boolean) =>
    `transition-all duration-1000 ease-out ${isVisible ? 'opacity-100 translate-y-0' : 'opacity-0 translate-y-8'}`;

  return (
    <section
      ref={sectionRef}
      className={`container mx-auto max-w-5xl py-24 px-4 sm:px-8 ${getFadeInClass(isVisible)}`}
    >
      <h2 className="font-raleway text-center text-[clamp(2.2rem,5vw,3.2rem)] leading-tight mb-6">
        Como construímos parcerias com as escolas
      </h2>
      
      <p className="text-center text-2xl text-gray-600 max-w-3xl mx-auto mb-16">
        Organizar o Tempo Integral como sistema exige escuta, planejamento conjunto, validação de viabilidade e acompanhamento contínuo.
      </p>

      <div className="flex justify-center">
        <img 
          src="../imagensFundo/image7.jpg" 
          alt="Diagrama do fluxo de parceria Labirintar–Escola" 
          className="w-full max-w-4xl rounded-2xl shadow-lg"
        />
      </div>
    </section>
  );
};

// --- Section 2: School Benefits ---
const SchoolBenefitsSection: React.FC = () => {
  const [sectionRef, isVisible] = useFadeIn<HTMLElement>();

  const getFadeInClass = (isVisible: boolean) =>
    `transition-all duration-1000 ease-out ${isVisible ? 'opacity-100 translate-y-0' : 'opacity-0 translate-y-8'}`;

  const benefits = [
    'Receita recorrente com previsibilidade e coerência pedagógica',
    'Uso estratégico dos espaços e do tempo escolar',
    'Visibilidade sobre o que acontece no contraturno, com dados para decisões mais conscientes',
    'Continuidade pedagógica que fortalece vínculos e reduz rotatividade',
    'Menos sobrecarga para a coordenação, mais foco no que importa',
    'Engajamento real de famílias e crianças ao longo do tempo',
    'Reputação de inovação sustentada pela prática, não pelo discurso'
  ];

  return (
    <section
      ref={sectionRef}
      className={`w-full py-24 px-4 sm:px-8 bg-gradient-to-br from-accent-blue to-light-bg ${getFadeInClass(isVisible)}`}
    >
      <div className="container mx-auto max-w-5xl">
        <h2 className="font-raleway text-center text-[clamp(2.2rem,5vw,3.2rem)] leading-tight mb-6">
          Vantagens para a escola ao escolher pela Labirintar
        </h2>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mt-12">
          {benefits.map((benefit, index) => (
            <div
              key={index}
              className="bg-white p-6 rounded-xl shadow-md hover:shadow-lg transition-shadow duration-300"
            >
              <div className="flex items-start gap-4">
                <div className="flex-shrink-0 w-8 h-8 bg-primary rounded-full flex items-center justify-center text-white font-bold">
                  {index + 1}
                </div>
                <p className="text-lg text-gray-800 leading-relaxed">
                  {benefit}
                </p>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

// --- Footer Component ---
const Footer: React.FC = () => {
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    phone: '',
    role: '',
    school: ''
  });
  const [isSubmitting, setIsSubmitting] = useState(false);

  const formatPhoneNumber = (value: string): string => {
    const numbers = value.replace(/\D/g, '');
    const limitedNumbers = numbers.slice(0, 11);

    if (limitedNumbers.length <= 2) {
      return `(${limitedNumbers}`;
    } else if (limitedNumbers.length <= 7) {
      return `(${limitedNumbers.slice(0, 2)}) ${limitedNumbers.slice(2)}`;
    } else {
      return `(${limitedNumbers.slice(0, 2)}) ${limitedNumbers.slice(2, 7)}-${limitedNumbers.slice(7)}`;
    }
  };

  const validatePhoneNumber = (value: string): boolean => {
    const numbers = value.replace(/\D/g, '');
    return numbers.length >= 10 && numbers.length <= 11;
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    if (name === 'phone') {
      setFormData(prev => ({ ...prev, [name]: formatPhoneNumber(value) }));
    } else {
      setFormData(prev => ({ ...prev, [name]: value }));
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!validatePhoneNumber(formData.phone)) {
      alert('Por favor, insira um telefone válido no formato (00) 99999-9999');
      return;
    }

    setIsSubmitting(true);
    
    try {
      const response = await fetch('https://script.google.com/macros/s/AKfycbwgfSc9VBe2FViJNYVCDiiWGHm_4cl3f9zSLsTCo4ZKNjieMwiJJbxjIXiXopgiHR3C/exec', {
        method: 'POST',
        mode: 'no-cors',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          action: 'contact',
          timestamp: new Date().toISOString(),
          source: 'para-escolas',
          ...formData
        })
      });

      alert('Mensagem enviada com sucesso! Nossa equipe entrará em contato em breve.');
      setFormData({ name: '', email: '', phone: '', role: '', school: '' });
    } catch (error) {
      console.error('Erro ao enviar formulário:', error);
      alert('Erro ao enviar mensagem. Por favor, tente novamente.');
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <footer id="contato" className="bg-light-bg py-20 px-4">
      <div className="container mx-auto max-w-4xl">
        <h2 className="font-raleway text-4xl text-text-main mb-6 text-center">
          Vamos organizar juntos o Tempo Integral da sua escola?
        </h2>
        <p className="text-xl text-gray-700 max-w-2xl mx-auto mb-12 text-center">
          Preencha seus dados e nossa equipe entra em contato para compreender
          o contexto da sua instituição e desenhar uma proposta alinhada ao seu projeto pedagógico.
        </p>
        
        <form onSubmit={handleSubmit} className="max-w-2xl mx-auto bg-white p-8 rounded-2xl shadow-lg">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
            <div>
              <label htmlFor="footer-name" className="block font-semibold mb-2" style={{ color: '#bf917f' }}>Nome Completo *</label>
              <input
                type="text"
                id="footer-name"
                name="name"
                value={formData.name}
                onChange={handleInputChange}
                required
                className="w-full p-3 border-2 border-gray-300 rounded-lg text-lg focus:ring-2 focus:ring-secondary focus:outline-none bg-white text-text-main"
                placeholder="Seu nome"
              />
            </div>
            
            <div>
              <label htmlFor="footer-email" className="block font-semibold mb-2" style={{ color: '#bf917f' }}>Email *</label>
              <input
                type="email"
                id="footer-email"
                name="email"
                value={formData.email}
                onChange={handleInputChange}
                required
                className="w-full p-3 border-2 border-gray-300 rounded-lg text-lg focus:ring-2 focus:ring-secondary focus:outline-none bg-white text-text-main"
                placeholder="seu@email.com"
              />
            </div>
            
            <div>
              <label htmlFor="footer-phone" className="block font-semibold mb-2" style={{ color: '#bf917f' }}>Telefone *</label>
              <input
                type="tel"
                id="footer-phone"
                name="phone"
                value={formData.phone}
                onChange={handleInputChange}
                required
                className="w-full p-3 border-2 border-gray-300 rounded-lg text-lg focus:ring-2 focus:ring-secondary focus:outline-none bg-white text-text-main"
                placeholder="(00) 00000-0000"
              />
            </div>
            
            <div>
              <label htmlFor="footer-role" className="block font-semibold mb-2" style={{ color: '#bf917f' }}>Cargo *</label>
              <input
                type="text"
                id="footer-role"
                name="role"
                value={formData.role}
                onChange={handleInputChange}
                required
                className="w-full p-3 border-2 border-gray-300 rounded-lg text-lg focus:ring-2 focus:ring-secondary focus:outline-none bg-white text-text-main"
                placeholder="Ex: Coordenador(a)"
              />
            </div>
          </div>
          
          <div className="mb-6">
            <label htmlFor="footer-school" className="block font-semibold mb-2" style={{ color: '#bf917f' }}>Nome da Escola *</label>
            <input
              type="text"
              id="footer-school"
              name="school"
              value={formData.school}
              onChange={handleInputChange}
              required
              className="w-full p-3 border-2 border-gray-300 rounded-lg text-lg focus:ring-2 focus:ring-secondary focus:outline-none bg-white text-text-main"
              placeholder="Nome da instituição"
            />
          </div>
          
          <div className="flex justify-center">
            <button
              type="submit"
              disabled={isSubmitting}
              className="py-4 px-10 rounded-full text-white font-bold text-lg bg-secondary transition-all transform shadow-md hover:shadow-lg hover:bg-opacity-90 hover:-translate-y-1 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {isSubmitting ? 'Enviando...' : 'Enviar Mensagem'}
            </button>
          </div>
        </form>
        
        <div className="flex justify-center gap-6 mt-12">
          <a href="https://www.instagram.com/labirintar/" target="_blank" rel="noopener noreferrer" className="text-secondary hover:text-primary transition-colors">
            <Instagram size={32} />
          </a>
          <a href="https://www.linkedin.com/company/labirintar/" target="_blank" rel="noopener noreferrer" className="text-secondary hover:text-primary transition-colors">
            <Linkedin size={32} />
          </a>
        </div>
      </div>
    </footer>
  );
};

// --- Main App Component ---
const App: React.FC = () => {
  useEffect(() => {
    document.documentElement.style.scrollBehavior = 'smooth';
    return () => {
      document.documentElement.style.scrollBehavior = 'auto';
    };
  }, []);

  return (
    <div className="font-raleway overflow-x-hidden min-h-screen flex flex-col">
      <TopBar />
      <Hero />
      <main className="flex-1">
        <PartnershipFlowSection />
        <SchoolBenefitsSection />
      </main>
      <Footer />
    </div>
  );
};

const root = ReactDOM.createRoot(document.getElementById('root')!);
root.render(<App />);
