import { createFileRoute } from "@tanstack/react-router";
import { useEffect, useRef, useState } from "react";
import { motion, useScroll, useTransform, useMotionValue, useSpring } from "framer-motion";
import {
  Menu, X, ArrowRight, Mail, Phone, MapPin, Code2, Smartphone,
  Layout, Sparkles, Zap, Palette, Globe, Github, Linkedin, Send,
  Brush, LifeBuoy, Atom, FileType, Wind, Server, Database, FileCode2,
  Layers, GitBranch, Wrench, Workflow,
} from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import veigasImg from "@/assets/proj-veigas.jpg";
import fitflowImg from "@/assets/proj-fitflow.jpg";
import silvaImg from "@/assets/proj-silva.jpg";
import perdidosImg from "@/assets/proj-perdidos.jpg";
import ocrImg from "@/assets/proj-ocr.jpg";
import motoImg from "@/assets/proj-moto.jpg";

export const Route = createFileRoute("/")({
  head: () => ({
    meta: [
      { title: "pg Web e App Designer — Paulo Gomes, Web Design em Almada" },
      { name: "description", content: "Paulo Gomes — Web Designer especializado em sites e aplicações web/mobile modernos, com foco em performance, 3D e experiências imersivas." },
      { property: "og:title", content: "pg Web e App Designer" },
      { property: "og:description", content: "Sites e aplicações web/mobile com design moderno, 3D e dark mode." },
    ],
  }),
  component: Index,
});

const NAV = [
  { href: "#inicio", label: "Início" },
  { href: "#sobre", label: "Sobre" },
  { href: "#servicos", label: "Serviços" },
  { href: "#projetos", label: "Projetos" },
  { href: "#tecnologias", label: "Ferramentas" },
  { href: "/politica-privacidade", label: "Política de Privacidade" },
  { href: "/termos-condicoes", label: "Termos e Condições" },
  { href: "#contacto", label: "Contacto" },
];

function Index() {
  return (
    <div className="relative min-h-screen overflow-x-hidden bg-background text-foreground">
      <BackgroundFX />
      <Header />
      <main className="relative z-10">
        <Hero />
        <Sobre />
        <Servicos />
        <Projetos />
        <Tecnologias />
        <Contacto />
      </main>
      <Footer />
    </div>
  );
}

/* ---------------- Background FX ---------------- */
function Floating3DShape({
  className,
  shape = "cube",
  duration = 18,
}: {
  className?: string;
  shape?: "cube" | "pyramid" | "ring" | "sphere";
  duration?: number;
}) {
  if (shape === "ring") {
    return (
      <div className={`pointer-events-none absolute perspective-1000 ${className ?? ""}`}>
        <motion.div
          animate={{ rotateX: [0, 360], rotateY: [0, 360] }}
          transition={{ duration, repeat: Infinity, ease: "linear" }}
          className="preserve-3d h-full w-full"
        >
          <div className="absolute inset-0 rounded-full border-2 border-primary/40" style={{ transform: "rotateX(70deg)" }} />
          <div className="absolute inset-0 rounded-full border-2 border-accent/40" style={{ transform: "rotateY(70deg)" }} />
          <div className="absolute inset-0 rounded-full border border-primary/30" />
        </motion.div>
      </div>
    );
  }
  if (shape === "sphere") {
    return (
      <div className={`pointer-events-none absolute perspective-1000 ${className ?? ""}`}>
        <motion.div
          animate={{ rotateY: [0, 360], y: [0, -20, 0] }}
          transition={{ rotateY: { duration, repeat: Infinity, ease: "linear" }, y: { duration: 6, repeat: Infinity, ease: "easeInOut" } }}
          className="preserve-3d h-full w-full rounded-full"
          style={{
            background: "radial-gradient(circle at 30% 30%, oklch(0.78 0.16 195 / 0.9), oklch(0.7 0.22 330 / 0.6) 60%, oklch(0.2 0.05 270 / 0.2))",
            boxShadow: "inset -20px -20px 50px oklch(0.05 0.05 270 / 0.6), 0 30px 60px -10px oklch(0.78 0.16 195 / 0.4)",
          }}
        />
      </div>
    );
  }
  if (shape === "pyramid") {
    const faces = [
      { transform: "rotateY(0deg) translateZ(40px)" },
      { transform: "rotateY(120deg) translateZ(40px)" },
      { transform: "rotateY(240deg) translateZ(40px)" },
    ];
    return (
      <div className={`pointer-events-none absolute perspective-1000 ${className ?? ""}`}>
        <motion.div
          animate={{ rotateX: [0, 360], rotateY: [0, 360], y: [0, -15, 0] }}
          transition={{ rotateX: { duration, repeat: Infinity, ease: "linear" }, rotateY: { duration: duration * 1.4, repeat: Infinity, ease: "linear" }, y: { duration: 5, repeat: Infinity, ease: "easeInOut" } }}
          className="preserve-3d relative h-full w-full"
        >
          {faces.map((f, i) => (
            <div
              key={i}
              className="absolute inset-0"
              style={{
                ...f,
                clipPath: "polygon(50% 0%, 0% 100%, 100% 100%)",
                background: i % 2 === 0
                  ? "linear-gradient(135deg, oklch(0.78 0.16 195 / 0.6), oklch(0.7 0.22 330 / 0.4))"
                  : "linear-gradient(135deg, oklch(0.7 0.22 330 / 0.6), oklch(0.78 0.16 195 / 0.4))",
                border: "1px solid oklch(1 0 0 / 0.15)",
              }}
            />
          ))}
        </motion.div>
      </div>
    );
  }
  // cube
  const size = 50;
  const sides = [
    { transform: `translateZ(${size}px)`, bg: "oklch(0.78 0.16 195 / 0.45)" },
    { transform: `rotateY(180deg) translateZ(${size}px)`, bg: "oklch(0.7 0.22 330 / 0.45)" },
    { transform: `rotateY(90deg) translateZ(${size}px)`, bg: "oklch(0.78 0.16 195 / 0.3)" },
    { transform: `rotateY(-90deg) translateZ(${size}px)`, bg: "oklch(0.7 0.22 330 / 0.3)" },
    { transform: `rotateX(90deg) translateZ(${size}px)`, bg: "oklch(0.78 0.16 195 / 0.55)" },
    { transform: `rotateX(-90deg) translateZ(${size}px)`, bg: "oklch(0.7 0.22 330 / 0.55)" },
  ];
  return (
    <div className={`pointer-events-none absolute perspective-1000 ${className ?? ""}`}>
      <motion.div
        animate={{ rotateX: [0, 360], rotateY: [0, 360], y: [0, -25, 0] }}
        transition={{ rotateX: { duration, repeat: Infinity, ease: "linear" }, rotateY: { duration: duration * 1.6, repeat: Infinity, ease: "linear" }, y: { duration: 7, repeat: Infinity, ease: "easeInOut" } }}
        className="preserve-3d relative h-full w-full"
      >
        {sides.map((s, i) => (
          <div
            key={i}
            className="absolute inset-0 border border-white/15"
            style={{ transform: s.transform, background: s.bg, boxShadow: "inset 0 0 30px oklch(0.05 0.05 270 / 0.5)" }}
          />
        ))}
      </motion.div>
    </div>
  );
}

