import React, { useEffect, useMemo, useRef, useState } from 'react';
import { createRoot } from 'react-dom/client';
import * as THREE from 'three';
import '../style.css';
import { pages } from './generated/pages.js';

const routeByFile = {
  '/index.html': '/',
  '/modulos.html': '/modulos',
  '/precos.html': '/precos',
  '/sobre.html': '/sobre',
  '/blog.html': '/blog',
  '/contato.html': '/contato',
  '/demo.html': '/demo'
};

const fileByRoute = {
  '/': '/',
  '/modulos': '/modulos',
  '/precos': '/precos',
  '/sobre': '/sobre',
  '/blog': '/blog',
  '/contato': '/contato',
  '/demo': '/demo'
};

function currentRoute() {
  const path = window.location.pathname || '/';
  return routeByFile[path] || (pages[path] ? path : '/');
}

function routeFromHref(rawHref) {
  if (!rawHref || rawHref.startsWith('mailto:') || rawHref.startsWith('tel:')) return null;

  const url = new URL(rawHref, window.location.origin);
  if (url.origin !== window.location.origin) return null;

  if (rawHref.startsWith('#')) {
    return { route: currentRoute(), href: window.location.pathname + rawHref, hash: rawHref };
  }

  const route = routeByFile[url.pathname] || (pages[url.pathname] ? url.pathname : null);
  if (!route) return null;

  return { route, href: fileByRoute[route] + url.hash, hash: url.hash };
}

function useThreeScene(pageHtml) {
  useEffect(() => {
    const canvas = document.getElementById('hero-canvas');
    if (!canvas) return undefined;

    let frameId = 0;
    let mouseX = 0;
    let mouseY = 0;
    const scene = new THREE.Scene();
    const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
    const renderer = new THREE.WebGLRenderer({ canvas, alpha: true, antialias: true });

    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));

    const particlesGeo = new THREE.BufferGeometry();
    const count = 1800;
    const pos = new Float32Array(count * 3);
    for (let i = 0; i < count; i += 1) {
      const t = Math.random() * Math.PI * 2;
      const p = Math.acos(Math.random() * 2 - 1);
      const r = 5 + Math.random() * 5;
      pos[i * 3] = Math.sin(p) * Math.cos(t) * r;
      pos[i * 3 + 1] = Math.sin(p) * Math.sin(t) * r;
      pos[i * 3 + 2] = Math.cos(p) * r;
    }
    particlesGeo.setAttribute('position', new THREE.BufferAttribute(pos, 3));

    const particles = new THREE.Points(
      particlesGeo,
      new THREE.PointsMaterial({
        color: 0x14b8a6,
        size: 0.035,
        transparent: true,
        opacity: 0.3,
        blending: THREE.AdditiveBlending,
        sizeAttenuation: true
      })
    );
    scene.add(particles);

    const net = new THREE.Mesh(
      new THREE.IcosahedronGeometry(3.5, 1),
      new THREE.MeshBasicMaterial({ color: 0x14b8a6, wireframe: true, transparent: true, opacity: 0.04 })
    );
    scene.add(net);

    [
      { radius: 3.8, width: 0.4, color: 0x14b8a6, opacity: 0.06, rx: Math.PI / 3 },
      { radius: 4.8, width: 0.3, color: 0x6366f1, opacity: 0.04, rx: -Math.PI / 4, rz: Math.PI / 5 },
      { radius: 5.5, width: 0.25, color: 0x06b6d4, opacity: 0.03, rx: Math.PI / 2.5, rz: Math.PI / 7 }
    ].forEach((ring) => {
      const mesh = new THREE.Mesh(
        new THREE.RingGeometry(ring.radius, ring.radius + ring.width, 64),
        new THREE.MeshBasicMaterial({ color: ring.color, side: THREE.DoubleSide, transparent: true, opacity: ring.opacity })
      );
      mesh.rotation.x = ring.rx || 0;
      mesh.rotation.z = ring.rz || 0;
      scene.add(mesh);
    });

    camera.position.z = 11;

    const onMouseMove = (event) => {
      mouseX = (event.clientX / window.innerWidth - 0.5) * 2;
      mouseY = (event.clientY / window.innerHeight - 0.5) * 2;
    };

    const onResize = () => {
      camera.aspect = window.innerWidth / window.innerHeight;
      camera.updateProjectionMatrix();
      renderer.setSize(window.innerWidth, window.innerHeight);
    };

    const animate = () => {
      frameId = requestAnimationFrame(animate);
      particles.rotation.y += 0.0003;
      particles.rotation.x += 0.0001;
      net.rotation.y += 0.0012;
      net.rotation.x += 0.0006;
      scene.children.forEach((child, index) => {
        if (child.isMesh && child.geometry.type === 'RingGeometry') {
          child.rotation.y += 0.0004 * (index === 5 ? -1 : 1);
        }
      });
      particles.rotation.y += (mouseX * 0.012 - particles.rotation.y) * 0.008;
      particles.rotation.x += (mouseY * 0.012 - particles.rotation.x) * 0.008;
      renderer.render(scene, camera);
    };

    document.addEventListener('mousemove', onMouseMove);
    window.addEventListener('resize', onResize);
    animate();

    return () => {
      cancelAnimationFrame(frameId);
      document.removeEventListener('mousemove', onMouseMove);
      window.removeEventListener('resize', onResize);
      renderer.dispose();
      particlesGeo.dispose();
      scene.traverse((obj) => {
        if (obj.geometry) obj.geometry.dispose();
        if (obj.material) obj.material.dispose();
      });
    };
  }, [pageHtml]);
}

