import React from "https://esm.sh/react@18.3.1";
import { createRoot } from "https://esm.sh/react-dom@18.3.1/client";
import { AnimatePresence, motion } from "https://esm.sh/framer-motion@11.18.2?deps=react@18.3.1,react-dom@18.3.1";
import {
  Activity,
  ArrowRight,
  Box,
  Cloud,
  Code2,
  Gauge,
  LayoutDashboard,
  Layers3,
  Menu,
  ServerCog,
  Sparkles,
  Triangle
} from "https://esm.sh/lucide-react@0.468.0?deps=react@18.3.1";

const navItems = [
  { label: "Serviços", href: "#servicos" },
  { label: "Soluções", href: "#solucoes" },
  { label: "Portfólio", href: "#portfolio" },
  { label: "Processo", href: "#processo" },
  { label: "Sobre", href: "#sobre" }
];

const clients = [
  { name: "Acme", Icon: Box },
  { name: "Pulse", Icon: Activity },
  { name: "Vertex", Icon: Triangle },
  { name: "Cloudly", Icon: Cloud },
  { name: "Nexus", Icon: Layers3 },
  { name: "Orbit", Icon: Sparkles }
];

const services = [
  {
    title: "Web Design Estratégico",
    Icon: LayoutDashboard,
    summary: "Interfaces intuitivas, rápidas e memoráveis para transformar atenção em ação.",
    detail: "Criamos jornadas visuais com hierarquia clara, narrativa persuasiva e foco em microconversões. Cada bloco da página é desenhado para orientar o usuário até a próxima decisão.",
    proof: "Interfaces que convertem: +25% na retenção de usuários.",
    cta: "Ver Estudo de Caso"
  },
  {
    title: "Desenvolvimento Web Moderno",
    Icon: Code2,
    summary: "Arquitetura rápida, segura e escalável para sites de alta conversão.",
    detail: "Desenvolvemos componentes responsivos, integrações limpas e bases preparadas para analytics, testes e evolução contínua sem sacrificar velocidade ou estabilidade.",
    proof: "Stack moderna (React/Next.js) para sites ultra-rápidos e seguros.",
    cta: "Pedir Orçamento"
  },
  {
    title: "SEO & Performance",
    Icon: Gauge,
    summary: "Otimização técnica para tráfego orgânico, velocidade e rastreabilidade.",
    detail: "Ajustamos semântica, renderização, imagens, cache e Core Web Vitals para que a página seja encontrada, carregue rápido e sustente campanhas com maior eficiência.",
    proof: "Aumento médio de 40% no tráfego orgânico dos nossos clientes.",
    cta: "Falar com Consultor",
    seal: true
  },
  {
    title: "Hospedagem & Manutenção",
    Icon: ServerCog,
    summary: "Monitoramento, segurança e suporte contínuo para manter sua operação no ar.",
    detail: "Cuidamos de disponibilidade, backups, atualizações e observabilidade para reduzir risco operacional e preservar vendas durante campanhas e picos de acesso.",
    proof: "Disponibilidade de 99.9% e monitoramento 24/7 para que você nunca perca uma venda.",
    cta: "Pedir Orçamento"
  }
];

function BrandMark({ compact = false }) {
  return (
    <img
      src="./src/assets/modulo-logo.png"
      className={compact ? "h-10 w-10 object-contain" : "h-[210px] w-[210px] object-contain sm:h-[260px] sm:w-[260px]"}
      aria-label="Modulo"
      alt="Modulo"
      draggable="false"
    />
  );
}

function HeaderLogo() {
  return (
    <img
      src="./src/assets/modulo-secondary-logo.png"
      className="h-8 w-auto object-contain sm:h-9 lg:h-10"
      aria-label="Modulo"
      alt="Modulo"
      draggable="false"
    />
  );
}