function BackgroundFX() {
  const { scrollY } = useScroll();
  const y1 = useTransform(scrollY, [0, 2000], [0, -400]);
  const y2 = useTransform(scrollY, [0, 2000], [0, -200]);
  const y3 = useTransform(scrollY, [0, 3000], [0, -600]);
  return (
    <div className="pointer-events-none fixed inset-0 z-0">
      <div className="absolute inset-0 bg-hero" />
      <div className="absolute inset-0 grid-bg" />
      <motion.div
        style={{ y: y1 }}
        className="absolute -left-20 top-40 h-[420px] w-[420px] rounded-full bg-primary/30 blur-[140px] animate-pulse-glow"
      />
      <motion.div
        style={{ y: y2 }}
        className="absolute right-0 top-[60vh] h-[520px] w-[520px] rounded-full bg-accent/30 blur-[160px] animate-pulse-glow"
      />
      <motion.div
        style={{ y: y1 }}
        className="absolute left-1/3 top-[140vh] h-[360px] w-[360px] rounded-full bg-primary/20 blur-[120px]"
      />
      {/* Floating 3D objects */}
      <motion.div style={{ y: y2 }} className="absolute inset-0">
        <Floating3DShape shape="cube" className="right-[8%] top-[18vh] h-[100px] w-[100px]" duration={20} />
        <Floating3DShape shape="ring" className="left-[6%] top-[80vh] h-[180px] w-[180px]" duration={24} />
        <Floating3DShape shape="pyramid" className="right-[12%] top-[120vh] h-[120px] w-[120px]" duration={18} />
        <Floating3DShape shape="sphere" className="left-[10%] top-[200vh] h-[140px] w-[140px]" duration={26} />
        <Floating3DShape shape="cube" className="right-[20%] top-[260vh] h-[80px] w-[80px]" duration={22} />
      </motion.div>
      <motion.div style={{ y: y3 }} className="absolute inset-0">
        <Floating3DShape shape="ring" className="right-[30%] top-[40vh] h-[120px] w-[120px]" duration={30} />
        <Floating3DShape shape="pyramid" className="left-[25%] top-[160vh] h-[90px] w-[90px]" duration={22} />
        <Floating3DShape shape="sphere" className="right-[5%] top-[230vh] h-[100px] w-[100px]" duration={28} />
      </motion.div>
    </div>
  );
}

/* ---------------- Header ---------------- */
function Header() {
  const [open, setOpen] = useState(false);
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 20);
    window.addEventListener("scroll", onScroll);
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return (
    <header
      className={`fixed inset-x-0 top-0 z-50 transition-all duration-300 ${
        scrolled ? "glass border-b border-border/50" : "bg-transparent"
      }`}
    >
      <div className="mx-auto flex max-w-7xl items-center justify-between px-6 py-4">
        <a href="#inicio" className="group flex items-center gap-2">
          <div className="relative h-9 w-9 rounded-lg bg-gradient-primary shadow-glow transition-transform group-hover:scale-110">
            <span className="absolute inset-0 flex items-center justify-center font-display text-sm font-bold text-primary-foreground">PG</span>
          </div>
          <div className="flex flex-col leading-tight">
            <span className="font-display text-sm font-semibold tracking-tight">pg Web e App Designer</span>
            <span className="text-[10px] uppercase tracking-[0.2em] text-muted-foreground">Paulo Gomes</span>
          </div>
        </a>
        <nav className="hidden items-center gap-1 md:flex">
          {NAV.map((n) => {
            const isExternal = n.href.startsWith("/");
            return (
              <a
                key={n.href}
                href={n.href}
                {...(isExternal ? { target: "_blank", rel: "noopener noreferrer" } : {})}
                className="relative px-3 py-2 text-sm text-muted-foreground transition-colors hover:text-foreground"
              >
                {n.label}
              </a>
            );
          })}
          <a
            href="#contacto"
            className="ml-2 inline-flex items-center gap-2 rounded-full bg-gradient-primary px-4 py-2 text-sm font-medium text-primary-foreground shadow-glow transition-transform hover:scale-105"
          >
            Vamos conversar <ArrowRight className="h-4 w-4" />
          </a>
        </nav>
        <button onClick={() => setOpen((v) => !v)} className="md:hidden rounded-md p-2 text-foreground" aria-label="Menu">
          {open ? <X /> : <Menu />}
        </button>
      </div>
      {open && (
        <div className="md:hidden border-t border-border/50 glass">
          <div className="flex flex-col p-4 gap-1">
            {NAV.map((n) => {
              const isExternal = n.href.startsWith("/");
              return (
                <a
                  key={n.href}
                  href={n.href}
                  {...(isExternal ? { target: "_blank", rel: "noopener noreferrer" } : {})}
                  onClick={() => setOpen(false)}
                  className="rounded-md px-3 py-2 text-sm text-muted-foreground hover:bg-muted/40 hover:text-foreground"
                >
                  {n.label}
                </a>
              );
            })}
          </div>
        </div>
      )}
    </header>
  );
}

