/* global React, ReactDOM */
const { useState, useEffect, useRef } = React;

if ("scrollRestoration" in history) {
  history.scrollRestoration = "manual";
}
window.scrollTo(0, 0);

const WHATSAPP_URL = "https://wa.me/5583998548407?text=Oi!%20Vi%20seu%20site%20e%20quero%20saber%20mais";

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "showFloat": true
}/*EDITMODE-END*/;

const Icon = {
  WhatsApp: ({ size = 22 }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
      <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.967-.94 1.164-.173.198-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.71.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 0 1-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 0 1-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 0 1 2.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0 0 12.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 0 0 5.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 0 0-3.48-8.413Z"/>
    </svg>
  ),
  Arrow: ({ size = 16 }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
  ),
};

function Ph({ light = false, src, alt = "" }) {
  if (src) {
    return (
      <img
        className={`ph ${light ? "ph-light" : ""}`}
        src={src}
        alt={alt}
        loading="lazy"
        decoding="async"
        style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }}
      />
    );
  }
  return <div className={`ph ${light ? "ph-light" : ""}`} aria-hidden="true" />;
}

function TypingText({ text, as: As = "p", speed = 14, startDelay = 0, className = "" }) {
  const ref = useRef(null);
  const [shown, setShown] = useState(false);
  useEffect(() => {
    const el = ref.current; if (!el) return;
    const io = new IntersectionObserver((es) => {
      es.forEach((e) => {
        if (e.isIntersecting) {
          setTimeout(() => setShown(true), startDelay);
          io.disconnect();
        }
      });
    }, { threshold: 0.2 });
    io.observe(el);
    return () => io.disconnect();
  }, [startDelay]);
  const words = text.split(" ");
  let counter = 0;
  const out = [];
  words.forEach((word, wi) => {
    const chars = [...word];
    out.push(
      <span key={"w" + wi} style={{ display: "inline-block", whiteSpace: "nowrap" }}>
        {chars.map((c, ci) => {
          const idx = counter + ci;
          return (
            <span
              key={ci}
              style={{
                opacity: shown ? 1 : 0,
                transition: "opacity 80ms linear",
                transitionDelay: shown ? `${idx * speed}ms` : "0ms",
              }}
            >
              {c}
            </span>
          );
        })}
      </span>
    );
    counter += chars.length;
    if (wi < words.length - 1) {
      out.push(<React.Fragment key={"s" + wi}> </React.Fragment>);
      counter += 1;
    }
  });
  return <As ref={ref} className={className}>{out}</As>;
}

function Reveal({ children, delay = 0, as: As = "div", className = "", ...rest }) {
  const ref = useRef(null);
  const [shown, setShown] = useState(false);
  useEffect(() => {
    const el = ref.current; if (!el) return;
    const io = new IntersectionObserver((es) => {
      es.forEach((e) => { if (e.isIntersecting) { setTimeout(() => setShown(true), delay); io.disconnect(); } });
    }, { threshold: 0.12 });
    io.observe(el);
    return () => io.disconnect();
  }, [delay]);
  return <As ref={ref} className={`reveal ${shown ? "is-in" : ""} ${className}`} {...rest}>{children}</As>;
}

function HeroLineSvg({ text, target }) {
  const fontStack = '"dharma-gothic-e", "Bebas Neue", "Anton", "Oswald", "Impact", sans-serif';
  return (
    <svg
      viewBox={`0 0 ${target} 182`}
      preserveAspectRatio="xMinYMid meet"
      role="img"
      aria-label={text}
      style={{ width: "100%", height: "100%", display: "block", overflow: "visible" }}
    >
      <text
        x="0"
        y="160"
        fontFamily={fontStack}
        fontWeight="400"
        fontSize="200"
        fill="#F0F0F5"
        stroke="none"
        textAnchor="start"
        textLength={target}
        lengthAdjust="spacing"
        style={{ paintOrder: "fill" }}
      >
        {text.toUpperCase()}
      </text>
    </svg>
  );
}

