// Galeria — todas as fotos em ASCII slug (foto-01.webp ... foto-36.webp).
// Mostra 10 iniciais (padrão 2,1,1,2,1,1,1,1,1,1 = 12 células = 3 linhas limpas)
// e libera o resto via botão "Ver mais fotos" (padrão 2,1,1 cíclico).
const CARROSSEL_DIR = "carrossel";
const TOTAL_FOTOS = 36;
const galleryImages = Array.from({ length: TOTAL_FOTOS }, (_, i) =>
  `${CARROSSEL_DIR}/foto-${String(i + 1).padStart(2, "0")}.webp`
);
const INITIAL_SHOWN = 10;
// rs (row-span) por posição — mantém o mosaico tall/small
const getRs = (i) => {
  if (i < INITIAL_SHOWN) return (i === 0 || i === 3) ? 2 : 1;
  return ((i - INITIAL_SHOWN) % 3 === 0) ? 2 : 1;
};

const Galeria = () => {
  const [lightbox, setLightbox] = React.useState(null);
  const [allOpen, setAllOpen] = React.useState(false);
  const visible = galleryImages.slice(0, INITIAL_SHOWN);
  const hasMore = galleryImages.length > INITIAL_SHOWN;
  // trava o scroll do body enquanto o modal está aberto
  React.useEffect(() => {
    if (!allOpen) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    const onEsc = (e) => { if (e.key === "Escape") setAllOpen(false); };
    window.addEventListener("keydown", onEsc);
    return () => {
      document.body.style.overflow = prev;
      window.removeEventListener("keydown", onEsc);
    };
  }, [allOpen]);
  return (
    <section id="galeria" style={{ background: "#1F1410", padding: "140px 32px 100px", color: "#F5EFE6" }}>
      <div style={{ maxWidth: 1400, margin: "0 auto" }}>
        <Reveal style={{ textAlign: "center", marginBottom: 24 }}>
          <Eyebrow color="#D9B68A">Portfólio</Eyebrow>
        </Reveal>
        <Reveal delay={150} as="h2" style={{
          fontFamily: "'Cormorant Garamond', serif",
          fontWeight: 300,
          fontSize: "clamp(36px, 4.5vw, 64px)",
          lineHeight: 1.05,
          textAlign: "center",
          margin: 0,
          letterSpacing: "-0.01em",
        }}>
          Mesas que <em style={{ fontStyle: "italic", color: "#E8C9A0" }}>ficam na memória</em>.
        </Reveal>

        <div className="gallery-mosaic" style={{ marginTop: 80 }}>
          {visible.map((src, i) => (
            <Reveal key={src} delay={(i % 4) * 80} className={`g-item g-rs${getRs(i)}`}>
              <button onClick={() => setLightbox(src)} className="g-btn" aria-label="Ampliar imagem">
                <img src={src} alt="" loading="lazy" decoding="async" width="800" height="800" />
              </button>
            </Reveal>
          ))}
        </div>

        {hasMore && (
          <Reveal style={{ textAlign: "center", marginTop: 56 }}>
            <button
              onClick={() => setAllOpen(true)}
              className="hero-cta"
              style={{
                fontFamily: "'Cormorant Garamond', serif",
                fontSize: 14,
                letterSpacing: "0.34em",
                textTransform: "uppercase",
                color: "#F5EFE6",
                background: "transparent",
                border: "0.5px solid #D9B68A",
                padding: "20px 44px",
                display: "inline-flex",
                alignItems: "center",
                gap: 16,
                fontWeight: 500,
                cursor: "pointer",
              }}
            >
              Ver mais fotos <span>→</span>
            </button>
          </Reveal>
        )}

        <Reveal delay={300} style={{
          marginTop: 80,
          textAlign: "center",
          padding: "60px 32px",
          borderTop: "0.5px solid rgba(245,239,230,.2)",
          borderBottom: "0.5px solid rgba(245,239,230,.2)",
        }}>
          <p style={{
            fontFamily: "'Cormorant Garamond', serif",
            fontSize: "clamp(24px, 3vw, 36px)",
            fontStyle: "italic",
            fontWeight: 300,
            margin: 0,
            opacity: 0.92,
          }}>
            Cada mesa é única, como o seu evento.
          </p>
          <a href="#orcamento" className="hero-cta" style={{
            marginTop: 32,
            display: "inline-flex",
            fontFamily: "'Cormorant Garamond', serif",
            fontSize: 14,
            letterSpacing: "0.32em",
            textTransform: "uppercase",
            color: "#1F1410",
            background: "#E8C9A0",
            textDecoration: "none",
            padding: "20px 44px",
            alignItems: "center",
            gap: 16,
            fontWeight: 500,
          }}>
            <span className="cta-text-desktop">Solicitar proposta personalizada</span>
            <span className="cta-text-mobile">Solicite sua proposta</span>
            <span>→</span>
          </a>
        </Reveal>
      </div>

      {/* Modal "Ver mais fotos" — só renderiza no DOM quando aberto, pra não baixar as 26 fotos extras antes da hora */}
      {allOpen && (
        <div onClick={() => setAllOpen(false)} style={{
          position: "fixed",
          inset: 0,
          background: "rgba(10,5,3,.96)",
          zIndex: 150,
          overflowY: "auto",
          padding: "80px 32px 60px",
        }}>
          <button onClick={() => setAllOpen(false)} style={{
            position: "fixed", top: 24, right: 24,
            background: "transparent", border: "0.5px solid #F5EFE6",
            color: "#F5EFE6",
            fontFamily: "'Cormorant Garamond', serif",
            fontSize: 12, letterSpacing: "0.32em", textTransform: "uppercase",
            padding: "12px 24px", cursor: "pointer",
            zIndex: 160,
          }}>Fechar ✕</button>
          <div onClick={(e) => e.stopPropagation()} style={{ maxWidth: 1400, margin: "0 auto" }}>
            <div style={{ textAlign: "center", marginBottom: 16 }}>
              <Eyebrow color="#D9B68A">Galeria completa</Eyebrow>
            </div>
            <h3 style={{
              fontFamily: "'Cormorant Garamond', serif",
              fontWeight: 300,
              fontSize: "clamp(28px, 3.5vw, 44px)",
              textAlign: "center",
              color: "#F5EFE6",
              margin: "0 0 48px",
              letterSpacing: "-0.01em",
            }}>
              Todas as <em style={{ fontStyle: "italic", color: "#E8C9A0" }}>mesas SW</em>.
            </h3>
            <div className="gallery-modal-grid">
              {galleryImages.map((src) => (
                <button
                  key={src}
                  onClick={() => setLightbox(src)}
                  className="g-btn"
                  aria-label="Ampliar imagem"
                  style={{ aspectRatio: "1/1" }}
                >
                  <img src={src} alt="" loading="lazy" decoding="async" width="800" height="800" />
                </button>
              ))}
            </div>
          </div>
        </div>
      )}

      {lightbox && (
        <div onClick={() => setLightbox(null)} style={{
          position: "fixed",
          inset: 0,
          background: "rgba(10,5,3,.94)",
          zIndex: 200,
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          cursor: "zoom-out",
          padding: 40,
        }}>
          <img src={lightbox} alt="" decoding="async" style={{ maxWidth: "90%", maxHeight: "90vh", objectFit: "contain", boxShadow: "0 40px 80px rgba(0,0,0,.6)" }} />
          <button onClick={() => setLightbox(null)} style={{
            position: "absolute", top: 32, right: 32,
            background: "transparent", border: "0.5px solid #F5EFE6",
            color: "#F5EFE6",
            fontFamily: "'Cormorant Garamond', serif",
            fontSize: 12, letterSpacing: "0.32em", textTransform: "uppercase",
            padding: "12px 24px", cursor: "pointer",
          }}>Fechar ✕</button>
        </div>
      )}
    </section>
  );
};