/* ---------------- Hero ---------------- */
function Hero() {
  const ref = useRef<HTMLDivElement>(null);
  const { scrollYProgress } = useScroll({ target: ref, offset: ["start start", "end start"] });
  const y = useTransform(scrollYProgress, [0, 1], [0, 200]);
  const opacity = useTransform(scrollYProgress, [0, 0.8], [1, 0]);

  return (
    <section id="inicio" ref={ref} className="relative flex min-h-screen items-center pt-28">
      <motion.div style={{ y, opacity }} className="mx-auto grid max-w-7xl gap-12 px-6 lg:grid-cols-[1.1fr_0.9fr] lg:items-center">
        <div>
          <motion.div
            initial={{ opacity: 0, y: 24 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.6 }}
            className="inline-flex items-center gap-2 rounded-full border border-border bg-card/40 px-4 py-1.5 text-xs uppercase tracking-[0.2em] text-muted-foreground backdrop-blur"
          >
            <span className="h-1.5 w-1.5 animate-pulse rounded-full bg-primary" />
            Disponível para novos projetos
          </motion.div>
          <motion.h1
            initial={{ opacity: 0, y: 24 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.7, delay: 0.05 }}
            className="mt-6 font-display text-5xl font-bold leading-[1.05] sm:text-6xl lg:text-7xl"
          >
            Desenho <span className="text-gradient">sites</span> e <span className="text-gradient">apps</span> que se sentem do futuro.
          </motion.h1>
          <motion.p
            initial={{ opacity: 0, y: 24 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.7, delay: 0.15 }}
            className="mt-6 max-w-xl text-lg text-muted-foreground"
          >
            Sou o Paulo Gomes, web designer em Almada. Crio experiências modernas, com toque 3D, animações fluidas e foco total na performance — tanto em web como em mobile.
          </motion.p>
          <motion.div
            initial={{ opacity: 0, y: 24 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.7, delay: 0.25 }}
            className="mt-8 flex flex-wrap gap-3"
          >
            <a href="#projetos" className="inline-flex items-center gap-2 rounded-full bg-gradient-primary px-6 py-3 text-sm font-medium text-primary-foreground shadow-glow transition-transform hover:scale-105">
              Ver projetos <ArrowRight className="h-4 w-4" />
            </a>
            <a href="#contacto" className="inline-flex items-center gap-2 rounded-full border border-border bg-card/40 px-6 py-3 text-sm font-medium text-foreground backdrop-blur transition-colors hover:bg-card">
              Iniciar projeto
            </a>
          </motion.div>
          <div className="mt-12 grid max-w-md grid-cols-3 gap-6">
            {[
              { n: "3+", l: "Anos de experiência" },
              { n: "8+", l: "Projetos entregues" },
              { n: "5+", l: "Clientes satisfeitos" },
            ].map((s) => (
              <div key={s.l}>
                <div className="font-display text-2xl font-bold text-gradient">{s.n}</div>
                <div className="mt-1 text-xs text-muted-foreground">{s.l}</div>
              </div>
            ))}
          </div>
        </div>

        <HeroVisual />
      </motion.div>

      <a href="#sobre" className="absolute bottom-8 left-1/2 -translate-x-1/2 text-xs text-muted-foreground hover:text-foreground transition-colors">
        <div className="flex flex-col items-center gap-2">
          <span className="uppercase tracking-[0.3em]">Scroll</span>
          <div className="h-10 w-[2px] bg-gradient-to-b from-primary to-transparent" />
        </div>
      </a>
    </section>
  );
}

