/* About page — cinematic, founder-led */
const { motion: ma, useInView: useInVa, useScroll: useScrA, useTransform: useTransA } = FramerMotion;
const { useRef: uRa } = React;
const {
  WordsPullUp: WPa, WordsPullUpMultiStyle: WPMa, AnimatedParagraph: APa, FadeUp: FUa,
  IconArrowRight: IArrA, IconCheck: ICha, IconSparkle: ISpa,
  Navbar: NBa, CtaPill: CPa, Footer: FTa, EASE_EXPO: EEa, NAV_ITEMS_PAGE,
} = window;

function AboutHero() {
  return (
    <section className="relative w-full p-3 md:p-5" style={{ minHeight: "max(720px, 100svh)" }}>
      <div className="relative w-full rounded-2xl md:rounded-[2rem] overflow-hidden bg-[#070B1F]" style={{ minHeight: "max(704px, calc(100svh - 2.5rem))" }}>
        {/* Cinematic hero background video */}
        <video
          autoPlay
          loop
          muted
          playsInline
          preload="auto"
          poster="assets/hero-poster.jpg"
          className="absolute inset-0 w-full h-full object-cover pointer-events-none"
        >
          <source src="assets/hero.webm" type="video/webm" />
          <source src="assets/hero.mp4" type="video/mp4" />
        </video>
        <div className="absolute inset-0 dot-grid opacity-[0.18] pointer-events-none" />
        <div className="absolute inset-0 noise-overlay opacity-[0.18] mix-blend-overlay pointer-events-none" />
        <div className="absolute inset-0 pointer-events-none"
          style={{ background: "radial-gradient(ellipse at 50% 40%, transparent 0%, transparent 35%, rgba(7,11,31,0.6) 90%)" }}
        />
        <div className="absolute inset-0 pointer-events-none hidden md:block"
          style={{ background: "linear-gradient(90deg, rgba(7,11,31,0.88) 0%, rgba(7,11,31,0.62) 42%, rgba(7,11,31,0.22) 75%, rgba(7,11,31,0.05) 100%)" }}
        />
        <div className="absolute inset-0 pointer-events-none md:hidden"
          style={{ background: "linear-gradient(180deg, rgba(7,11,31,0.55) 0%, rgba(7,11,31,0.18) 35%, rgba(7,11,31,0.55) 100%)" }}
        />
        <div className="absolute -top-32 -left-32 w-[60vw] h-[60vw] max-w-[700px] max-h-[700px] pointer-events-none ai-glow opacity-50" />
        <AboutHeroParticles />

        <NBa />

        {/* Eyebrow with live ping */}
        <ma.div
          initial={{ opacity: 0, y: -8 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 1, delay: 0.4, ease: EEa }}
          className="absolute top-20 md:top-24 left-6 md:left-9 z-20 flex items-center gap-2.5"
        >
          <span className="relative inline-flex w-2 h-2">
            <span className="absolute inset-0 rounded-full bg-orange/70 animate-ping" />
            <span className="relative inline-flex w-2 h-2 rounded-full bg-orange" />
          </span>
          <span className="eyebrow-orange">Sobre · a nossa história</span>
        </ma.div>

        {/* Right side: orbital info chips */}
        <ma.div
          initial={{ opacity: 0, x: 30 }}
          animate={{ opacity: 1, x: 0 }}
          transition={{ duration: 1.2, delay: 0.7, ease: EEa }}
          className="hidden lg:flex absolute top-24 right-9 z-20 flex-col gap-2 items-end"
        >
          {[
            { k: "Fundada", v: "2026" },
            { k: "Localização", v: "Lisboa, PT" },
            { k: "Foco", v: "Pequenos negócios" },
          ].map((c, i) => (
            <ma.div
              key={c.k}
              initial={{ opacity: 0, x: 20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.8, delay: 0.9 + i * 0.12, ease: EEa }}
              className="flex items-center gap-3 bg-[#070B1F]/60 backdrop-blur-sm hairline rounded-full pl-3 pr-4 py-1.5"
            >
              <span className="text-[10px] tracking-[0.18em] uppercase text-orange">{c.k}</span>
              <span className="text-xs text-primary/85">{c.v}</span>
            </ma.div>
          ))}
        </ma.div>

        {/* 3-row grid: spacer for nav · centerpiece · heading */}
        <div className="absolute inset-0 grid grid-rows-[112px_minmax(0,1fr)_auto] pt-2 pb-10 md:pb-14 px-5 sm:px-7 md:px-10 z-10">
          <div />

          {/* Row 2: centerpiece */}
          <div className="relative flex items-center justify-center min-h-0">
            <ConvergenceCore />
          </div>

          {/* Row 3: heading */}
          <div className="max-w-7xl mx-auto w-full grid grid-cols-12 gap-6 items-end">
            <div className="col-span-12 lg:col-span-8">
              <WPMa
                justify="flex-start"
                className="text-4xl sm:text-5xl md:text-6xl lg:text-7xl text-primary leading-[0.96] tracking-[-0.03em]"
                segments={[
                  { text: "Pequenos negócios,",       className: "font-normal" },
                  { text: "primeiro",                  className: "serif italic font-normal text-orange" },
                  { text: "contacto.",                 className: "font-normal" },
                ]}
              />
            </div>
            <div className="col-span-12 lg:col-span-4">
              <ma.p
                initial={{ y: 24, opacity: 0 }}
                animate={{ y: 0, opacity: 1 }}
                transition={{ duration: 0.9, delay: 0.85, ease: EEa }}
                className="text-primary/65 text-sm md:text-base leading-relaxed"
              >
                Apoiamos o primeiro contacto, respondemos com base no contexto
                configurado e organizamos leads para a equipa fechar.
              </ma.p>
            </div>
          </div>
        </div>

        <ScrollCue label="rolar para descobrir" />
      </div>
    </section>
  );
}

