// Seções: Hero, Public, Diferenciais, Depoimentos
const HERO_SLIDES = ["slide-01.webp", "assets/16.webp", "assets/05.webp", "assets/03.webp"];
const HERO_TW_WORDS = ["inesquecível.", "marcante.", "memorável."];

// Typewriter em loop: digita uma palavra, segura, apaga, e digita a próxima.
// Reserva a largura da palavra mais longa para não causar reflow.
const Typewriter = ({ words = [], delay = 400, perChar = 55, holdMs = 900, eraseMs = 30 }) => {
  const [text, setText] = React.useState("");

  React.useEffect(() => {
    let cancelled = false;
    let timeoutId;
    const wait = (ms) => new Promise((r) => { timeoutId = setTimeout(r, ms); });
    const run = async () => {
      await wait(delay);
      let i = 0;
      while (!cancelled) {
        const word = words[i % words.length];
        for (let c = 1; c <= word.length; c++) {
          if (cancelled) return;
          setText(word.slice(0, c));
          await wait(perChar);
        }
        await wait(holdMs);
        for (let c = word.length - 1; c >= 0; c--) {
          if (cancelled) return;
          setText(word.slice(0, c));
          await wait(eraseMs);
        }
        i++;
        await wait(250);
      }
    };
    run();
    return () => { cancelled = true; clearTimeout(timeoutId); };
  }, [words, delay, perChar, holdMs, eraseMs]);

  const longest = words.reduce((a, b) => (b.length > a.length ? b : a), "");

  return (
    <em style={{ fontStyle: "italic", color: "#E8C9A0", position: "relative", display: "inline-block" }}>
      <span aria-hidden="true" style={{ visibility: "hidden" }}>{longest}</span>
      <span className="tw-text" style={{ position: "absolute", left: 0, right: 0, top: 0, whiteSpace: "pre" }}>
        {text}
        <span className="tw-caret tw-caret-blink" aria-hidden="true">|</span>
      </span>
    </em>
  );
};