function HeroVisual() {
  const ref = useRef<HTMLDivElement>(null);
  const rx = useMotionValue(0);
  const ry = useMotionValue(0);
  const srx = useSpring(rx, { stiffness: 120, damping: 18 });
  const sry = useSpring(ry, { stiffness: 120, damping: 18 });

  const onMove = (e: React.MouseEvent) => {
    const r = ref.current!.getBoundingClientRect();
    const x = (e.clientX - r.left) / r.width - 0.5;
    const y = (e.clientY - r.top) / r.height - 0.5;
    ry.set(x * 24);
    rx.set(-y * 24);
  };
  const onLeave = () => { rx.set(0); ry.set(0); };

  return (
    <div ref={ref} onMouseMove={onMove} onMouseLeave={onLeave} className="perspective-1000 relative mx-auto aspect-square w-full max-w-[520px]">
      <motion.div style={{ rotateX: srx, rotateY: sry }} className="preserve-3d relative h-full w-full">
        {/* glow orb */}
        <div className="absolute inset-12 rounded-full bg-gradient-primary opacity-40 blur-3xl animate-pulse-glow" />
        {/* ring */}
        <div className="absolute inset-0 rounded-full border border-primary/30 animate-spin-slow" style={{ transform: "translateZ(20px)" }} />
        <div className="absolute inset-6 rounded-full border border-accent/30 animate-spin-slow" style={{ animationDirection: "reverse", transform: "translateZ(40px)" }} />

        {/* center card */}
        <motion.div
          style={{ transform: "translateZ(80px)" }}
          className="absolute left-1/2 top-1/2 w-[78%] -translate-x-1/2 -translate-y-1/2 rounded-3xl bg-card-gradient p-8 shadow-elevated backdrop-blur"
        >
          <div className="flex items-center justify-between">
            <div className="flex gap-1.5">
              <span className="h-2.5 w-2.5 rounded-full bg-destructive/70" />
              <span className="h-2.5 w-2.5 rounded-full bg-accent/70" />
              <span className="h-2.5 w-2.5 rounded-full bg-primary/70" />
            </div>
            <Sparkles className="h-4 w-4 text-primary" />
          </div>
          <div className="mt-6 space-y-3">
            <div className="h-3 w-3/4 rounded bg-gradient-primary" />
            <div className="h-2 w-full rounded bg-muted" />
            <div className="h-2 w-5/6 rounded bg-muted" />
            <div className="h-2 w-2/3 rounded bg-muted" />
          </div>
          <div className="mt-6 grid grid-cols-3 gap-2">
            {[0, 1, 2].map((i) => (
              <div key={i} className="h-14 rounded-lg bg-gradient-to-br from-primary/20 to-accent/20 border border-border" />
            ))}
          </div>
          <div className="mt-6 inline-flex items-center gap-2 rounded-full bg-gradient-primary px-3 py-1.5 text-[11px] font-medium text-primary-foreground">
            Live preview <Zap className="h-3 w-3" />
          </div>
        </motion.div>

        {/* floating chips */}
        <motion.div style={{ transform: "translateZ(120px)" }} className="absolute -left-4 top-10 animate-float-slow rounded-2xl glass px-4 py-3 shadow-glow">
          <div className="flex items-center gap-2">
            <Code2 className="h-4 w-4 text-primary" />
            <span className="text-xs font-medium">React · TypeScript</span>
          </div>
        </motion.div>
        <motion.div style={{ transform: "translateZ(140px)" }} className="absolute -right-2 top-1/3 animate-float-slower rounded-2xl glass px-4 py-3 shadow-glow-accent">
          <div className="flex items-center gap-2">
            <Smartphone className="h-4 w-4 text-accent" />
            <span className="text-xs font-medium">Mobile First</span>
          </div>
        </motion.div>
        <motion.div style={{ transform: "translateZ(100px)" }} className="absolute -bottom-2 left-12 animate-float-slow rounded-2xl glass px-4 py-3">
          <div className="flex items-center gap-2">
            <Palette className="h-4 w-4 text-primary" />
            <span className="text-xs font-medium">UI · UX</span>
          </div>
        </motion.div>
      </motion.div>
    </div>
  );
}

/* ---------------- Sobre ---------------- */
function Sobre() {
  return (
    <Section id="sobre" eyebrow="Sobre" title="Mais do que pixels — soluções que funcionam.">
      <div className="grid gap-10 lg:grid-cols-2 lg:items-center">
        <motion.div
          initial={{ opacity: 0, y: 30 }} whileInView={{ opacity: 1, y: 0 }} viewport={{ once: true }} transition={{ duration: 0.6 }}
          className="space-y-5 text-muted-foreground"
        >
          <p>
            Sou um designer e developer com paixão por interfaces modernas. Junto sensibilidade visual a código limpo para construir sites e aplicações que comunicam, convertem e perduram.
          </p>
          <p>
            Trabalho de perto com cada cliente — desde a conceção à entrega — garantindo um produto à medida, acessível, rápido e preparado para crescer.
          </p>
          <div className="grid grid-cols-2 gap-4 pt-4">
            {[
              { icon: Layout, t: "Design centrado no utilizador" },
              { icon: Zap, t: "Performance acima de tudo" },
              { icon: Smartphone, t: "Responsivo e mobile-first" },
              { icon: Sparkles, t: "Atenção ao detalhe" },
            ].map((f) => (
              <div key={f.t} className="flex items-start gap-3 rounded-xl border border-border bg-card/40 p-4 backdrop-blur">
                <f.icon className="mt-0.5 h-5 w-5 shrink-0 text-primary" />
                <span className="text-sm text-foreground">{f.t}</span>
              </div>
            ))}
          </div>
        </motion.div>

        <motion.div
          initial={{ opacity: 0, scale: 0.95 }} whileInView={{ opacity: 1, scale: 1 }} viewport={{ once: true }} transition={{ duration: 0.7 }}
          className="relative"
        >
          <div className="absolute -inset-8 rounded-3xl bg-gradient-primary opacity-20 blur-3xl" />
          <div className="relative rounded-3xl border border-border bg-card-gradient p-8 shadow-elevated backdrop-blur">
            <div className="font-display text-sm uppercase tracking-[0.3em] text-muted-foreground">Processo</div>
            <ol className="mt-6 space-y-5">
              {[
                { n: "01", t: "Descoberta", d: "Compreender o negócio, os objetivos e o público." },
                { n: "02", t: "Design", d: "Wireframes, identidade visual e protótipos interativos." },
                { n: "03", t: "Desenvolvimento", d: "Código limpo, performante e responsivo." },
                { n: "04", t: "Lançamento & suporte", d: "Publicação, monitorização e melhoria contínua." },
              ].map((s) => (
                <li key={s.n} className="flex gap-4">
                  <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-gradient-primary font-display text-sm font-bold text-primary-foreground shadow-glow">
                    {s.n}
                  </div>
                  <div>
                    <div className="font-medium text-foreground">{s.t}</div>
                    <div className="text-sm text-muted-foreground">{s.d}</div>
                  </div>
                </li>
              ))}
            </ol>
          </div>
        </motion.div>
      </div>
    </Section>
  );
}