/* ============================================================
   ConvergenceField — radiating SVG lines from edges to center
   with traveling "lead" particles. Plus pulsing constellation.
============================================================ */
function ConvergenceField() {
  // 16 lines radiating from a center, distributed around 360°
  const center = { x: 600, y: 400 };
  const lines = (function build() {
    const arr = [];
    const N = 16;
    for (let i = 0; i < N; i++) {
      const angle = (i / N) * Math.PI * 2;
      const r1 = 720; // edge radius
      const r2 = 110; // inner radius (around core)
      const x1 = center.x + Math.cos(angle) * r1;
      const y1 = center.y + Math.sin(angle) * r1;
      const x2 = center.x + Math.cos(angle) * r2;
      const y2 = center.y + Math.sin(angle) * r2;
      arr.push({ x1, y1, x2, y2, angle, delay: (i * 0.35) % 5 });
    }
    return arr;
  })();

  // Outer ring node positions (12 dots around the edge)
  const ringNodes = (function () {
    const arr = [];
    const N = 12;
    for (let i = 0; i < N; i++) {
      const a = (i / N) * Math.PI * 2 + 0.1;
      arr.push({
        x: center.x + Math.cos(a) * 540,
        y: center.y + Math.sin(a) * 540,
        delay: -(i * 0.5),
        size: i % 3 === 0 ? 4 : 2.5,
      });
    }
    return arr;
  })();

  return (
    <div className="absolute inset-0 pointer-events-none">
      <svg
        viewBox="0 0 1200 800"
        preserveAspectRatio="xMidYMid slice"
        className="absolute inset-0 w-full h-full"
        aria-hidden
      >
        <defs>
          <radialGradient id="conv-line" cx="0.5" cy="0.5" r="0.5">
            <stop offset="0%"  stopColor="#FF6B73" stopOpacity="0.6" />
            <stop offset="60%" stopColor="#FF8289" stopOpacity="0.25" />
            <stop offset="100%" stopColor="#F7F8FF" stopOpacity="0" />
          </radialGradient>
          <linearGradient id="conv-radial" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%"  stopColor="#F7F8FF" stopOpacity="0" />
            <stop offset="50%" stopColor="#F7F8FF" stopOpacity="0.18" />
            <stop offset="100%" stopColor="#FF6B73" stopOpacity="0.45" />
          </linearGradient>
          <filter id="conv-glow" x="-100%" y="-100%" width="300%" height="300%">
            <feGaussianBlur stdDeviation="3" result="b" />
            <feMerge><feMergeNode in="b"/><feMergeNode in="SourceGraphic"/></feMerge>
          </filter>
        </defs>

        {/* Faint concentric rings */}
        {[200, 320, 440].map((r, i) => (
          <circle key={i} cx={center.x} cy={center.y} r={r}
            stroke="#F7F8FF" strokeOpacity={0.04 + i * 0.02}
            strokeWidth={i === 1 ? 1 : 0.7}
            strokeDasharray={i === 1 ? "3 8" : "none"}
            fill="none">
            <animate attributeName="r"
              values={`${r};${r + 8};${r}`}
              dur={`${10 + i * 2}s`}
              repeatCount="indefinite"
            />
          </circle>
        ))}

        {/* Radiating lines */}
        {lines.map((l, i) => (
          <line
            key={`l-${i}`}
            x1={l.x1} y1={l.y1} x2={l.x2} y2={l.y2}
            stroke="url(#conv-radial)"
            strokeWidth="0.8"
            opacity="0.55"
          >
            <animate attributeName="opacity"
              values="0.15;0.65;0.15"
              dur={`${6 + (i % 5)}s`}
              begin={`${-l.delay}s`}
              repeatCount="indefinite"
            />
          </line>
        ))}

        {/* Traveling particles flowing INTO the center along the lines */}
        {lines.map((l, i) => (
          <circle key={`p-${i}`} r={i % 3 === 0 ? 3 : 2}
            fill={i % 3 === 0 ? "#FF6B73" : "#FF8289"}
            opacity="0.85"
            filter="url(#conv-glow)">
            <animate attributeName="cx"
              values={`${l.x1};${l.x2}`}
              dur={`${5 + (i % 4)}s`}
              begin={`${-(i * 0.4)}s`}
              repeatCount="indefinite"
            />
            <animate attributeName="cy"
              values={`${l.y1};${l.y2}`}
              dur={`${5 + (i % 4)}s`}
              begin={`${-(i * 0.4)}s`}
              repeatCount="indefinite"
            />
            <animate attributeName="opacity"
              values="0;0.95;0.95;0"
              keyTimes="0;0.1;0.85;1"
              dur={`${5 + (i % 4)}s`}
              begin={`${-(i * 0.4)}s`}
              repeatCount="indefinite"
            />
            <animate attributeName="r"
              values={`${i % 3 === 0 ? 2 : 1.5};${i % 3 === 0 ? 3.5 : 2.5};0.5`}
              dur={`${5 + (i % 4)}s`}
              begin={`${-(i * 0.4)}s`}
              repeatCount="indefinite"
            />
          </circle>
        ))}

        {/* Outer ring nodes (constellation) */}
        {ringNodes.map((n, i) => (
          <g key={`n-${i}`}>
            <circle cx={n.x} cy={n.y} r={n.size + 6}
              fill="rgba(255,107,115, 0.10)"
              filter="url(#conv-glow)">
              <animate attributeName="r"
                values={`${n.size + 4};${n.size + 10};${n.size + 4}`}
                dur={`${4 + (i % 3)}s`}
                begin={`${n.delay}s`}
                repeatCount="indefinite"
              />
            </circle>
            <circle cx={n.x} cy={n.y} r={n.size}
              fill="#F7F8FF" opacity="0.75">
              <animate attributeName="opacity"
                values="0.4;1;0.4"
                dur={`${4 + (i % 3)}s`}
                begin={`${n.delay}s`}
                repeatCount="indefinite"
              />
            </circle>
          </g>
        ))}
      </svg>
    </div>
  );
}