function Header() {
  return (
    <header className="sticky top-0 z-50 border-b border-white/[0.06] bg-black/55 backdrop-blur-2xl">
      <nav className="mx-auto flex h-20 max-w-[1480px] items-center justify-between px-6 sm:px-10 lg:h-24">
        <a href="#hero" className="shrink-0" aria-label="Modulo início">
          <HeaderLogo />
        </a>

        <div className="hidden items-center gap-12 text-[15px] font-semibold text-white/90 lg:flex">
          {navItems.map((item) => (
            <a key={item.label} href={item.href}>
              <span className="nav-link">{item.label}</span>
            </a>
          ))}
        </div>

        <div className="flex items-center gap-3">
          <a
            href="#contato"
            className="group hidden items-center gap-3 rounded-lg border border-white/15 bg-white/[0.035] px-5 py-3 text-sm font-semibold text-white shadow-[inset_0_1px_0_rgba(255,255,255,0.08)] backdrop-blur-xl transition hover:border-white/30 hover:bg-white/[0.08] sm:flex"
          >
            Vamos conversar
            <ArrowRight className="h-4 w-4 transition group-hover:translate-x-1" />
          </a>
          <button className="grid h-11 w-11 place-items-center rounded-lg border border-white/15 bg-white/[0.035] text-white lg:hidden" aria-label="Abrir menu">
            <Menu className="h-5 w-5" />
          </button>
        </div>
      </nav>
    </header>
  );
}