/* ---------------- Serviços ---------------- */
const SERVICES = [
  { icon: Globe, t: "Websites institucionais", d: "Sites modernos, optimizados para SEO e prontos para converter visitantes em clientes." },
  { icon: Layout, t: "Landing Pages", d: "Páginas de alto impacto, focadas em conversão para campanhas e produtos." },
  { icon: Smartphone, t: "Aplicações Web/Mobile", d: "Apps responsivas com experiência fluida em qualquer dispositivo." },
  { icon: Palette, t: "UI/UX Design", d: "Interfaces elegantes, intuitivas e centradas no utilizador." },
  { icon: Code2, t: "Desenvolvimento React", d: "Aplicações React/TypeScript modernas, modulares e escaláveis." },
  { icon: Zap, t: "Performance & SEO", d: "Optimização técnica, Core Web Vitals e visibilidade orgânica." },
  { icon: Brush, t: "Branding de Marca", d: "Desde a ideia inicial até à identidade visual completa — logótipo, paleta, tipografia e manual de marca prontos a usar em qualquer suporte." },
  { icon: LifeBuoy, t: "Suporte e Manutenção", d: "Acompanhamento contínuo, actualizações, segurança, backups e pequenas melhorias para manter o seu site sempre rápido e atualizado." },
];
function Servicos() {
  return (
    <Section id="servicos" eyebrow="Serviços" title="O que posso construir consigo.">
      <div className="grid gap-5 sm:grid-cols-2 lg:grid-cols-3">
        {SERVICES.map((s, i) => (
          <motion.div
            key={s.t}
            initial={{ opacity: 0, y: 30 }} whileInView={{ opacity: 1, y: 0 }} viewport={{ once: true }}
            transition={{ duration: 0.5, delay: i * 0.05 }}
            className="group relative overflow-hidden rounded-2xl border border-border bg-card-gradient p-6 backdrop-blur transition-transform hover:-translate-y-1 hover:shadow-elevated"
          >
            <div className="absolute -right-10 -top-10 h-32 w-32 rounded-full bg-primary/20 blur-2xl transition-opacity group-hover:bg-accent/30" />
            <div className="relative">
              <div className="inline-flex h-12 w-12 items-center justify-center rounded-xl bg-gradient-primary text-primary-foreground shadow-glow">
                <s.icon className="h-6 w-6" />
              </div>
              <h3 className="mt-5 font-display text-lg font-semibold">{s.t}</h3>
              <p className="mt-2 text-sm text-muted-foreground">{s.d}</p>
            </div>
          </motion.div>
        ))}
      </div>
    </Section>
  );
}

/* ---------------- Projetos ---------------- */

const FEATURED = {
  t: "Agência Imobiliária da Veigas",
  tag: "Web Site · Redesign",
  desc: "Redesenhei todo o web site e a experiência digital da agência, modernizando a navegação, performance e conversão. O tráfego gerado aumentou em 320%.",
  href: "https://imoveisdeportugal.pt/",
  img: veigasImg,
};

const PROJETOS = [
  { t: "FitFlow", tag: "Web App", desc: "Aplicação web para gestão de treino e bem-estar.", href: "https://fitflow.paulogomes.pt/", img: fitflowImg },
  { t: "Silva & Associados | Excelência Jurídica", tag: "Business Web Site", desc: "Website institucional para sociedade de advogados, com identidade sóbria e moderna.", href: "https://silvalaw.paulogomes.pt/", img: silvaImg },
  { t: "Perdidos e Achados", tag: "Comunidade", desc: "Plataforma comunitária para reportar e encontrar objetos perdidos.", href: "https://perdidoseachados.paulogomes.pt/", img: perdidosImg },
  { t: "OCR to Image", tag: "Web site de IA", desc: "Imagem com texto: extração inteligente de texto a partir de imagens.", href: "https://ocrtoimage.paulogomes.pt/", img: ocrImg },
  { t: "Moto trips — As minhas aventuras sobre rodas", tag: "Web App", desc: "Diário de viagens de mota com rotas, fotografias e histórias.", href: "https://mototrips.paulogomes.pt/", img: motoImg },
];