// Cada passo observa sua própria entrada em view — assim no mobile a "pérola" e a
// linha conectora animam conforme o usuário desce a página (e não tudo de uma vez).
const ProcessStep = ({ s, total }) => {
  const [ref, shown] = useReveal(0.3);
  return (
    <div ref={ref} className={`step-block${shown ? " in-view-block" : ""}`}>
      <span className="step-station" aria-hidden="true" />
      <span className="step-line" aria-hidden="true" />
      <div className="step-num" style={{
        fontFamily: "'Cormorant Garamond', serif",
        fontSize: 13,
        letterSpacing: "0.32em",
        color: "#8B4F36",
        marginBottom: 18,
        paddingBottom: 18,
      }}>
        {s.n} / {total}
      </div>
      <h3 style={{
        fontFamily: "'Cormorant Garamond', serif",
        fontWeight: 400,
        fontSize: 24,
        margin: 0,
        lineHeight: 1.2,
        letterSpacing: "-0.005em",
      }}>{s.title}</h3>
      <p style={{
        fontFamily: "'Cormorant Garamond', serif",
        fontSize: 16,
        lineHeight: 1.6,
        marginTop: 16,
        color: "#3D2418",
        opacity: 0.85,
      }}>{s.text}</p>
    </div>
  );
};