function HeroDots({ count = 36 }) {
  const rand = (min, max) => min + Math.random() * (max - min);
  const containerRef = useRef(null);
  const dotsRef = useRef([]);
  const [dots] = useState(() =>
    Array.from({ length: count }, (_, i) => ({
      id: i,
      left: Math.random() * 100,
      top: Math.random() * 100,
      size: 2 + Math.random() * 3,
      delay: -Math.random() * 20,
      duration: 22 + Math.random() * 16,
      dx1: rand(-300, 300), dy1: rand(-200, 200),
      dx2: rand(-300, 300), dy2: rand(-200, 200),
      dx3: rand(-300, 300), dy3: rand(-200, 200),
    }))
  );

  useEffect(() => {
    const hero = containerRef.current?.closest("section");
    if (!hero) return;
    const RADIUS = 250;
    const STRENGTH = 0.35;
    let frame = 0;
    let mx = 0, my = 0, active = false;

    const apply = () => {
      frame = 0;
      dotsRef.current.forEach((el) => {
        if (!el) return;
        if (!active) { el.style.transform = ""; return; }
        const r = el.getBoundingClientRect();
        const dx = mx - (r.left + r.width / 2);
        const dy = my - (r.top + r.height / 2);
        const dist = Math.hypot(dx, dy);
        if (dist < RADIUS) {
          const f = (RADIUS - dist) / RADIUS;
          el.style.transform = `translate(${dx * f * STRENGTH}px, ${dy * f * STRENGTH}px)`;
        } else {
          el.style.transform = "";
        }
      });
    };
    const queue = () => { if (!frame) frame = requestAnimationFrame(apply); };
    const onMove = (e) => { mx = e.clientX; my = e.clientY; active = true; queue(); };
    const onLeave = () => { active = false; queue(); };

    hero.addEventListener("mousemove", onMove);
    hero.addEventListener("mouseleave", onLeave);
    return () => {
      hero.removeEventListener("mousemove", onMove);
      hero.removeEventListener("mouseleave", onLeave);
      if (frame) cancelAnimationFrame(frame);
    };
  }, []);

  return (
    <div className="hero-dots" ref={containerRef} aria-hidden="true">
      {dots.map((d, i) => (
        <span
          key={d.id}
          ref={(el) => { dotsRef.current[i] = el; }}
          className="dot-pos"
          style={{ left: `${d.left}%`, top: `${d.top}%` }}
        >
          <span
            className="dot"
            style={{
              width: `${d.size}px`,
              height: `${d.size}px`,
              animationDelay: `${d.delay}s`,
              animationDuration: `${d.duration}s`,
              "--dx1": `${d.dx1}px`,
              "--dy1": `${d.dy1}px`,
              "--dx2": `${d.dx2}px`,
              "--dy2": `${d.dy2}px`,
              "--dx3": `${d.dx3}px`,
              "--dy3": `${d.dy3}px`,
            }}
          />
        </span>
      ))}
    </div>
  );
}

function ScrollCue() {
  const [hidden, setHidden] = React.useState(false);
  const [isTouch, setIsTouch] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => setHidden(window.scrollY > 60);
    const mq = window.matchMedia("(max-width: 1024px)");
    const update = () => setIsTouch(mq.matches);
    update();
    mq.addEventListener("change", update);
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => {
      window.removeEventListener("scroll", onScroll);
      mq.removeEventListener("change", update);
    };
  }, []);
  return (
    <div className={`scroll-cue${hidden ? " is-hidden" : ""}`} aria-hidden="true">
      <span className="scroll-cue-label">{isTouch ? "Arraste para baixo" : "Role para baixo"}</span>
      <span className="scroll-cue-line" />
    </div>
  );
}

function Hero() {
  return (
    <section className="hero" data-screen-label="01 Hero">
      <HeroDots count={36} />
      <ScrollCue />
      <div className="hero-stack">
        <Reveal delay={80} className="hero-group group-1">
          <div className="hero-line line-1"><HeroLineSvg text="Suas Fotos" target={580} /></div>
          <div className="hero-pill pill-1" aria-hidden="true">
            <img src="uploads/hero-pill-cap.png" alt="" fetchpriority="high" decoding="async" />
          </div>
        </Reveal>
        <Reveal delay={140} className="hero-group group-2">
          <div className="hero-pill pill-2" aria-hidden="true">
            <img src="uploads/hero-pill-sun.png" alt="" fetchpriority="high" decoding="async" />
          </div>
          <div className="hero-line line-2"><HeroLineSvg text="Feitas com IA" target={680} /></div>
        </Reveal>
        <Reveal delay={220} as="p" className="sub">
          Retratos profissionais com inteligência artificial.<br className="sub-br-mobile" />
          {" "}Sem estúdio. Sem fotógrafo. Sem sair de casa.
        </Reveal>
        <Reveal delay={280} className="cta-row">
          <a className="btn-edit" href={WHATSAPP_URL} target="_blank" rel="noreferrer">
            <span>Começar meu ensaio</span>
            <span className="arr"><Icon.Arrow size={16} /></span>
          </a>
        </Reveal>
      </div>
    </section>
  );
}