/* ConvergenceCore — central pulsing orb with rotating rings and orbital dots */
function ConvergenceCore() {
  return (
    <div className="relative pointer-events-none">
      {/* Large halo */}
      <ma.div
        initial={{ opacity: 0, scale: 0.6 }}
        animate={{ opacity: 1, scale: 1 }}
        transition={{ duration: 1.8, delay: 0.5, ease: EEa }}
        className="absolute -inset-16 sm:-inset-24 md:-inset-32 rounded-full"
        style={{
          background: "radial-gradient(circle at 50% 50%, rgba(255,107,115, 0.45), rgba(255,107,115, 0) 65%)",
          filter: "blur(40px)",
        }}
      />

      {/* Three rotating dashed rings */}
      <ma.div
        animate={{ rotate: 360 }}
        transition={{ duration: 36, repeat: Infinity, ease: "linear" }}
        className="absolute -inset-14 sm:-inset-20 md:-inset-28 rounded-full border border-dashed"
        style={{ borderColor: "rgba(247,248,255,0.10)", borderWidth: 1 }}
      />
      <ma.div
        animate={{ rotate: -360 }}
        transition={{ duration: 28, repeat: Infinity, ease: "linear" }}
        className="absolute -inset-9 sm:-inset-14 md:-inset-20 rounded-full border border-dashed"
        style={{ borderColor: "rgba(255,107,115,0.16)", borderWidth: 1 }}
      />
      <ma.div
        animate={{ rotate: 360 }}
        transition={{ duration: 20, repeat: Infinity, ease: "linear" }}
        className="absolute -inset-5 sm:-inset-9 md:-inset-12 rounded-full border"
        style={{ borderColor: "rgba(247,248,255,0.14)", borderWidth: 1 }}
      >
        {/* Orbital dot riding on this ring */}
        <span
          className="absolute top-1/2 -mt-1.5 right-0 w-3 h-3 rounded-full bg-orange"
          style={{ boxShadow: "0 0 12px rgba(255,107,115,0.8)", transform: "translateX(50%)" }}
        />
      </ma.div>

      {/* Core orb with breathing scale */}
      <ma.div
        initial={{ opacity: 0, scale: 0.4 }}
        animate={{ opacity: 1, scale: 1 }}
        transition={{ duration: 1.4, delay: 0.4, ease: EEa }}
        className="relative rounded-full"
        style={{
          width: "clamp(120px, 22vh, 200px)",
          height: "clamp(120px, 22vh, 200px)",
          background:
            "radial-gradient(circle at 35% 30%, #FFC8B4 0%, #FF8289 25%, #FF6B73 55%, #E94F5D 85%, #222747 100%)",
          boxShadow:
            "inset 0 0 40px rgba(255,255,255,0.25), 0 0 80px rgba(255,107,115,0.65), 0 0 160px -20px rgba(255,107,115,0.55)",
        }}
      >
        {/* Inner sheen */}
        <span className="absolute inset-2 rounded-full pointer-events-none"
          style={{
            background:
              "radial-gradient(circle at 35% 25%, rgba(255,255,255,0.5), rgba(255,255,255,0) 45%)",
          }}
        />
        {/* Soft pulsing inner ring */}
        <ma.span
          animate={{ scale: [1, 1.15, 1], opacity: [0.4, 0, 0.4] }}
          transition={{ duration: 3, repeat: Infinity, ease: "easeInOut" }}
          className="absolute inset-4 rounded-full"
          style={{ border: "1px solid rgba(255,255,255,0.45)" }}
        />
      </ma.div>

      {/* Floating labels around the orb */}
      {[
        { label: "Capta",     angle: -110, delay: 1.1 },
        { label: "Responde",  angle: -30,  delay: 1.25 },
        { label: "Qualifica", angle: 60,   delay: 1.4 },
        { label: "Organiza",  angle: 160,  delay: 1.55 },
      ].map((t) => {
        // distance from orb center: orb half-radius + clearance
        const rad = (t.angle * Math.PI) / 180;
        const cosA = Math.cos(rad).toFixed(3);
        const sinA = Math.sin(rad).toFixed(3);
        const distExpr = "(min(11vh, 100px) + 70px)";
        const x = `calc(${cosA} * ${distExpr})`;
        const y = `calc(${sinA} * ${distExpr})`;
        return (
          <ma.div
            key={t.label}
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{ duration: 1, delay: t.delay, ease: EEa }}
            className="hidden sm:block absolute top-1/2 left-1/2"
            style={{ transform: `translate(calc(-50% + ${x}), calc(-50% + ${y}))` }}
          >
            <span className="inline-flex items-center gap-2 bg-[#070B1F]/70 backdrop-blur-sm hairline rounded-full px-3 py-1 text-[10px] tracking-[0.18em] uppercase text-primary/80 whitespace-nowrap">
              <span className="w-1 h-1 rounded-full bg-orange" />
              {t.label}
            </span>
          </ma.div>
        );
      })}
    </div>
  );
}