const ComoFunciona = () => {
  const steps = [
    { n: "01", title: "Você nos conta sobre o evento", text: "Preencha o formulário ou fale com a gente pelo WhatsApp. Quanto mais detalhes você puder compartilhar, melhor." },
    { n: "02", title: "Entendemos a sua visão", text: "Em até 24 horas entramos em contato. Conversamos para entender como vocês sonharam esse dia, suas preferências e o que é fundamental para você." },
    { n: "03", title: "Degustação personalizada", text: "Recebemos você no atelier com uma mesa montada cheia de encanto, ou enviamos uma caixa para experimentar em casa. Você prova exatamente o que vai para o seu evento." },
    { n: "04", title: "Sua proposta exclusiva", text: "A partir do que conversamos e do que você experimentou, montamos uma proposta personalizada, clara e objetiva — feita para refletir exatamente o que vocês imaginaram." },
    { n: "05", title: "A SW cuida de tudo até o grande dia", text: "Da produção à montagem no evento, você se dedica ao que realmente importa. Nossa equipe garante que a mesa vai estar exatamente como vocês sonharam." },
  ];
  const total = String(steps.length).padStart(2, "0");
  const [gridRef, gridShown] = useReveal(0.2);
  return (
    <section style={{ background: "#F5EFE6", padding: "140px 32px", color: "#1F1410" }}>
      <div style={{ maxWidth: 1400, margin: "0 auto" }}>
        <Reveal style={{ textAlign: "center", marginBottom: 24 }}>
          <Eyebrow>Processo</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,
          letterSpacing: "-0.01em",
          textWrap: "balance",
        }}>
          Do primeiro contato ao grande dia, <em style={{ fontStyle: "italic", color: "#6B3D2A" }}>sem complicação</em>.
        </Reveal>

        <div ref={gridRef} className={`steps-grid${gridShown ? " in-view" : ""}`} style={{ marginTop: 100 }}>
          <span className="steps-thread" aria-hidden="true" />
          {steps.map((s, i) => (
            <ProcessStep key={i} s={s} total={total} />
          ))}
        </div>
      </div>
    </section>
  );
};