function Projetos() {
  return (
    <Section id="projetos" eyebrow="Projetos" title="Trabalhos recentes.">
      {/* Featured */}
      <motion.a
        href={FEATURED.href}
        target="_blank"
        rel="noopener noreferrer"
        initial={{ opacity: 0, y: 40 }} whileInView={{ opacity: 1, y: 0 }} viewport={{ once: true }}
        transition={{ duration: 0.6 }}
        className="group relative mb-8 grid overflow-hidden rounded-3xl border border-border bg-card-gradient backdrop-blur lg:grid-cols-[1.2fr_1fr]"
      >
        <div className="relative aspect-[16/10] overflow-hidden lg:aspect-auto">
          <img src={FEATURED.img} alt={FEATURED.t} loading="lazy" width={1024} height={1024} className="h-full w-full object-cover transition-transform duration-700 group-hover:scale-105" />
          <div className="absolute inset-0 bg-gradient-to-tr from-background/80 via-background/20 to-transparent" />
          <div className="absolute left-5 top-5 inline-flex items-center gap-2 rounded-full bg-gradient-primary px-3 py-1.5 text-[11px] font-medium uppercase tracking-[0.2em] text-primary-foreground shadow-glow">
            <Sparkles className="h-3 w-3" /> Projeto em destaque
          </div>
        </div>
        <div className="flex flex-col justify-center gap-4 p-8 lg:p-10">
          <div className="text-xs uppercase tracking-[0.2em] text-muted-foreground">{FEATURED.tag}</div>
          <h3 className="font-display text-2xl font-bold sm:text-3xl">{FEATURED.t}</h3>
          <p className="text-sm text-muted-foreground">{FEATURED.desc}</p>
          <div className="mt-2 inline-flex items-center gap-2 rounded-full border border-primary/50 bg-primary/10 px-3 py-1 text-xs font-semibold text-primary w-fit">
            <Zap className="h-3.5 w-3.5" /> Tráfego +320%
          </div>
          <div className="mt-2 inline-flex items-center gap-2 text-sm font-medium text-primary">
            Ver projeto <ArrowRight className="h-4 w-4 transition-transform group-hover:translate-x-1" />
          </div>
        </div>
      </motion.a>

      <div className="grid gap-6 md:grid-cols-2">
        {PROJETOS.map((p, i) => (
          <motion.a
            key={p.t}
            href={p.href}
            target="_blank"
            rel="noopener noreferrer"
            initial={{ opacity: 0, y: 40 }} whileInView={{ opacity: 1, y: 0 }} viewport={{ once: true }}
            transition={{ duration: 0.6, delay: i * 0.08 }}
            className="group relative block overflow-hidden rounded-3xl border border-border bg-card-gradient backdrop-blur"
          >
            <div className="relative aspect-[16/10] overflow-hidden">
              <img src={p.img} alt={p.t} loading="lazy" width={1024} height={1024} className="h-full w-full object-cover transition-transform duration-700 group-hover:scale-105" />
              <div className="absolute inset-0 bg-gradient-to-t from-background/80 to-transparent" />
            </div>
            <div className="flex items-center justify-between gap-4 p-6">
              <div className="min-w-0">
                <div className="text-xs uppercase tracking-[0.2em] text-muted-foreground">{p.tag}</div>
                <h3 className="mt-1 font-display text-lg font-semibold truncate">{p.t}</h3>
                <p className="mt-1 text-sm text-muted-foreground line-clamp-2">{p.desc}</p>
              </div>
              <ArrowRight className="h-5 w-5 shrink-0 text-primary transition-transform group-hover:translate-x-1" />
            </div>
          </motion.a>
        ))}
      </div>
    </Section>
  );
}

/* ---------------- Tecnologias ---------------- */
const TECH: { t: string; icon: React.ComponentType<{ className?: string }> }[] = [
  { t: "React", icon: Atom },
  { t: "TypeScript", icon: FileType },
  { t: "Next.js", icon: Layers },
  { t: "Tailwind CSS", icon: Wind },
  { t: "Node.js", icon: Server },
  { t: "PHP", icon: FileCode2 },
  { t: "MySQL", icon: Database },
  { t: "WordPress", icon: Globe },
  { t: "cPanel", icon: Wrench },
  { t: "REST APIs", icon: Workflow },
  { t: "Framer Motion", icon: Sparkles },
  { t: "GSAP", icon: Zap },
  { t: "HTML5", icon: Code2 },
  { t: "CSS3", icon: Palette },
  { t: "Git", icon: GitBranch },
];
function Tecnologias() {
  return (
    <Section id="tecnologias" eyebrow="Stack" title="Ferramentas de eleição.">
      <div className="grid grid-cols-3 gap-4 sm:grid-cols-4 md:grid-cols-5 lg:grid-cols-6">
        {TECH.map((tech, i) => (
          <motion.div
            key={tech.t}
            initial={{ opacity: 0, y: 30, rotateX: -25 }}
            whileInView={{ opacity: 1, y: 0, rotateX: 0 }}
            viewport={{ once: true, margin: "-50px" }}
            transition={{ duration: 0.5, delay: i * 0.04 }}
            whileHover={{ y: -6, rotateY: 8, rotateX: -8 }}
            className="perspective-1000 group flex flex-col items-center gap-3"
          >
            <div className="preserve-3d relative flex h-20 w-20 items-center justify-center rounded-2xl border border-border bg-card-gradient shadow-elevated backdrop-blur transition-shadow group-hover:shadow-glow">
              <div className="absolute inset-0 rounded-2xl bg-gradient-primary opacity-0 blur-xl transition-opacity group-hover:opacity-60" />
              <div className="absolute -inset-px rounded-2xl bg-gradient-to-br from-primary/30 via-transparent to-accent/30 opacity-50" />
              <div
                className="relative flex h-14 w-14 items-center justify-center rounded-xl bg-gradient-primary text-primary-foreground shadow-glow"
                style={{ transform: "translateZ(20px)" }}
              >
                <tech.icon className="h-7 w-7" />
              </div>
            </div>
            <span className="text-center text-xs font-medium text-foreground sm:text-sm">{tech.t}</span>
          </motion.div>
        ))}
      </div>
    </Section>
  );
}