function AboutHeroParticles() {
  const dots = (function () {
    const arr = [];
    for (let i = 0; i < 18; i++) {
      arr.push({
        l: 4 + Math.random() * 92,
        t: 5 + Math.random() * 90,
        s: 2 + Math.random() * 5,
        d: Math.random() * 9,
        o: 0.25 + Math.random() * 0.55,
      });
    }
    return arr;
  })();
  return (
    <div className="absolute inset-0 pointer-events-none">
      {dots.map((d, i) => (
        <span key={i} className="particle"
          style={{
            left: `${d.l}%`,
            top: `${d.t}%`,
            width: `${d.s}px`,
            height: `${d.s}px`,
            animationDelay: `${d.d}s`,
            opacity: d.o,
          }}
        />
      ))}
    </div>
  );
}

/* Small chevron + label at hero bottom hinting "scroll" */
function ScrollCue({ label }) {
  return (
    <ma.div
      initial={{ opacity: 0, y: 12 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 1, delay: 1.6, ease: EEa }}
      className="hidden md:flex absolute bottom-5 right-7 z-20 items-center gap-3 text-primary/45"
    >
      <span className="text-[10px] tracking-[0.18em] uppercase">{label}</span>
      <ma.span
        animate={{ y: [0, 6, 0] }}
        transition={{ duration: 2, repeat: Infinity, ease: "easeInOut" }}
        className="inline-block"
      >
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" className="w-4 h-4">
          <path d="M6 9l6 6 6-6" strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
      </ma.span>
    </ma.div>
  );
}