// Anima um número de 0 → target quando entra no viewport.
// Para valores não-numéricos (CWB), só faz fade-in.
const CountUp = ({ value, duration = 1600, style }) => {
  const ref = React.useRef(null);
  const [display, setDisplay] = React.useState(value);
  const [started, setStarted] = React.useState(false);

  // Parse: extrai número, prefixo, sufixo. Suporta "4,7" (vírgula decimal) e
  // "1.000"/"10.000" (ponto como separador de milhar, padrão BR).
  const parsed = React.useMemo(() => {
    const m = String(value).match(/^([^\d]*)(\d+(?:[.,]\d+)?)(.*)$/);
    if (!m) return null;
    const numStr = m[2];
    // Heurística: "X.YYY" com exatamente 3 dígitos depois → separador de milhar
    const sep = numStr.match(/^(\d+)[.,](\d+)$/);
    if (sep && sep[2].length === 3) {
      return { prefix: m[1], target: parseInt(sep[1] + sep[2], 10), decimals: 0, suffix: m[3], thousand: true };
    }
    const decimals = numStr.includes(",") ? numStr.split(",")[1].length
                   : numStr.includes(".") ? numStr.split(".")[1].length : 0;
    const target = parseFloat(numStr.replace(",", "."));
    return { prefix: m[1], target, decimals, suffix: m[3], thousand: false };
  }, [value]);

  const formatNumber = (cur, parsed) => {
    if (parsed.decimals > 0) return cur.toFixed(parsed.decimals).replace(".", ",");
    if (parsed.thousand) return Math.round(cur).toLocaleString("pt-BR");
    return Math.round(cur).toString();
  };

  React.useEffect(() => {
    if (!parsed) { setDisplay(value); return; }
    setDisplay(`${parsed.prefix}${formatNumber(0, parsed)}${parsed.suffix}`);
    const node = ref.current;
    if (!node) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting && !started) {
          setStarted(true);
          const start = performance.now();
          const tick = (now) => {
            const t = Math.min(1, (now - start) / duration);
            const eased = 1 - Math.pow(1 - t, 3); // easeOutCubic
            const cur = parsed.target * eased;
            setDisplay(`${parsed.prefix}${formatNumber(cur, parsed)}${parsed.suffix}`);
            if (t < 1) requestAnimationFrame(tick);
          };
          requestAnimationFrame(tick);
        }
      });
    }, { threshold: 0.4 });
    io.observe(node);
    return () => io.disconnect();
  }, [parsed, duration, started, value]);

  return <span ref={ref} style={style}>{display}</span>;
};