const HeroFull = () => {
  // idx começa em -1 para que o primeiro slide entre via transição (fade + zoom),
  // não renderizado já no estado final
  const [idx, setIdx] = React.useState(-1);
  React.useEffect(() => {
    const raf = requestAnimationFrame(() => setIdx(0));
    const t = setInterval(() => setIdx((i) => (i + 1) % HERO_SLIDES.length), 5500);
    return () => {
      cancelAnimationFrame(raf);
      clearInterval(t);
    };
  }, []);
  return (
    <section style={{ position: "relative", minHeight: "100vh", overflow: "hidden", background: "#1A0E08", display: "flex", flexDirection: "column" }}>
      {/* slideshow de fundo */}
      {HERO_SLIDES.map((src, i) => (
        <div key={src} style={{
          position: "absolute", inset: 0,
          backgroundImage: `url('${src}')`,
          backgroundSize: "cover",
          backgroundPosition: "center",
          filter: "brightness(0.42)",
          opacity: idx === i ? 1 : 0,
          transition: "opacity 1.6s cubic-bezier(.4,0,.2,1)",
          transform: idx === i ? "scale(1.04)" : "scale(1)",
          transitionProperty: "opacity, transform",
          transitionDuration: "1.6s, 7s",
        }} />
      ))}
      {/* gradient overlay */}
      <div style={{
        position: "absolute", inset: 0,
        background: "linear-gradient(180deg, rgba(20,10,6,.7) 0%, rgba(20,10,6,.5) 40%, rgba(20,10,6,.9) 100%)",
      }} />

      {/* nav */}
      <nav style={{
        position: "relative",
        display: "flex",
        justifyContent: "space-between",
        alignItems: "center",
        padding: "28px 56px",
        maxWidth: 1400,
        margin: "0 auto",
        width: "100%",
        zIndex: 5,
      }}>
        <Logo height={56} light />
        <div style={{
          display: "flex",
          gap: 48,
          fontFamily: "'Cormorant Garamond', serif",
          fontSize: 13,
          letterSpacing: "0.32em",
          textTransform: "uppercase",
          color: "#F5EFE6",
        }}>
          <a href="#publico" style={{ color: "inherit", textDecoration: "none" }}>Eventos</a>
          <a href="#galeria" style={{ color: "inherit", textDecoration: "none" }}>Mesas</a>
          <a href="#sobre" style={{ color: "inherit", textDecoration: "none" }}>Atelier</a>
          <a href="#orcamento" style={{ color: "inherit", textDecoration: "none" }}>Orçamento</a>
        </div>
      </nav>

      {/* conteúdo central — agora dentro de flex 1 para centralizar verticalmente */}
      <div style={{
        position: "relative",
        zIndex: 4,
        flex: 1,
        display: "flex",
        flexDirection: "column",
        justifyContent: "center",
        alignItems: "center",
        maxWidth: 1100,
        margin: "0 auto",
        padding: "60px 32px",
        textAlign: "center",
        color: "#F5EFE6",
        width: "100%",
      }}>
        <Reveal delay={300} as="h1" style={{
          fontFamily: "'Cormorant Garamond', serif",
          fontWeight: 300,
          fontSize: "clamp(64px, 6.8vw, 104px)",
          lineHeight: 0.82,
          letterSpacing: "-0.02em",
          margin: 0,
          textWrap: "balance",
        }}>
          Doces que<span className="hero-space"> </span><br className="hero-br-m" />tornam o<br />
          seu evento<span className="hero-space"> </span><br className="hero-br-m" /><Typewriter words={HERO_TW_WORDS} />
        </Reveal>

        <Reveal delay={600} style={{ marginTop: 48, display: "flex", flexDirection: "column", alignItems: "center", gap: 18 }}>
          <a href="#orcamento" className="hero-cta" style={{
            fontFamily: "'Cormorant Garamond', serif",
            fontSize: 14,
            letterSpacing: "0.34em",
            textTransform: "uppercase",
            color: "#1F1410",
            background: "#F5EFE6",
            textDecoration: "none",
            padding: "22px 48px",
            display: "inline-flex",
            alignItems: "center",
            justifyContent: "center",
            gap: 16,
            fontWeight: 500,
          }}>
            <span aria-hidden="true" style={{ visibility: "hidden" }}>→</span>
            <span>
              <span className="cta-text-desktop">Solicitar minha proposta personalizada</span>
              <span className="cta-text-mobile">Solicite sua proposta</span>
            </span>
            <span>→</span>
          </a>
          <a href="https://wa.me/5541987921533" style={{
            fontFamily: "'Cormorant Garamond', serif",
            fontSize: 20,
            fontStyle: "italic",
            color: "#E8C9A0",
            textDecoration: "none",
            opacity: 0.95,
          }}>
            <span className="cta-text-desktop">ou fale diretamente com a gente pelo WhatsApp ↓</span>
            <span className="cta-text-mobile">ou fale pelo WhatsApp ↓</span>
          </a>
        </Reveal>

        <Reveal delay={900} className="hero-stats" style={{
          marginTop: 72,
          display: "flex",
          justifyContent: "center",
          alignItems: "center",
          gap: 56,
          flexWrap: "wrap",
          fontFamily: "'Cormorant Garamond', serif",
        }}>
          <div style={{ textAlign: "center" }}>
            <RiseIn delay={1100} duration={1100} style={{
              fontSize: 36,
              fontWeight: 300,
              letterSpacing: "-0.02em",
              color: "#E8C9A0",
              lineHeight: 1.1,
            }}>+1.000</RiseIn>
            <div style={{
              marginTop: 10,
              fontSize: 12,
              letterSpacing: "0.32em",
              textTransform: "uppercase",
              color: "#F5EFE6",
              opacity: 0.85,
              fontWeight: 500,
            }}>Eventos realizados</div>
          </div>
          <div className="hero-stat-divider" style={{ width: 0.5, height: 44, background: "rgba(232,201,160,.4)" }} aria-hidden="true" />
          <div style={{ textAlign: "center" }}>
            <RiseIn delay={1300} duration={1100} style={{
              fontSize: 36,
              fontWeight: 300,
              letterSpacing: "-0.02em",
              color: "#E8C9A0",
              lineHeight: 1.1,
            }}>+10 anos</RiseIn>
            <div style={{
              marginTop: 10,
              fontSize: 12,
              letterSpacing: "0.32em",
              textTransform: "uppercase",
              color: "#F5EFE6",
              opacity: 0.85,
              fontWeight: 500,
            }}>de história</div>
          </div>
        </Reveal>
      </div>

      {/* scroll cue */}
      <div style={{
        position: "absolute",
        bottom: 28,
        left: "50%",
        transform: "translateX(-50%)",
        zIndex: 5,
        color: "#E8C9A0",
        opacity: 0.7,
        fontSize: 22,
        lineHeight: 1,
      }}>
        <span className="scroll-cue" style={{ display: "inline-block" }}>⌄</span>
      </div>
    </section>
  );
};