function Principles() {
  const items = [
    { k: "01", name: "Transparente", body: "A assistente apresenta-se como AI e não tenta passar por uma pessoa real." },
    { k: "02", name: "Contextual",   body: "Respostas usam apenas a informação do negócio configurada pelo utilizador." },
    { k: "03", name: "Prática",      body: "Foco no primeiro contacto, qualificação inicial e organização de leads." },
    { k: "04", name: "Humana",       body: "A equipa continua responsável por confirmar, vender e acompanhar." },
  ];
  return (
    <section className="bg-[#070B1F] px-5 md:px-8 py-24 md:py-32 border-t border-white/5">
      <div className="max-w-7xl mx-auto">
        <div className="max-w-3xl mb-14 md:mb-20">
          <FUa><div className="eyebrow-orange mb-5">Princípios do produto</div></FUa>
          <WPMa
            justify="flex-start"
            className="text-3xl sm:text-4xl md:text-5xl text-primary leading-[1.02]"
            segments={[
              { text: "Quatro princípios", className: "font-normal" },
              { text: "que definem",       className: "serif italic font-normal text-orange" },
              { text: "o que construímos.", className: "font-normal" },
            ]}
          />
        </div>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3 md:gap-2">
          {items.map((it, i) => (
            <FUa key={it.k} delay={i * 0.1}>
              <div className="bg-[#1A1E3A] rounded-2xl p-7 md:p-8 h-full hairline lift">
                <div className="text-primary/40 text-xs tracking-[0.18em] mb-12">{it.k}</div>
                <h3 className="text-primary text-2xl tracking-tight mb-3">{it.name}</h3>
                <p className="text-primary/55 text-sm leading-relaxed">{it.body}</p>
              </div>
            </FUa>
          ))}
        </div>
      </div>
    </section>
  );
}