const Sobre = () => {
  const parallaxRef = useParallax(0.06);
  return (
    <section id="sobre" style={{ background: "#1F1410", color: "#F5EFE6", padding: "140px 32px", overflow: "hidden" }}>
      <div className="sobre-grid" style={{ maxWidth: 1280, margin: "0 auto" }}>
        <div ref={parallaxRef} style={{ willChange: "transform" }}>
          <Reveal y={40}>
            <div style={{
              position: "relative",
              aspectRatio: "4/5",
              background: "url('cliedeeclovis.webp') center/cover",
              borderRadius: 0,
            }}>
              <div className="sobre-badge" style={{
                position: "absolute",
                bottom: -28,
                right: -28,
                width: 130,
                height: 130,
                borderRadius: "50%",
                background: "rgba(31, 20, 16, 0.45)",
                backdropFilter: "blur(14px) saturate(150%)",
                WebkitBackdropFilter: "blur(14px) saturate(150%)",
                border: "0.5px solid rgba(232, 201, 160, 0.4)",
                boxShadow: "0 12px 32px rgba(0, 0, 0, 0.35), inset 0 1px 0 rgba(255, 255, 255, 0.06)",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
              }}>
                <svg className="badge-rotate" viewBox="0 0 130 130" width="130" height="130" style={{ position: "absolute", inset: 0 }}>
                  <defs>
                    <path id="ct" d="M 65,65 m -50,0 a 50,50 0 1,1 100,0 a 50,50 0 1,1 -100,0" />
                  </defs>
                  <text fontFamily="'Cormorant Garamond', serif" fontSize="9" fill="#D9B68A" textLength="312" lengthAdjust="spacing">
                    <textPath href="#ct" startOffset="0">ATELIER SW · DOCES FINOS · CURITIBA</textPath>
                  </text>
                </svg>
                <Logo height={42} light />
              </div>
            </div>
          </Reveal>
        </div>

        <div>
          <Reveal>
            <Eyebrow color="#D9B68A" lines={false}>Nossa história</Eyebrow>
          </Reveal>
          <Reveal delay={150} as="h2" style={{
            fontFamily: "'Cormorant Garamond', serif",
            fontWeight: 300,
            fontSize: "clamp(34px, 4vw, 56px)",
            lineHeight: 1.05,
            margin: "20px 0 0",
            letterSpacing: "-0.01em",
            textWrap: "balance",
          }}>
            Por trás de cada mesa,<br />
            <em style={{ fontStyle: "italic", color: "#E8C9A0" }}>
              uma história de <RiseIn delay={500} duration={1200} innerStyle={{ fontStyle: "italic" }}>+10 anos.</RiseIn>
            </em>
          </Reveal>

          <Reveal delay={350} style={{
            fontFamily: "'Cormorant Garamond', serif",
            fontSize: 19,
            lineHeight: 1.6,
            marginTop: 36,
            opacity: 0.85,
          }}>
            <p style={{ margin: 0 }}>
              A SW Doces Exclusivos nasceu da paixão da Chef Cleide pela confeitaria fina de alta qualidade. Em +10 anos, foram mais de 1.000 eventos em Curitiba: casamentos nos espaços mais elegantes da cidade, festas de 15 anos inesquecíveis e eventos corporativos de marcas que entendem que cada detalhe comunica.
            </p>
            <p style={{ marginTop: 24, marginBottom: 0 }}>
              Cada mesa que sai do nosso atelier tem o cuidado de quem sabe que está fazendo parte de um momento que vai ficar na memória <em style={{ fontStyle: "italic", color: "#E8C9A0" }}>para sempre</em>.
            </p>
          </Reveal>

          <Reveal delay={550} style={{
            marginTop: 56,
            display: "grid",
            gridTemplateColumns: "repeat(2, 1fr)",
            gap: "32px 48px",
          }}>
            {[
              { n: "+1.000", l: "Eventos\nrealizados" },
              { n: "+10", l: "Anos de\nmercado" },
              { n: "Sob medida", l: "Para cada\nevento" },
              { n: "CWB + SC", l: "Curitiba e\nlitoral de SC" },
            ].map((s, i) => (
              <div key={i} style={{ borderTop: "0.5px solid rgba(245,239,230,.2)", paddingTop: 20 }}>
                <RiseIn delay={150 + i * 180} duration={1100} style={{
                  display: "block",
                  fontFamily: "'Cormorant Garamond', serif",
                  fontSize: 38,
                  fontWeight: 300,
                  letterSpacing: "-0.02em",
                  lineHeight: 1.15,
                  color: "#E8C9A0",
                }}>
                  <CountUp value={s.n} />
                </RiseIn>
                <div style={{
                  marginTop: 10,
                  fontSize: 11,
                  letterSpacing: "0.32em",
                  textTransform: "uppercase",
                  fontFamily: "'Cormorant Garamond', serif",
                  whiteSpace: "pre-line",
                  lineHeight: 1.5,
                  opacity: 0.7,
                }}>
                  {s.l}
                </div>
              </div>
            ))}
          </Reveal>
        </div>
      </div>
    </section>
  );
};