function usePageInteractions(pageHtml, setRoute) {
  useEffect(() => {
    let lastScrollY = window.scrollY;
    const nav = document.querySelector('.nav');

    const updateNav = () => {
      if (!nav) return;
      const current = window.scrollY;
      nav.classList.toggle('scrolled', current > 32);
      nav.classList.toggle('nav-compact', current > 72 && current >= lastScrollY);
      if (current < 40) nav.classList.remove('nav-compact');
      lastScrollY = Math.max(current, 0);
    };

    const testimonials = document.querySelector('.testimonials');
    const faq = document.querySelector('.faq');
    const cta = document.querySelector('.cta');
    if (testimonials && faq && cta) cta.before(testimonials, faq);

    const observer = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) entry.target.classList.add('visible');
      });
    }, { threshold: 0.08 });

    document.querySelectorAll('.fade-in, .feature-card, .module-card, .pricing-card, .security-item, .blog-card, .stat-item, .testimonial-card').forEach((el) => {
      el.classList.add('fade-in');
      observer.observe(el);
    });

    const counterObserver = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (!entry.isIntersecting) return;
        const el = entry.target;
        const target = parseInt(el.dataset.target || '0', 10);
        const duration = 2000;
        const start = performance.now();
        const update = (now) => {
          const progress = Math.min((now - start) / duration, 1);
          el.textContent = String(Math.floor(progress * target));
          if (progress < 1) requestAnimationFrame(update);
        };
        requestAnimationFrame(update);
        counterObserver.unobserve(el);
      });
    }, { threshold: 0.5 });

    document.querySelectorAll('.counter').forEach((el) => counterObserver.observe(el));

    const onClick = (event) => {
      const link = event.target.closest('a');
      if (link) {
        const target = routeFromHref(link.getAttribute('href'));
        if (target) {
          event.preventDefault();
          window.history.pushState({}, '', target.href);
          setRoute(target.route);
          window.setTimeout(() => {
            if (target.hash) document.querySelector(target.hash)?.scrollIntoView({ behavior: 'smooth' });
            else window.scrollTo({ top: 0, behavior: 'smooth' });
          }, 0);
          return;
        }
      }

      const hamburger = event.target.closest('.nav-hamburger');
      if (hamburger) {
        document.querySelector('.nav-links')?.classList.toggle('show');
        return;
      }

      const tabButton = event.target.closest('.feature-tabs-nav button');
      if (tabButton?.dataset.tab) {
        document.querySelectorAll('.feature-tabs-nav button').forEach((button) => button.classList.remove('active'));
        document.querySelectorAll('.feature-tab-content').forEach((content) => content.classList.remove('active'));
        tabButton.classList.add('active');
        document.getElementById(tabButton.dataset.tab)?.classList.add('active');
        return;
      }

      const faqQuestion = event.target.closest('.faq-question');
      if (faqQuestion) {
        const item = faqQuestion.parentElement;
        const isOpen = item.classList.contains('open');
        document.querySelectorAll('.faq-item.open').forEach((openItem) => openItem.classList.remove('open'));
        if (!isOpen) item.classList.add('open');
        return;
      }

      const dot = event.target.closest('.testimonial-dots button');
      if (dot) {
        const idx = parseInt(dot.dataset.index || '0', 10);
        const track = document.getElementById('testimonialTrack');
        if (track?.children[idx]) {
          track.scrollTo({ left: track.children[idx].offsetLeft - track.offsetLeft, behavior: 'smooth' });
          document.querySelectorAll('.testimonial-dots button').forEach((button) => button.classList.remove('active'));
          dot.classList.add('active');
        }
        return;
      }

      if (event.target.closest('#chatToggle')) {
        document.getElementById('chatWindow')?.classList.toggle('open');
        return;
      }

      if (event.target.closest('#chatSend')) {
        sendChatMessage();
      }
    };

    const onKeyDown = (event) => {
      if (event.target?.id === 'chatInput' && event.key === 'Enter') sendChatMessage();
    };

    const onTestimonialScroll = () => {
      const track = document.getElementById('testimonialTrack');
      if (!track?.children[0]) return;
      const idx = Math.round(track.scrollLeft / track.children[0].offsetWidth);
      document.querySelectorAll('.testimonial-dots button').forEach((button, index) => button.classList.toggle('active', index === idx));
    };

    const sendChatMessage = () => {
      const input = document.getElementById('chatInput');
      const messages = document.getElementById('chatMessages');
      const message = input?.value.trim();
      if (!input || !messages || !message) return;

      const userMessage = document.createElement('div');
      userMessage.className = 'chatbot-msg user';
      userMessage.textContent = message;
      messages.appendChild(userMessage);
      input.value = '';

      window.setTimeout(() => {
        const responses = [
          'Obrigado pelo contato! Um especialista Tolmora vai retornar em ate 2 horas uteis.',
          'Otima pergunta! Voce pode agendar uma demo gratuita em tolmora.com.br/demo',
          'Sim! Oferecemos 14 dias de trial sem compromisso. Quer agendar?',
          'O Tolmora oferece todos os modulos de RH e DP integrados. Qual area te interessa mais?'
        ];
        const botMessage = document.createElement('div');
        botMessage.className = 'chatbot-msg bot';
        botMessage.textContent = responses[Math.floor(Math.random() * responses.length)];
        messages.appendChild(botMessage);
        messages.scrollTop = messages.scrollHeight;
      }, 800);

      messages.scrollTop = messages.scrollHeight;
    };

    const track = document.getElementById('testimonialTrack');
    window.addEventListener('scroll', updateNav, { passive: true });
    document.addEventListener('click', onClick);
    document.addEventListener('keydown', onKeyDown);
    track?.addEventListener('scroll', onTestimonialScroll);
    updateNav();

    return () => {
      window.removeEventListener('scroll', updateNav);
      document.removeEventListener('click', onClick);
      document.removeEventListener('keydown', onKeyDown);
      track?.removeEventListener('scroll', onTestimonialScroll);
      observer.disconnect();
      counterObserver.disconnect();
    };
  }, [pageHtml, setRoute]);
}

function App() {
  const [route, setRoute] = useState(currentRoute);
  const rootRef = useRef(null);
  const page = pages[route] || pages['/'];
  const pageHtml = page.html;

  useMemo(() => {
    document.title = page.title;
  }, [page.title]);

  useThreeScene(pageHtml);
  usePageInteractions(pageHtml, setRoute);

  useEffect(() => {
    const onLocationChange = () => setRoute(currentRoute());
    window.addEventListener('popstate', onLocationChange);
    return () => window.removeEventListener('popstate', onLocationChange);
  }, []);

  useEffect(() => {
    const hash = window.location.hash;
    if (hash && !hash.startsWith('#/')) {
      window.setTimeout(() => document.querySelector(hash)?.scrollIntoView({ behavior: 'smooth' }), 0);
    }
  }, [pageHtml]);

  return <div ref={rootRef} dangerouslySetInnerHTML={{ __html: pageHtml }} />;
}

createRoot(document.getElementById('root')).render(<App />);