function ForWhom() {
  const list = [
    { name: "Restaurantes",      bullet: "Reservas, horários, grupos, perguntas frequentes." },
    { name: "Clínicas",          bullet: "Qualificar por serviço, urgência e disponibilidade." },
    { name: "Barbearias",        bullet: "Marcações mesmo enquanto estás a atender." },
    { name: "Estética",          bullet: "Pedidos de tratamentos e orçamentos preliminares." },
    { name: "Stands automóveis", bullet: "Interesse por veículo, financiamento, retoma." },
    { name: "Serviços locais",   bullet: "Pedidos com localização, urgência e detalhe." },
    { name: "Consultores",       bullet: "Filtrar leads com maior potencial." },
    { name: "Imobiliárias",      bullet: "Tipologia, zona, orçamento e prazo." },
  ];
  return (
    <section className="bg-[#070B1F] px-5 md:px-8 py-24 md:py-32 border-t border-white/5">
      <div className="max-w-7xl mx-auto">
        <div className="grid grid-cols-1 md:grid-cols-12 gap-10 mb-12">
          <div className="md:col-span-6">
            <FUa><div className="eyebrow-orange mb-5">Para quem</div></FUa>
            <WPMa
              justify="flex-start"
              className="text-3xl sm:text-4xl md:text-5xl text-primary leading-[1.02]"
              segments={[
                { text: "Negócios que",         className: "font-normal" },
                { text: "não podem",             className: "serif italic font-normal text-orange" },
                { text: "perder pedidos.",       className: "font-normal" },
              ]}
            />
          </div>
          <div className="md:col-span-6 flex md:items-end">
            <FUa delay={0.3}>
              <p className="text-primary/60 text-base leading-relaxed max-w-md">
                Foi pensada para negócios que recebem pedidos em vários pontos de
                contacto e precisam de organizar melhor, sem depender de
                integrações complexas.
              </p>
            </FUa>
          </div>
        </div>

        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3 md:gap-2">
          {list.map((it, i) => (
            <FUa key={it.name} delay={i * 0.06}>
              <div className="group bg-[#1A1E3A] hairline rounded-2xl p-6 h-full lift cursor-default">
                <div className="flex items-center justify-between mb-5">
                  <span className="text-primary text-base md:text-lg tracking-tight">{it.name}</span>
                  <IArrA className="w-4 h-4 text-primary/30 group-hover:text-primary/80 group-hover:translate-x-1 transition-all" style={{ transform: "rotate(-45deg)" }} />
                </div>
                <p className="text-primary/55 text-sm leading-relaxed">{it.bullet}</p>
              </div>
            </FUa>
          ))}
        </div>
      </div>
    </section>
  );
}

function AboutCTA() {
  return (
    <section className="bg-[#070B1F] px-5 md:px-8 pb-24 md:pb-36 pt-12">
      <div className="max-w-5xl mx-auto">
        <div className="relative overflow-hidden rounded-3xl md:rounded-[2rem] bg-[#111530] hairline-strong px-6 sm:px-10 md:px-16 py-20 md:py-28 text-center">
          <div className="absolute inset-0 aurora opacity-60" />
          <div className="absolute inset-0 noise-overlay opacity-30 mix-blend-overlay pointer-events-none" />
          <div className="relative">
            <WPMa
              justify="center"
              className="text-3xl sm:text-4xl md:text-5xl text-primary leading-[1.02] max-w-2xl mx-auto"
              segments={[
                { text: "Queres criar a tua",              className: "font-normal" },
                { text: "assistente virtual?",             className: "serif italic font-normal text-orange" },
              ]}
            />
            <FUa delay={0.4}>
              <p className="mt-6 text-primary/60 text-base max-w-xl mx-auto leading-relaxed">
                Volta à landing page e pede acesso antecipado ao Captixy.
              </p>
            </FUa>
            <FUa delay={0.55}>
              <div className="mt-9 flex items-center justify-center gap-4 flex-wrap">
                <CPa href="https://app.captixy.com/signup" size="md">Pedir acesso</CPa>
                <a href="index.html" className="text-sm text-primary/65 hover:text-primary transition-colors link-underline">
                  ← Voltar à Captixy
                </a>
              </div>
            </FUa>
          </div>
        </div>
      </div>
    </section>
  );
}

function App() {
  return (
    <>
      <AboutHero />
      <Principles />
      <ForWhom />
      <AboutCTA />
      <FTa />
    </>
  );
}

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