function FloatingLogo() {
  const [showStaticLogo, setShowStaticLogo] = React.useState(false);
  const [videoEnded, setVideoEnded] = React.useState(false);
  const [showVideo, setShowVideo] = React.useState(true);
  const overlapStarted = React.useRef(false);
  const introFinished = React.useRef(false);
  const startLogoOverlap = () => {
    if (overlapStarted.current) return;
    overlapStarted.current = true;
    setShowStaticLogo(true);
  };
  const finishIntro = () => {
    if (introFinished.current) return;
    introFinished.current = true;
    startLogoOverlap();
    setVideoEnded(true);
    window.setTimeout(() => setShowVideo(false), 180);
  };
  const transition = {
    duration: 4.8,
    repeat: Infinity,
    ease: "easeInOut",
    times: [0, 0.5, 1]
  };
  const glowDelay = 3;

  return (
    <div className="relative mx-auto flex min-h-[330px] w-full items-center justify-center sm:min-h-[410px] lg:min-h-[520px]">
      <motion.div
        className="absolute bottom-[20%] h-[2px] w-[52%] max-w-[340px] rounded-full bg-gradient-to-r from-transparent via-[#ff5f2e] via-45% to-transparent blur-[1px]"
        initial={{ opacity: 0, scaleX: 0.32 }}
        animate={videoEnded ? { opacity: [1, 0.58, 1], scaleX: [1.08, 0.78, 1.08] } : { opacity: 0, scaleX: 0.32 }}
        transition={videoEnded ? { ...transition, delay: glowDelay } : { duration: 0.2 }}
      />
      <motion.div
        className="absolute bottom-[20%] h-9 w-[48%] max-w-[330px] rounded-t-full bg-gradient-to-r from-transparent via-[#ff2f7f] to-[#8a2be2] blur-xl"
        initial={{ opacity: 0, scale: 0.58 }}
        animate={videoEnded ? { opacity: [0.86, 0.36, 0.86], scale: [1.04, 0.82, 1.04] } : { opacity: 0, scale: 0.58 }}
        transition={videoEnded ? { ...transition, delay: glowDelay } : { duration: 0.2 }}
      />
      <motion.div
        className="absolute bottom-[20%] h-24 w-[50%] max-w-[340px] rounded-t-full bg-[radial-gradient(ellipse_at_50%_100%,rgba(255,95,46,0.42),rgba(226,31,182,0.26)_44%,transparent_72%)] blur-2xl"
        initial={{ opacity: 0, scale: 0.6 }}
        animate={videoEnded ? { opacity: 0.62, scale: 0.88 } : { opacity: 0, scale: 0.6 }}
        transition={{ duration: 2, delay: glowDelay, ease: "easeIn" }}
      />

      {showVideo ? (
        <motion.video
          className="absolute h-[270px] w-[270px] object-contain sm:h-[345px] sm:w-[345px]"
          src="./src/assets/modulo-logo-animation.mp4"
          autoPlay
          muted
          playsInline
          preload="auto"
          initial={{ opacity: 1, scale: 1 }}
          animate={videoEnded ? { opacity: 0, scale: 0.985 } : { opacity: 1, scale: 1 }}
          transition={{ duration: 0.18, ease: "easeOut" }}
          onEnded={finishIntro}
          onTimeUpdate={(event) => {
            const video = event.currentTarget;
            if (Number.isFinite(video.duration) && video.duration > 0 && video.currentTime >= video.duration - 0.1) {
              startLogoOverlap();
            }
          }}
          onLoadedMetadata={(event) => {
            const video = event.currentTarget;
            if (Number.isFinite(video.duration) && video.duration > 0) {
              window.setTimeout(startLogoOverlap, Math.max(0, video.duration * 1000 - 100));
              window.setTimeout(finishIntro, video.duration * 1000 + 80);
            }
          }}
          onError={finishIntro}
          aria-label="Animação do logo Modulo"
        />
      ) : null}

      {showStaticLogo ? (
        <motion.div
          className="absolute"
          initial={{ opacity: 0, scale: 0.985, y: 0 }}
          animate={{ opacity: 1, scale: 1, y: [0, -20, 0] }}
          transition={{
            opacity: { duration: 0.18, ease: "easeOut" },
            scale: { duration: 0.18, ease: "easeOut" },
            y: { ...transition, delay: videoEnded ? 0 : 0.1 }
          }}
        >
          <motion.div
            className="pointer-events-none absolute -inset-10 z-0 rounded-[64px] bg-[radial-gradient(circle,rgba(255,95,46,0.34)_0%,rgba(226,31,182,0.28)_42%,rgba(138,43,226,0.2)_58%,transparent_76%)] blur-2xl"
            initial={{ opacity: 0, scale: 0.82 }}
            animate={videoEnded ? { opacity: 0.86, scale: 1 } : { opacity: 0, scale: 0.82 }}
            transition={{ duration: 2, delay: glowDelay, ease: "easeIn" }}
          />
          <span className="relative z-10 block">
            <BrandMark />
          </span>
        </motion.div>
      ) : null}
    </div>
  );
}

function SocialProof() {
  const row = [...clients, ...clients];

  return (
    <section className="mx-auto w-full max-w-[1480px] px-6 pb-16 sm:px-10 lg:pb-20" aria-labelledby="social-proof">
      <h2 id="social-proof" className="mb-4 text-xs font-semibold uppercase tracking-[0.08em] text-white/48">
        Empresas que confiam em nosso trabalho
      </h2>
      <div className="overflow-hidden border-t border-white/10 pt-8">
        <div className="logo-marquee flex w-max items-center gap-16 pr-16">
          {row.map(({ name, Icon }, index) => (
            <a
              key={`${name}-${index}`}
              href="#portfolio"
              className="client-logo group flex min-w-40 items-center gap-3 text-white/50 opacity-50 grayscale transition duration-300 hover:text-white hover:opacity-100 hover:grayscale-0"
            >
              <Icon className="h-8 w-8 transition group-hover:text-[#ff5f2e]" strokeWidth={1.8} />
              <span className="text-2xl font-bold">{name}</span>
            </a>
          ))}
        </div>
      </div>
    </section>
  );
}