/* ---------------- Contacto ---------------- */
function Contacto() {
  const [sending, setSending] = useState(false);

  const onSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const form = e.currentTarget;
    const data = new FormData(form);
    const payload = {
      site: "pg Web e App Designer",
      nome: String(data.get("nome") || ""),
      email: String(data.get("email") || ""),
      assunto: String(data.get("assunto") || ""),
      mensagem: String(data.get("mensagem") || ""),
    };
    setSending(true);
    try {
      const res = await fetch("/api/contact.php", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });
      const json = await res.json().catch(() => ({}));
      if (!res.ok || !json.ok) throw new Error(json.error || "Erro ao enviar");
      toast.success("Mensagem enviada com sucesso. Obrigado!");
      form.reset();
    } catch (err) {
      const msg = err instanceof Error ? err.message : "Erro ao enviar";
      toast.error(msg);
    } finally {
      setSending(false);
    }
  };

  return (
    <Section id="contacto" eyebrow="Contacto" title="Vamos criar algo memorável.">
      <div className="grid gap-10 lg:grid-cols-[0.9fr_1.1fr]">
        <motion.div
          initial={{ opacity: 0, x: -30 }} whileInView={{ opacity: 1, x: 0 }} viewport={{ once: true }} transition={{ duration: 0.6 }}
          className="space-y-6"
        >
          <p className="text-muted-foreground">
            Tem um projeto em mente? Diga-me o que precisa e respondo o mais rápido possível.
          </p>
          <ul className="space-y-5">
            <li className="flex items-start gap-4">
              <div className="flex h-11 w-11 shrink-0 items-center justify-center rounded-xl bg-gradient-primary text-primary-foreground shadow-glow">
                <Mail className="h-5 w-5" />
              </div>
              <div>
                <div className="text-xs uppercase tracking-[0.2em] text-muted-foreground">Email</div>
                <a href="mailto:ola@paulogomes.pt" className="font-medium text-foreground hover:text-primary transition-colors">
                  ola@paulogomes.pt
                </a>
              </div>
            </li>
            <li className="flex items-start gap-4">
              <div className="flex h-11 w-11 shrink-0 items-center justify-center rounded-xl bg-gradient-primary text-primary-foreground shadow-glow">
                <Phone className="h-5 w-5" />
              </div>
              <div>
                <div className="text-xs uppercase tracking-[0.2em] text-muted-foreground">Telemóvel</div>
                <a href="tel:+351917890864" className="font-medium text-foreground hover:text-primary transition-colors">
                  +351 917 890 864
                </a>
                <div className="mt-0.5 text-xs italic text-muted-foreground">
                  Chamada para a rede móvel nacional
                </div>
              </div>
            </li>
            <li className="flex items-start gap-4">
              <div className="flex h-11 w-11 shrink-0 items-center justify-center rounded-xl bg-gradient-primary text-primary-foreground shadow-glow">
                <MapPin className="h-5 w-5" />
              </div>
              <div>
                <div className="text-xs uppercase tracking-[0.2em] text-muted-foreground">Localização</div>
                <span className="font-medium text-foreground">Almada — Portugal</span>
              </div>
            </li>
          </ul>
          <div className="flex gap-3 pt-2">
            <a href="#" aria-label="LinkedIn" className="flex h-10 w-10 items-center justify-center rounded-lg border border-border bg-card/40 text-muted-foreground transition-all hover:border-primary/60 hover:text-primary">
              <Linkedin className="h-4 w-4" />
            </a>
            <a href="#" aria-label="GitHub" className="flex h-10 w-10 items-center justify-center rounded-lg border border-border bg-card/40 text-muted-foreground transition-all hover:border-primary/60 hover:text-primary">
              <Github className="h-4 w-4" />
            </a>
          </div>
        </motion.div>

        <motion.form
          onSubmit={onSubmit}
          initial={{ opacity: 0, x: 30 }} whileInView={{ opacity: 1, x: 0 }} viewport={{ once: true }} transition={{ duration: 0.6 }}
          className="relative overflow-hidden rounded-3xl border border-border bg-card-gradient p-8 shadow-elevated backdrop-blur"
        >
          <div className="absolute -right-10 -top-10 h-40 w-40 rounded-full bg-accent/20 blur-3xl" />
          <h3 className="font-display text-xl font-semibold">Contacto</h3>
          <p className="mt-1 text-sm text-muted-foreground">Resposta dentro de 24h úteis.</p>
          <div className="relative mt-6 grid gap-4 sm:grid-cols-2">
            <Field name="nome" label="Nome" required />
            <Field name="email" label="Email" type="email" required />
            <Field name="assunto" label="Assunto" className="sm:col-span-2" />
            <Field name="mensagem" label="Mensagem" textarea required className="sm:col-span-2" />
          </div>
          <Button type="submit" disabled={sending} className="mt-6 w-full rounded-full bg-gradient-primary py-6 text-base font-medium text-primary-foreground shadow-glow transition-transform hover:scale-[1.02] hover:bg-gradient-primary disabled:opacity-60">
            {sending ? "A enviar..." : (<><Send className="mr-2 h-4 w-4" /> Enviar mensagem</>)}
          </Button>
        </motion.form>
      </div>
    </Section>
  );
}

function Field({
  name, label, type = "text", required, textarea, className = "",
}: { name: string; label: string; type?: string; required?: boolean; textarea?: boolean; className?: string }) {
  const base = "peer w-full rounded-xl border border-border bg-background/60 px-4 pt-6 pb-2 text-sm text-foreground outline-none transition-colors placeholder-transparent focus:border-primary focus:ring-2 focus:ring-primary/20";
  return (
    <label className={`relative block ${className}`}>
      {textarea ? (
        <textarea name={name} required={required} placeholder={label} rows={5} className={base} />
      ) : (
        <input name={name} type={type} required={required} placeholder={label} className={base} />
      )}
      <span className="pointer-events-none absolute left-4 top-2 text-[11px] uppercase tracking-[0.15em] text-muted-foreground">
        {label}{required && " *"}
      </span>
    </label>
  );
}