const Publico = () => {
  const cards = [
    {
      tag: "Casamentos",
      img: "casamento.webp",
      text: "Para o dia mais importante da sua vida, a mesa de doces precisa ser tão especial quanto tudo o mais que vocês planejaram. Criamos composições que emocionam, do primeiro olhar à última foto.",
      cta: "Ver opções",
    },
    {
      tag: "Festa de 15 Anos",
      img: "15-anos.webp",
      text: "O dia que ela vai lembrar para sempre começa com cada detalhe no lugar certo. Mesas que impressionam os convidados e ficam para sempre no álbum da debutante.",
      cta: "Ver opções",
    },
    {
      tag: "Corporativo",
      img: "corporativo.webp",
      text: "Da confraternização ao lançamento de produto: doces que elevam a experiência dos seus convidados e reforçam o padrão da sua empresa. Personalizados com a identidade da marca.",
      cta: "Ver opções",
    },
  ];
  return (
    <section id="publico" style={{ background: "#F5EFE6", padding: "140px 32px", color: "#1F1410" }}>
      <div style={{ maxWidth: 1280, margin: "0 auto" }}>
        <Reveal style={{ textAlign: "center", marginBottom: 24 }}>
          <Eyebrow>Para quem é</Eyebrow>
        </Reveal>
        <Reveal delay={150} as="h2" style={{
          fontFamily: "'Cormorant Garamond', serif",
          fontWeight: 300,
          fontSize: "clamp(36px, 4.5vw, 64px)",
          lineHeight: 1.05,
          letterSpacing: "-0.01em",
          margin: 0,
          textAlign: "center",
          textWrap: "balance",
        }}>
          Para eventos que <em style={{ fontStyle: "italic", color: "#6B3D2A" }}>merecem o melhor</em>.
        </Reveal>

        <div className="public-grid" style={{ marginTop: 80 }}>
          {cards.map((c, i) => (
            <Reveal key={i} delay={i * 150}>
              <article className="public-card">
                <div className="public-card-img" style={{ backgroundImage: `url('${c.img}')` }} />
                <div style={{ padding: "32px 28px 28px" }}>
                  <div style={{
                    fontFamily: "'Cormorant Garamond', serif",
                    fontSize: 11,
                    letterSpacing: "0.42em",
                    textTransform: "uppercase",
                    color: "#6B3D2A",
                  }}>
                    {String(i + 1).padStart(2, "0")} · {c.tag}
                  </div>
                  <h3 style={{
                    fontFamily: "'Cormorant Garamond', serif",
                    fontWeight: 300,
                    fontSize: 32,
                    lineHeight: 1.1,
                    margin: "12px 0 0",
                    letterSpacing: "-0.005em",
                  }}>
                    {c.tag}
                  </h3>
                  <p style={{
                    fontFamily: "'Cormorant Garamond', serif",
                    fontSize: 17,
                    lineHeight: 1.55,
                    margin: "20px 0 0",
                    color: "#3D2418",
                    opacity: 0.85,
                  }}>
                    {c.text}
                  </p>
                  <a href="#orcamento" className="card-link">
                    {c.cta} <span style={{ marginLeft: 8 }}>→</span>
                  </a>
                </div>
              </article>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
};

const Diferenciais = () => {
  const blocks = [
    {
      title: "Doces que impressionam o olhar e o paladar",
      text: "Cada peça é pensada como uma obra: técnica refinada, controle absoluto do processo e o nível de exigência que faz da mesa SW uma experiência sensorial completa. Sofisticação que se sente antes mesmo de provar.",
      symbol: "I",
    },
    {
      title: "Uma mesa com a sua história",
      text: "Não basta ser diferente da mesa de outra pessoa — precisa ser única para você. Criamos doces que carregam a memória do casal, momentos da debutante, símbolos da marca. Cada mesa tem significado, porque é o seu evento, e ele importa.",
      symbol: "II",
    },
    {
      title: "Degustação como ninguém faz",
      text: "Aqui você não escolhe a partir de uma planilha. Recebemos você no atelier com uma mesa montada, cheia de encanto — ou enviamos uma caixa para provar em casa, no seu tempo. Você experimenta exatamente o que vai para o seu orçamento.",
      symbol: "III",
    },
    {
      title: "+10 anos vivendo cada momento",
      text: "Não acompanhamos esses momentos de longe — participamos deles. Mais de 1.000 eventos em Curitiba: casamentos nos espaços mais elegantes, festas de 15 anos memoráveis e eventos corporativos que viraram referência. Uma década criando os doces e montando as mesas que ficaram na memória.",
      symbol: "IV",
    },
  ];
  return (
    <section style={{
      background: "#1F1410",
      color: "#F5EFE6",
      padding: "140px 32px",
      position: "relative",
    }}>
      <div style={{ maxWidth: 1180, margin: "0 auto" }}>
        <Reveal style={{ textAlign: "center", marginBottom: 24 }}>
          <Eyebrow color="#D9B68A">Por que SW</Eyebrow>
        </Reveal>
        <Reveal delay={150} as="h2" style={{
          fontFamily: "'Cormorant Garamond', serif",
          fontWeight: 300,
          fontSize: "clamp(36px, 4.5vw, 64px)",
          lineHeight: 1.05,
          letterSpacing: "-0.01em",
          textAlign: "center",
          margin: 0,
          textWrap: "balance",
        }}>
          O que faz uma <em style={{ fontStyle: "italic", color: "#E8C9A0" }}>mesa SW</em> ser diferente.
        </Reveal>

        <div className="diff-grid" style={{ marginTop: 100 }}>
          {blocks.map((b, i) => (
            <Reveal key={i} delay={i * 100} className="diff-block">
              <div className="diff-num" style={{
                fontFamily: "'Cormorant Garamond', serif",
                fontStyle: "italic",
                fontSize: 56,
                fontWeight: 300,
                color: "#D9B68A",
                lineHeight: 1,
                marginBottom: 24,
                opacity: 0.5,
              }}>
                {b.symbol}
              </div>
              <h3 style={{
                fontFamily: "'Cormorant Garamond', serif",
                fontWeight: 400,
                fontSize: 28,
                margin: 0,
                letterSpacing: "-0.005em",
                lineHeight: 1.2,
              }}>
                {b.title}
              </h3>
              <p style={{
                fontFamily: "'Cormorant Garamond', serif",
                fontSize: 17,
                lineHeight: 1.6,
                marginTop: 18,
                opacity: 0.78,
              }}>
                {b.text}
              </p>
            </Reveal>
          ))}
        </div>

        <Reveal delay={500} style={{ textAlign: "center", marginTop: 88 }}>
          <a href="#orcamento" className="hero-cta" style={{
            fontFamily: "'Cormorant Garamond', serif",
            fontSize: 14,
            letterSpacing: "0.34em",
            textTransform: "uppercase",
            color: "#1F1410",
            background: "#F5EFE6",
            textDecoration: "none",
            padding: "22px 48px",
            display: "inline-flex",
            alignItems: "center",
            gap: 16,
            fontWeight: 500,
          }}>
            <span className="cta-text-desktop">Quero minha proposta personalizada</span>
            <span className="cta-text-mobile">Solicite sua proposta</span>
            <span>→</span>
          </a>
        </Reveal>
      </div>
    </section>
  );
};

const Depoimentos = () => {
  const items = [
    {
      text: "Foi incrível, um dia perfeito! Os doces uma delícia e a mesa impecável! Os convidados elogiaram, amaram! Bolo maravilhoso — o mais lindo que eu já vi. Do jeitinho que eu imaginei, vocês arrasaram muito.",
      name: "Alyne & Rodolfo",
      event: "Casamento · Luz da Mata",
    },
    {
      text: "Desde que olhamos os doces no cardápio já ficamos encantados. Não poderíamos ter escolhido melhor fornecedor — todos os convidados foram só elogios, sabor irresistível e cuidado em cada finalização.",
      name: "Nath & André",
      event: "Casamento · Cinco Elementos",
    },
    {
      text: "Foi o auge da nossa festa, todo mundo elogiou muito. Que bom que escolhemos vocês para fazerem parte do nosso dia, estava espetacular. Obrigada por tanto capricho e carinho conosco.",
      name: "Gabriela & Lucas",
      event: "Casamento · Agora a Noiva",
    },
    {
      text: "Estamos totalmente felizes por tudo. Atendente sempre atenciosa, docinhos maravilhosos, muitos elogios. O bolo ótimo. Tudo perfeito, obrigado pelo trabalho de vocês. Gratidão!",
      name: "André & Renata",
      event: "Casamento · Haras",
    },
    {
      text: "Que delícia! Uma perfeição, capricho e delicadeza em cada detalhe. Nós amamos e o feedback dos convidados foi maravilhoso. Parabéns a toda equipe pela dedicação em tornar esse dia ainda mais especial.",
      name: "Ingrid & Felipe",
      event: "Casamento · Haras",
    },
    {
      text: "Gente, eu não tenho palavras para dizer como estavam perfeitos os doces! Que mesa maravilhosa, tudo perfeito. Vocês foram incríveis desde o início. Irretocáveis. Obrigada por terem feito parte deste momento.",
      name: "Rafa & Raul",
      event: "Casamento · Chácara Silvestre",
    },
    {
      text: "Foi tudo maravilhoso, queria agradecer demais! Maravilhosos os doces, só elogios a vocês. Minha gratidão eterna.",
      name: "Andréa",
      event: "Festa de 15 Anos · Castelo do Batel",
    },
    {
      text: "Foi um sucesso. Doces foram muito elogiados — o morango com chocolate foi a perdição. A mesa de vocês fez bastante sucesso. Já colocamos vocês no nosso hall de fornecedores.",
      name: "T.R.T",
      event: "Evento Corporativo · Curitibano",
    },
    {
      text: "A festa foi sensacional e os doces estavam maravilhosos. O quindim estava ótimo, o bombom de morango não sobrou nenhum. Obrigada pelo carinho e por participarem desse dia com a gente!",
      name: "Ana Paula & Jader",
      event: "Casamento · Opera",
    },
  ];
  // Duplicado para criar loop sem costura no carrossel horizontal
  const loop = [...items, ...items];
  return (
    <section style={{ background: "#F5EFE6", padding: "140px 0", color: "#1F1410" }}>
      <div style={{ maxWidth: 1280, margin: "0 auto", padding: "0 32px" }}>
        <Reveal style={{ textAlign: "center", marginBottom: 24 }}>
          <Eyebrow>Prova social</Eyebrow>
        </Reveal>
        <Reveal delay={150} as="h2" style={{
          fontFamily: "'Cormorant Garamond', serif",
          fontWeight: 300,
          fontSize: "clamp(34px, 4.2vw, 60px)",
          lineHeight: 1.05,
          textAlign: "center",
          margin: 0,
          textWrap: "balance",
          letterSpacing: "-0.01em",
        }}>
          O que dizem as famílias <em style={{ fontStyle: "italic", color: "#6B3D2A" }}>que confiaram</em> na SW.
        </Reveal>
      </div>

      <Reveal delay={250} className="dep-carousel" style={{ marginTop: 80 }}>
        <div className="dep-track">
          {loop.map((d, i) => (
            <div key={i} className="dep-card" aria-hidden={i >= items.length ? "true" : undefined}>
              <div style={{
                fontFamily: "'Cormorant Garamond', serif",
                fontStyle: "italic",
                fontSize: 80,
                lineHeight: 0.5,
                color: "#6B3D2A",
                opacity: 0.4,
                height: 32,
              }}>"</div>
              <p style={{
                fontFamily: "'Cormorant Garamond', serif",
                fontSize: 19,
                lineHeight: 1.55,
                fontStyle: "italic",
                color: "#1F1410",
                margin: "12px 0 32px",
                fontWeight: 400,
              }}>
                {d.text}
              </p>
              <div style={{
                paddingTop: 20,
                borderTop: "0.5px solid rgba(31,20,16,.2)",
              }}>
                <div style={{
                  fontFamily: "'Cormorant Garamond', serif",
                  fontSize: 18,
                  fontWeight: 500,
                  color: "#1F1410",
                }}>{d.name}</div>
                <div style={{
                  fontFamily: "'Cormorant Garamond', serif",
                  fontSize: 12,
                  letterSpacing: "0.28em",
                  textTransform: "uppercase",
                  color: "#6B3D2A",
                  marginTop: 6,
                }}>{d.event}</div>
              </div>
            </div>
          ))}
        </div>
      </Reveal>

      <div style={{ maxWidth: 1280, margin: "0 auto", padding: "0 32px" }}>

        <Reveal delay={400} style={{ textAlign: "center", marginTop: 80 }}>
          <a href="#orcamento" className="hero-cta" style={{
            fontFamily: "'Cormorant Garamond', serif",
            fontSize: 14,
            letterSpacing: "0.34em",
            textTransform: "uppercase",
            color: "#F5EFE6",
            background: "#1F1410",
            textDecoration: "none",
            padding: "22px 48px",
            display: "inline-flex",
            alignItems: "center",
            gap: 16,
            fontWeight: 500,
          }}>
            <span className="cta-text-desktop">Quero minha proposta personalizada</span>
            <span className="cta-text-mobile">Solicite sua proposta</span>
            <span>→</span>
          </a>
        </Reveal>
      </div>
    </section>
  );
};

window.HeroFull = HeroFull;
window.Publico = Publico;
window.Diferenciais = Diferenciais;
window.Depoimentos = Depoimentos;