function ServiceIcon({ Icon }) {
  return (
    <div className="service-icon-tile grid h-20 w-20 shrink-0 place-items-center rounded-lg border border-white/10 shadow-[inset_0_1px_0_rgba(255,255,255,0.08)] sm:h-24 sm:w-24">
      <Icon className="h-10 w-10 text-white" strokeWidth={1.8} />
    </div>
  );
}

function ServiceCard({ service, isOpen, onToggle }) {
  const Icon = service.Icon;

  return (
    <motion.article
      layout
      onClick={onToggle}
      className="service-card cursor-pointer overflow-hidden rounded-lg border border-white/14 bg-black/38 p-5 backdrop-blur-2xl transition hover:border-white/28"
    >
      <motion.div layout className="flex items-start gap-5">
        <ServiceIcon Icon={Icon} />
        <div className="min-w-0 flex-1">
          <h3 className="text-xl font-semibold leading-tight text-white sm:text-2xl">{service.title}</h3>
          <p className="mt-3 text-sm leading-6 text-white/66">{service.summary}</p>
        </div>
        <ArrowRight className={["mt-2 h-5 w-5 shrink-0 text-white/65 transition", isOpen ? "rotate-90" : ""].join(" ")} />
      </motion.div>

      <AnimatePresence initial={false}>
        {isOpen ? (
          <motion.div
            layout
            initial={{ height: 0, opacity: 0 }}
            animate={{ height: "auto", opacity: 1 }}
            exit={{ height: 0, opacity: 0 }}
            transition={{ duration: 0.36, ease: "easeInOut" }}
            className="overflow-hidden"
          >
            <div className="mt-6 border-t border-white/10 pt-6">
              <div className="flex flex-col gap-5 sm:flex-row sm:items-start sm:justify-between">
                <div>
                  <div className="flex items-center gap-3">
                    <Icon className="h-5 w-5 text-[#ff5f2e]" />
                    <h4 className="text-lg font-semibold text-white">{service.title}</h4>
                  </div>
                  <p className="mt-4 text-sm leading-7 text-white/66">{service.detail}</p>
                  <p className="mt-4 text-sm font-semibold leading-7 text-white">{service.proof}</p>
                </div>
                {service.seal ? (
                  <div className="performance-seal shrink-0 rounded-full border border-white/60 px-5 py-4 text-center text-[0.7rem] font-extrabold uppercase leading-4 tracking-[0.08em] text-white">
                    Selado de Performance e Velocidade
                    <br />
                    Carregamento &lt; 2s
                  </div>
                ) : null}
              </div>
            </div>
          </motion.div>
        ) : null}
      </AnimatePresence>
    </motion.article>
  );
}

function ServicesSection() {
  const [openIndex, setOpenIndex] = React.useState(-1);

  return (
    <section id="servicos" className="services-section relative isolate overflow-hidden px-6 py-24 sm:px-10 lg:py-32">
      <div className="services-waves pointer-events-none absolute inset-0 -z-10" />
      <div className="mx-auto max-w-[1180px]">
        <div className="mx-auto max-w-4xl text-center">
          <p className="text-sm font-semibold uppercase tracking-[0.12em] text-white/55">Nossos Serviços</p>
          <h2 className="mt-4 text-4xl font-semibold leading-tight text-white sm:text-5xl lg:text-6xl">
            Do Conceito à Conversão
          </h2>
        </div>

        <motion.div layout className="mt-12 grid items-start gap-4 lg:grid-cols-2">
          {services.map((service, index) => (
            <ServiceCard
              key={service.title}
              service={service}
              isOpen={openIndex === index}
              onToggle={() => setOpenIndex(openIndex === index ? -1 : index)}
            />
          ))}
        </motion.div>

        <p className="mx-auto mt-10 max-w-3xl text-center text-sm font-medium leading-7 text-white/62">
          Especialistas em landing pages para infoprodutores e sites corporativos para indústrias.
        </p>
      </div>
    </section>
  );
}