/* ---------------- Footer ---------------- */
function Footer() {
  return (
    <footer className="relative z-10 mt-20 overflow-hidden border-t border-border/60 bg-background/60 backdrop-blur">
      {/* 3D decorative elements */}
      <div className="pointer-events-none absolute inset-0">
        <div className="absolute -left-20 -top-20 h-72 w-72 rounded-full bg-primary/25 blur-[120px] animate-pulse-glow" />
        <div className="absolute -right-20 -bottom-32 h-80 w-80 rounded-full bg-accent/25 blur-[140px] animate-pulse-glow" />
        <div className="absolute left-1/2 top-0 h-px w-2/3 -translate-x-1/2 bg-gradient-to-r from-transparent via-primary/60 to-transparent" />
      </div>

      <div className="relative mx-auto max-w-7xl px-6 py-16">
        <div className="perspective-1000 mb-12 flex justify-center">
          <motion.div
            initial={{ opacity: 0, rotateX: -30, y: 40 }}
            whileInView={{ opacity: 1, rotateX: 0, y: 0 }}
            viewport={{ once: true }}
            transition={{ duration: 0.8 }}
            whileHover={{ rotateY: 12, rotateX: -8, scale: 1.04 }}
            className="preserve-3d relative"
          >
            <div className="absolute -inset-8 rounded-3xl bg-gradient-primary opacity-30 blur-3xl" />
            <div
              className="relative flex h-28 w-28 items-center justify-center rounded-3xl bg-gradient-primary shadow-glow"
              style={{ transform: "translateZ(40px)" }}
            >
              <span className="font-display text-4xl font-bold text-primary-foreground">pg</span>
              <div className="absolute inset-0 rounded-3xl border border-primary/40 animate-spin-slow" style={{ transform: "translateZ(20px) scale(1.15)" }} />
              <div className="absolute inset-0 rounded-3xl border border-accent/40 animate-spin-slow" style={{ animationDirection: "reverse", transform: "translateZ(30px) scale(1.3)" }} />
            </div>
          </motion.div>
        </div>

        <div className="grid gap-10 text-sm sm:grid-cols-3">
          <div>
            <div className="font-display text-base font-semibold text-foreground">pg Web e App Designer</div>
            <p className="mt-2 text-muted-foreground">Sites e aplicações modernas, com toque 3D, em Almada — Portugal.</p>
          </div>
          <div>
            <div className="text-xs uppercase tracking-[0.25em] text-muted-foreground">Navegação</div>
            <ul className="mt-3 space-y-1.5">
              {NAV.map((n) => {
                const isExternal = n.href.startsWith("/");
                return (
                  <li key={n.href}>
                    <a
                      href={n.href}
                      {...(isExternal ? { target: "_blank", rel: "noopener noreferrer" } : {})}
                      className="text-muted-foreground transition-colors hover:text-primary"
                    >
                      {n.label}
                    </a>
                  </li>
                );
              })}
            </ul>
          </div>
          <div>
            <div className="text-xs uppercase tracking-[0.25em] text-muted-foreground">Contacto</div>
            <ul className="mt-3 space-y-1.5 text-muted-foreground">
              <li><a href="mailto:ola@paulogomes.pt" className="hover:text-primary transition-colors">ola@paulogomes.pt</a></li>
              <li><a href="tel:+351917890864" className="hover:text-primary transition-colors">+351 917 890 864</a></li>
              <li>Almada — Portugal</li>
            </ul>
          </div>
        </div>

        <div className="mt-12 flex flex-col items-center justify-between gap-3 border-t border-border/50 pt-6 sm:flex-row">
          <span className="text-xs text-muted-foreground">© {new Date().getFullYear()} pg Web e App Designer · Paulo Gomes</span>
          <div className="flex flex-wrap items-center justify-center gap-x-4 gap-y-1 text-xs text-muted-foreground">
            <a
              href="/politica-privacidade"
              target="_blank"
              rel="noopener noreferrer"
              className="transition-colors hover:text-primary"
            >
              Política de Privacidade
            </a>
            <span aria-hidden="true">·</span>
            <a
              href="/termos-condicoes"
              target="_blank"
              rel="noopener noreferrer"
              className="transition-colors hover:text-primary"
            >
              Termos e Condições
            </a>
            <span aria-hidden="true">·</span>
            <a
              href="/termos-servico"
              target="_blank"
              rel="noopener noreferrer"
              className="transition-colors hover:text-primary"
            >
              Termos de Serviço
            </a>
          </div>
          <span className="text-xs text-muted-foreground">Feito com cuidado em Almada — Portugal.</span>
        </div>
      </div>
    </footer>
  );
}

/* ---------------- Section wrapper ---------------- */
function Section({
  id, eyebrow, title, children,
}: { id: string; eyebrow: string; title: string; children: React.ReactNode }) {
  return (
    <section id={id} className="relative py-28">
      <div className="mx-auto max-w-7xl px-6">
        <motion.div
          initial={{ opacity: 0, y: 20 }} whileInView={{ opacity: 1, y: 0 }} viewport={{ once: true }} transition={{ duration: 0.5 }}
          className="mb-12 max-w-2xl"
        >
          <div className="inline-flex items-center gap-2 rounded-full border border-border bg-card/40 px-3 py-1 text-[11px] uppercase tracking-[0.25em] text-muted-foreground backdrop-blur">
            <span className="h-1 w-1 rounded-full bg-primary" /> {eyebrow}
          </div>
          <h2 className="mt-4 font-display text-4xl font-bold leading-tight sm:text-5xl">{title}</h2>
        </motion.div>
        {children}
      </div>
    </section>
  );
}