function Galeria() {
  const items = [
    { id: "01", src: "uploads/galeria%2001.jpg" },
    { id: "02", src: "uploads/galeria%2002.jpg" },
    { id: "03", src: "uploads/galeria%2003.jpg" },
    { id: "04", src: "uploads/galeria%2004.jpg" },
    { id: "05", src: "uploads/galeria%2005.jpg" },
    { id: "06", src: "uploads/galeria%2006.jpg" },
    { id: "07", src: "uploads/galeria%2007.jpg" },
    { id: "08", src: "uploads/galeria%2008.jpg" },
    { id: "09", src: "uploads/galeria%2009.jpg" },
  ];
  return (
    <section data-screen-label="02 Galeria">
      <div className="container">
        <div className="galeria-head">
          <Reveal as="h2">Galeria</Reveal>
        </div>
        <div className="gallery-grid">
          {items.map((it, i) => (
            <Reveal key={it.id} delay={i * 50} className="g-item">
              <Ph src={it.src} alt={`Portfólio ${it.id}`} />
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

function Servicos() {
  const items = [
    {
      n: "01",
      title: "Criação de foto com IA",
      desc: "Transformo suas selfies em retratos profissionais. Você escolhe o estilo (editorial, corporativo, artístico ou casual) e eu entrego o resultado em até 24h.",
    },
    {
      n: "02",
      title: "Pacote de ensaio",
      desc: "Pra quem quer variedade. Várias fotos em estilos diferentes, perfeito pra renovar o perfil, o LinkedIn e as redes de uma vez.",
    },
    {
      n: "03",
      title: "Restauração de foto",
      desc: "Fotos antigas, danificadas ou em baixa qualidade ganham vida nova com IA. Nitidez, cor e detalhes recuperados.",
    },
  ];
  return (
    <section className="servicos" data-screen-label="03 Serviços">
      <HeroDots count={24} />
      <div className="container">
        <div className="servicos-head">
          <Reveal as="h2">O que eu faço</Reveal>
        </div>
        <div className="serv-list">
          {items.map((it, i) => (
            <Reveal key={it.n} delay={i * 80} className="serv">
              <span className="serv-num">{it.n}</span>
              <h3 className="serv-title">{it.title}</h3>
              <p className="serv-desc">{it.desc}</p>
            </Reveal>
          ))}
        </div>
        <Reveal delay={120} className="servicos-cta">
          <a className="btn-edit" href={WHATSAPP_URL} target="_blank" rel="noreferrer">
            <span>Fale comigo no WhatsApp</span>
            <span className="arr"><Icon.Arrow size={16} /></span>
          </a>
        </Reveal>
      </div>
    </section>
  );
}

function Como() {
  const steps = [
    { n: "01", t: "Envie suas selfies", d: "3 fotos com boa iluminação, sem filtro, rosto visível." },
    { n: "02", t: "Escolha o estilo", d: "Editorial, profissional, artístico, casual. Você decide." },
    { n: "03", t: "Pagamento via Pix", d: "Rápido, sem cadastro, sem burocracia." },
    { n: "04", t: "Receba em 24h", d: "Fotos em alta resolução entregues direto no WhatsApp." },
  ];
  const stepDelays = [388, 1164, 1940, 2716];
  const gridRef = React.useRef(null);
  const [shownSteps, setShownSteps] = React.useState([false, false, false, false]);
  React.useEffect(() => {
    const el = gridRef.current;
    if (!el) return;
    const timers = [];
    const obs = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          el.classList.add("is-flowing");
          stepDelays.forEach((d, i) => {
            timers.push(
              setTimeout(() => {
                setShownSteps((prev) => {
                  const next = [...prev];
                  next[i] = true;
                  return next;
                });
              }, d)
            );
          });
          obs.disconnect();
        }
      },
      { threshold: 0.3 }
    );
    obs.observe(el);
    return () => {
      obs.disconnect();
      timers.forEach(clearTimeout);
    };
  }, []);
  return (
    <section data-screen-label="04 Como Funciona">
      <div className="container">
        <div className="como-head">
          <Reveal as="h2">Como funciona</Reveal>
        </div>
        <div className="como-grid" ref={gridRef}>
          <span className="como-flow" aria-hidden="true" />
          {steps.map((s, i) => (
            <div key={s.n} className={`como-step reveal${shownSteps[i] ? " is-in" : ""}`}>
              <div className="como-num">{s.n}</div>
              <div className="como-title">{s.t}</div>
              <div className="como-desc">{s.d}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function Sobre() {
  return (
    <section className="sobre" data-screen-label="05 Sobre Mim">
      <div className="sobre-grid">
        <Reveal className="sobre-photo">
          <img src="uploads/sobre-mim.png" alt="Alex Braz" className="sobre-portrait" loading="lazy" decoding="async" />
          <div className="sobre-photo-bg" aria-hidden="true" />
        </Reveal>
        <div className="sobre-text">
          <TypingText as="h2" text="Quem sou eu?" speed={40} />
          <TypingText
            as="p"
            text="Crio retratos e fotos profissionais usando inteligência artificial. Cada foto é construída como uma cena cinematográfica, com direção visual e iluminação pensada. Também faço restauração de fotos antigas. Mais de 6 anos de experiência e estudo constante. A IA evolui rápido, e meu trabalho acompanha esse ritmo."
            speed={12}
            startDelay={500}
          />
          <Reveal delay={220}><div className="sobre-rule" /></Reveal>
        </div>
      </div>
    </section>
  );
}

function CTAFinal() {
  return (
    <section className="cta-final" id="contato" data-screen-label="06 CTA Final">
      <HeroDots count={28} />
      <div className="container">
        <Reveal as="h2">Vamos criar as suas?</Reveal>
        <Reveal delay={100}><p className="sub">Envie suas selfies e receba fotos profissionais em até 24h.</p></Reveal>
        <Reveal delay={180} className="btn-row">
          <a className="btn-wa" href={WHATSAPP_URL} target="_blank" rel="noreferrer">
            <Icon.WhatsApp size={20} />
            <span>Chamar no WhatsApp</span>
            <Icon.Arrow size={16} />
          </a>
        </Reveal>
        <Reveal delay={240}>
          <div className="micro">
            <span>Atendimento humano</span>
            <span aria-hidden="true">—</span>
            <span>Sem robô</span>
            <span aria-hidden="true">—</span>
            <span>Sem cadastro</span>
          </div>
        </Reveal>
      </div>
    </section>
  );
}

function Footer() {
  return (
    <footer className="footer">
      <div className="container">
        <a className="ig" href="https://www.instagram.com/brazalex.ia/" target="_blank" rel="noreferrer" aria-label="Instagram">
          <img src="uploads/PERFIL-BAIXO.svg" alt="Instagram" className="ig-icon" loading="lazy" decoding="async" />
        </a>
        <div className="copy">© 2026 Alex Braz. Todos os direitos reservados.</div>
      </div>
    </footer>
  );
}

function ViewportBlurBottom() {
  const [hidden, setHidden] = React.useState(false);
  React.useEffect(() => {
    const target = document.querySelector(".footer");
    if (!target) return;
    const obs = new IntersectionObserver(
      ([entry]) => setHidden(entry.isIntersecting),
      { threshold: 0.05 }
    );
    obs.observe(target);
    return () => obs.disconnect();
  }, []);
  return (
    <span
      className={`viewport-blur-bottom${hidden ? " is-hidden" : ""}`}
      aria-hidden="true"
    />
  );
}

function FloatWA({ enabled }) {
  const [hideOnCta, setHideOnCta] = React.useState(false);
  React.useEffect(() => {
    if (!enabled) return;
    const target = document.querySelector(".cta-final");
    if (!target) return;
    const obs = new IntersectionObserver(
      ([entry]) => setHideOnCta(entry.isIntersecting),
      { threshold: 0.25 }
    );
    obs.observe(target);
    return () => obs.disconnect();
  }, [enabled]);
  if (!enabled) return null;
  return (
    <a
      className={`float-wa${hideOnCta ? " is-hidden" : ""}`}
      href={WHATSAPP_URL}
      target="_blank"
      rel="noreferrer"
      aria-label="Falar no WhatsApp"
    >
      <Icon.WhatsApp size={24} />
    </a>
  );
}

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  useEffect(() => {
    const update = () => {
      const s = Math.min(1, window.innerWidth / 1920);
      document.documentElement.style.setProperty("--hero-scale", String(s));
    };
    update();
    window.addEventListener("resize", update);
    return () => window.removeEventListener("resize", update);
  }, []);
  return (
    <React.Fragment>
      <main>
        <Hero />
        <Galeria />
        <Servicos />
        <Como />
        <Sobre />
        <CTAFinal />
      </main>
      <Footer />
      <FloatWA enabled={t.showFloat} />
      <ViewportBlurBottom />

      <TweaksPanel>
        <TweakSection label="Comportamento" />
        <TweakToggle label="Botão flutuante WhatsApp" value={t.showFloat} onChange={(v) => setTweak("showFloat", v)} />
      </TweaksPanel>
    </React.Fragment>
  );
}

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