function Hero() {
  return (
    <main id="hero" className="relative isolate overflow-hidden">
      <div className="hero-vignette pointer-events-none absolute inset-0 -z-10" />

      <section className="mx-auto grid min-h-[calc(100vh-5rem)] max-w-[1480px] grid-cols-1 items-center gap-4 px-6 pb-10 pt-12 sm:px-10 lg:grid-cols-[1fr_1.08fr_1fr] lg:gap-10 lg:pb-16 lg:pt-20">
        <div className="hero-copy order-1 text-center lg:text-left">
          <p className="hero-title mx-auto max-w-[440px] text-4xl font-medium leading-[1.2] sm:text-5xl lg:mx-0 lg:text-[3.25rem] xl:text-[3.65rem]">
            Seu
            <br />
            negócio
            <br />
            sem
            <br />
            limites.
          </p>
          <div className="mt-12 hidden items-center gap-4 lg:flex">
            <a
              href="#contato"
              className="group flex min-h-12 items-center justify-center gap-3 rounded-lg bg-gradient-to-r from-[#ff5f2e] to-[#8a2be2] px-6 text-sm font-bold text-white shadow-[0_12px_36px_rgba(255,95,46,0.28)] transition hover:translate-y-[-1px] hover:shadow-[0_16px_46px_rgba(138,43,226,0.32)]"
            >
              Quero um site incrível
              <ArrowRight className="h-4 w-4 transition group-hover:translate-x-1" />
            </a>
            <a href="#portfolio" className="ghost-portfolio group flex min-h-12 items-center justify-center gap-3 px-4 text-sm font-bold text-white">
              Ver portfólio
              <ArrowRight className="h-4 w-4 transition group-hover:translate-x-1" />
            </a>
          </div>
        </div>

        <div className="order-2">
          <FloatingLogo />
        </div>

        <div className="order-3 mx-auto max-w-[470px] text-center lg:text-left">
          <h1 className="text-2xl font-medium leading-[1.24] text-white sm:text-3xl lg:text-[1.8rem] xl:text-[2.05rem]">
            Sites que impulsionam{" "}
            <span className="text-gradient">negócios e geram</span> resultados reais.
          </h1>
          <p className="mt-7 text-sm leading-7 text-white/55 sm:text-[0.95rem]">
            Converta visitantes em clientes fiéis com design inteligente, UX comportamental e estratégias de conversão que funcionam de verdade.
          </p>
        </div>

        <div className="order-4 flex flex-col items-center gap-4 pt-3 sm:flex-row sm:justify-center lg:hidden">
          <a
            href="#contato"
            className="group flex min-h-12 items-center justify-center gap-3 rounded-lg bg-gradient-to-r from-[#ff5f2e] to-[#8a2be2] px-6 text-sm font-bold text-white shadow-[0_12px_36px_rgba(255,95,46,0.28)] transition hover:translate-y-[-1px] hover:shadow-[0_16px_46px_rgba(138,43,226,0.32)]"
          >
            Quero um site incrível
            <ArrowRight className="h-4 w-4 transition group-hover:translate-x-1" />
          </a>
          <a href="#portfolio" className="ghost-portfolio group flex min-h-12 items-center justify-center gap-3 px-4 text-sm font-bold text-white">
            Ver portfólio
            <ArrowRight className="h-4 w-4 transition group-hover:translate-x-1" />
          </a>
        </div>
      </section>

      <SocialProof />

      <ServicesSection />
      <section id="solucoes" className="sr-only">
        Soluções
      </section>
      <section id="portfolio" className="sr-only">
        Portfólio
      </section>
      <section id="processo" className="sr-only">
        Processo
      </section>
      <section id="sobre" className="sr-only">
        Sobre
      </section>
      <section id="contato" className="sr-only">
        Contato
      </section>
    </main>
  );
}

function App() {
  return (
    <div className="min-h-screen bg-black text-white antialiased">
      <Header />
      <Hero />
    </div>
  );
}

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