const FAQ = () => {
  const items = [
    {
      q: "Quanto tempo antes do evento devo entrar em contato?",
      a: "Quanto antes, melhor — especialmente para casamentos. Trabalhamos com um número limitado de eventos por mês para garantir o cuidado que cada um merece, e datas específicas têm demanda alta. Entre em contato com a maior antecedência possível para reservar a sua data na nossa agenda.",
    },
    {
      q: "Vocês atendem em qual região?",
      a: "Atendemos Curitiba e toda a Região Metropolitana, e também outros estados — com presença frequente no litoral de Santa Catarina. Para eventos em outras localidades, entre em contato e avaliamos juntos.",
    },
    {
      q: "Como funciona o orçamento?",
      a: "É simples: você preenche o formulário ou fala com a gente pelo WhatsApp. Em até 24 horas, enviamos uma proposta personalizada — clara, objetiva, pensada a partir do que conversamos. Sem compromisso.",
    },
    {
      q: "Vocês fazem degustação?",
      a: "Sim, e essa é uma das partes que mais gostamos do processo. A degustação pode ser presencial no nosso atelier, com uma mesa montada para você sentir como ficará no evento — ou enviamos uma caixa para você provar em casa, no seu tempo. Você escolhe o formato que faz mais sentido para vocês.",
    },
    {
      q: "É possível personalizar os doces com a identidade do evento?",
      a: "Sim, personalização é parte central da nossa proposta. Paleta de cores, decoração temática, embalagem assinada para bem-casados, bolos exclusivos criados a partir da história de vocês. Tudo é planejado junto com você.",
    },
  ];
  const [open, setOpen] = React.useState(0);
  return (
    <section style={{ background: "#F5EFE6", padding: "140px 32px", color: "#1F1410" }}>
      <div style={{ maxWidth: 880, margin: "0 auto" }}>
        <Reveal style={{ textAlign: "center", marginBottom: 24 }}>
          <Eyebrow>Dúvidas</Eyebrow>
        </Reveal>
        <Reveal delay={150} as="h2" style={{
          fontFamily: "'Cormorant Garamond', serif",
          fontWeight: 300,
          fontSize: "clamp(34px, 4.2vw, 56px)",
          lineHeight: 1.05,
          textAlign: "center",
          margin: 0,
          letterSpacing: "-0.01em",
        }}>
          Perguntas <em style={{ fontStyle: "italic", color: "#6B3D2A" }}>frequentes</em>.
        </Reveal>

        <div style={{ marginTop: 72 }}>
          {items.map((it, i) => {
            const isOpen = open === i;
            return (
              <Reveal key={i} delay={i * 60}>
                <div style={{ borderTop: i === 0 ? "0.5px solid rgba(31,20,16,.2)" : "none", borderBottom: "0.5px solid rgba(31,20,16,.2)" }}>
                  <button
                    onClick={() => setOpen(isOpen ? -1 : i)}
                    style={{
                      width: "100%",
                      background: "none",
                      border: "none",
                      padding: "28px 0",
                      display: "flex",
                      justifyContent: "space-between",
                      alignItems: "center",
                      cursor: "pointer",
                      textAlign: "left",
                      fontFamily: "'Cormorant Garamond', serif",
                      fontSize: 22,
                      fontWeight: 400,
                      color: "#1F1410",
                    }}
                  >
                    <span style={{ paddingRight: 24 }}>{it.q}</span>
                    <span style={{
                      fontStyle: "italic",
                      color: "#6B3D2A",
                      fontSize: 28,
                      transform: isOpen ? "rotate(45deg)" : "rotate(0)",
                      transition: "transform .4s",
                      fontWeight: 300,
                    }}>+</span>
                  </button>
                  <div style={{
                    maxHeight: isOpen ? 400 : 0,
                    overflow: "hidden",
                    transition: "max-height .5s cubic-bezier(.22,.61,.36,1)",
                  }}>
                    <p style={{
                      fontFamily: "'Cormorant Garamond', serif",
                      fontSize: 17,
                      lineHeight: 1.6,
                      color: "#3D2418",
                      opacity: 0.85,
                      margin: 0,
                      padding: "0 60px 28px 0",
                    }}>{it.a}</p>
                  </div>
                </div>
              </Reveal>
            );
          })}
        </div>
      </div>
    </section>
  );
};

window.Galeria = Galeria;
window.ComoFunciona = ComoFunciona;
window.Sobre = Sobre;
window.FAQ = FAQ;
