// Seções narrativas da página de upsell
const { useState, useEffect, useRef } = React;

// Hook simples para fade-in ao entrar no viewport
// Importante: encontra o scroll parent mais próximo (o IPhone tem scroll interno)
const useReveal = () => {
  const ref = useRef(null);
  const [visible, setVisible] = useState(false);
  useEffect(() => {
    if (!ref.current) return;
    // Encontra ancestor scrollável
    let root = null;
    let p = ref.current.parentElement;
    while (p) {
      const cs = getComputedStyle(p);
      if ((cs.overflowY === "auto" || cs.overflowY === "scroll") && p.scrollHeight > p.clientHeight) {
        root = p;
        break;
      }
      p = p.parentElement;
    }
    const obs = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            setVisible(true);
            obs.disconnect();
          }
        });
      },
      { threshold: 0.05, root, rootMargin: "0px 0px -10% 0px" }
    );
    obs.observe(ref.current);
    // Fallback: se elemento já visível no viewport (acima do fold), revela imediatamente
    const rect = ref.current.getBoundingClientRect();
    const rootRect = root ? root.getBoundingClientRect() : { top: 0, bottom: window.innerHeight };
    if (rect.top < rootRect.bottom && rect.bottom > rootRect.top) {
      setVisible(true);
    }
    return () => obs.disconnect();
  }, []);
  return [ref, visible];
};

const Reveal = ({ children, delay = 0, as: Tag = "div", style = {}, ...rest }) => {
  const [ref, visible] = useReveal();
  return (
    <Tag
      ref={ref}
      style={{
        opacity: visible ? 1 : 0,
        transform: visible ? "translateY(0)" : "translateY(16px)",
        transition: `opacity 800ms cubic-bezier(.2,.7,.3,1) ${delay}ms, transform 800ms cubic-bezier(.2,.7,.3,1) ${delay}ms`,
        ...style,
      }}
      {...rest}
    >
      {children}
    </Tag>
  );
};

// Banner topo de progresso
const ProgressBanner = ({ tweaks }) => {
  return (
    <div
      style={{
        background: tweaks.dark ? "#2a1814" : "#fbf3ee",
        borderBottom: `1px solid ${tweaks.dark ? "#3d2620" : "#e8dcd0"}`,
        padding: "10px 16px",
        position: "sticky",
        top: 0,
        zIndex: 50,
        backdropFilter: "blur(8px)",
      }}
    >
      <div
        style={{
          display: "flex",
          alignItems: "center",
          gap: "10px",
          fontSize: "11px",
          letterSpacing: "0.1em",
          textTransform: "uppercase",
          color: tweaks.dark ? "#e8c8a8" : "#7a4a28",
          fontWeight: 600,
        }}
      >
        <span style={{ display: "flex", alignItems: "center", gap: "6px" }}>
          <span
            style={{
              width: "18px",
              height: "18px",
              borderRadius: "50%",
              background: tweaks.accent,
              color: "#fff",
              display: "inline-flex",
              alignItems: "center",
              justifyContent: "center",
              fontSize: "10px",
              fontWeight: 700,
            }}
          >
            ✓
          </span>
          Etapa 1 de 2
        </span>
        <div
          style={{
            flex: 1,
            height: "3px",
            background: tweaks.dark ? "#3d2620" : "#ead9c9",
            borderRadius: "2px",
            overflow: "hidden",
            position: "relative",
          }}
        >
          <div
            style={{
              position: "absolute",
              left: 0,
              top: 0,
              bottom: 0,
              width: "55%",
              background: `linear-gradient(90deg, ${tweaks.accent} 0%, ${tweaks.gold} 100%)`,
              boxShadow: `0 0 8px ${tweaks.gold}88`,
            }}
          />
        </div>
        <span style={{ color: tweaks.dark ? "#a89888" : "#a89888" }}>2/2</span>
      </div>
    </div>
  );
};

// Seção 1: Hero com retrato
const HeroSection = ({ tweaks, name }) => {
  return (
    <section
      style={{
        padding: "32px 22px 36px",
        textAlign: "center",
        position: "relative",
      }}
    >
      <Reveal>
        <div
          style={{
            display: "inline-block",
            fontSize: "11px",
            letterSpacing: "0.18em",
            textTransform: "uppercase",
            color: tweaks.gold,
            fontWeight: 600,
            marginBottom: "16px",
            padding: "5px 12px",
            border: `1px solid ${tweaks.gold}55`,
            borderRadius: "100px",
            background: tweaks.dark ? "rgba(184,137,61,0.1)" : "rgba(184,137,61,0.08)",
          }}
        >
          ✦ Mensagem da Mestre Maya
        </div>
      </Reveal>

      <Reveal delay={120} as="h1" style={{
        fontFamily: "'Cormorant Garamond', serif",
        fontSize: "32px",
        fontWeight: 500,
        lineHeight: 1.15,
        color: tweaks.dark ? "#f5ede0" : "#1a1410",
        margin: "0 0 8px",
        letterSpacing: "-0.01em",
      }}>
        Olá, <em style={{ fontStyle: "italic", color: tweaks.gold, fontWeight: 500 }}>{name || "querida"}</em>...
      </Reveal>

      <Reveal delay={200} as="h2" style={{
        fontFamily: "'Cormorant Garamond', serif",
        fontSize: "30px",
        fontWeight: 400,
        lineHeight: 1.18,
        color: tweaks.dark ? "#f5ede0" : "#1a1410",
        margin: "0 0 28px",
        letterSpacing: "-0.015em",
        textWrap: "pretty",
      }}>
        Seu desenho <em style={{ fontStyle: "italic" }}>já está pronto</em>...
        <br />
        mas existe algo que você ainda não viu.
      </Reveal>

      <Reveal delay={300}>
        <div style={{ position: "relative", maxWidth: "240px", margin: "0 auto 18px" }}>
          <PortraitFrame accentColor={tweaks.gold}>
            <Portrait colored={false} blur={2.5} />
          </PortraitFrame>

          {/* Selo "P&B" */}
          <div
            style={{
              position: "absolute",
              bottom: "8px",
              left: "50%",
              transform: "translateX(-50%)",
              background: tweaks.dark ? "#1a1410" : "#1a1410",
              color: tweaks.gold,
              fontSize: "10px",
              letterSpacing: "0.2em",
              padding: "5px 14px",
              borderRadius: "100px",
              fontWeight: 600,
              border: `1px solid ${tweaks.gold}66`,
              textTransform: "uppercase",
            }}
          >
            ✦ Versão Preto & Branco
          </div>
        </div>
      </Reveal>

      <Reveal delay={400}>
        <p style={{
          fontFamily: "'Inter Tight', sans-serif",
          fontSize: "16px",
          lineHeight: 1.55,
          color: tweaks.dark ? "#c8b8a8" : "#5a4a3e",
          margin: "0 auto",
          maxWidth: "320px",
          textWrap: "pretty",
        }}>
          O desenho em preto e branco mostra apenas o rosto da sua alma gêmea.
          {" "}
          <strong style={{ color: tweaks.dark ? "#f5ede0" : "#1a1410", fontWeight: 600 }}>
            Ele não revela quem essa pessoa realmente é.
          </strong>
        </p>
      </Reveal>

      <Reveal delay={600}>
        <div style={{ marginTop: "28px", display: "flex", flexDirection: "column", alignItems: "center", gap: "8px" }}>
          <div style={{
            fontSize: "11px",
            letterSpacing: "0.2em",
            textTransform: "uppercase",
            color: tweaks.dark ? "#a89888" : "#a89888",
            fontFamily: "'Inter Tight', sans-serif",
          }}>
            Continue lendo
          </div>
          <div style={{ animation: "bounce 2s infinite" }}>
            <svg width="20" height="20" viewBox="0 0 20 20" fill="none">
              <path d="M5 8L10 13L15 8" stroke={tweaks.gold} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
            </svg>
          </div>
        </div>
      </Reveal>
    </section>
  );
};

// Seção 2: Agitação da Dor
const PainSection = ({ tweaks }) => {
  const questions = [
    "Qual é o nome dele?",
    "Onde ele mora?",
    "Quando ele vai aparecer?",
    "Por que essa conexão parece tão forte?",
  ];

  return (
    <section
      style={{
        padding: "48px 24px 56px",
        background: tweaks.dark ? "#15100c" : "#f3ebe0",
        borderTop: `1px solid ${tweaks.dark ? "#2a1f18" : "#e6d8c8"}`,
        borderBottom: `1px solid ${tweaks.dark ? "#2a1f18" : "#e6d8c8"}`,
        position: "relative",
      }}
    >
      {/* ornamento */}
      <Reveal>
        <div style={{ textAlign: "center", marginBottom: "28px" }}>
          <svg width="40" height="12" viewBox="0 0 40 12" fill="none">
            <path d="M0 6 L14 6" stroke={tweaks.gold} strokeWidth="0.8" />
            <circle cx="20" cy="6" r="2.5" fill={tweaks.gold} />
            <path d="M26 6 L40 6" stroke={tweaks.gold} strokeWidth="0.8" />
          </svg>
        </div>
      </Reveal>

      <Reveal delay={100}>
        <p style={{
          fontFamily: "'Cormorant Garamond', serif",
          fontStyle: "italic",
          fontSize: "22px",
          lineHeight: 1.4,
          color: tweaks.dark ? "#f5ede0" : "#1a1410",
          textAlign: "center",
          margin: "0 0 24px",
          textWrap: "pretty",
        }}>
          E é exatamente por isso que muitas mulheres recebem apenas o desenho simples...
        </p>
      </Reveal>

      <Reveal delay={200}>
        <p style={{
          fontFamily: "'Inter Tight', sans-serif",
          fontSize: "16px",
          lineHeight: 1.6,
          color: tweaks.dark ? "#c8b8a8" : "#5a4a3e",
          textAlign: "center",
          margin: "0 0 24px",
        }}>
          E depois ficam obcecadas tentando descobrir:
        </p>
      </Reveal>

      <div style={{ maxWidth: "320px", margin: "0 auto 28px", display: "flex", flexDirection: "column", gap: "10px" }}>
        {questions.map((q, i) => (
          <Reveal key={i} delay={300 + i * 100}>
            <div
              style={{
                background: tweaks.dark ? "rgba(245,237,224,0.04)" : "#fbf6ee",
                border: `1px solid ${tweaks.dark ? "rgba(184,137,61,0.2)" : "#e6d8c8"}`,
                borderLeft: `3px solid ${tweaks.gold}`,
                padding: "14px 16px",
                borderRadius: "4px",
                display: "flex",
                alignItems: "center",
                gap: "12px",
              }}
            >
              <span style={{
                fontFamily: "'Cormorant Garamond', serif",
                fontStyle: "italic",
                fontSize: "20px",
                color: tweaks.gold,
                lineHeight: 1,
              }}>?</span>
              <span style={{
                fontFamily: "'Cormorant Garamond', serif",
                fontStyle: "italic",
                fontSize: "18px",
                color: tweaks.dark ? "#f5ede0" : "#2a1f18",
                lineHeight: 1.3,
              }}>{q}</span>
            </div>
          </Reveal>
        ))}
      </div>

      <Reveal delay={750}>
        <p style={{
          fontFamily: "'Inter Tight', sans-serif",
          fontSize: "16px",
          lineHeight: 1.6,
          color: tweaks.dark ? "#c8b8a8" : "#5a4a3e",
          textAlign: "center",
          margin: "0 0 16px",
          textWrap: "pretty",
        }}>
          E muitas voltam <em style={{ fontStyle: "italic", fontWeight: 500 }}>desesperadas</em> depois,
          querendo essas respostas...
        </p>
      </Reveal>

      <Reveal delay={850}>
        <p style={{
          fontFamily: "'Cormorant Garamond', serif",
          fontStyle: "italic",
          fontSize: "20px",
          lineHeight: 1.4,
          color: tweaks.dark ? "#e8c8a8" : "#7a4a28",
          textAlign: "center",
          margin: "0",
          textWrap: "pretty",
        }}>
          Mas quando o desenho é enviado,<br />
          essa oportunidade <strong style={{ color: tweaks.gold, fontWeight: 600 }}>desaparece</strong>.
        </p>
      </Reveal>
    </section>
  );
};

// Seção 3: Apresentação do Combo
const ComboHeroSection = ({ tweaks }) => {
  return (
    <section style={{ padding: "56px 24px 48px", textAlign: "center" }}>
      <Reveal>
        <p style={{
          fontFamily: "'Inter Tight', sans-serif",
          fontSize: "13px",
          letterSpacing: "0.18em",
          textTransform: "uppercase",
          color: tweaks.dark ? "#a89888" : "#8a7060",
          margin: "0 0 12px",
          fontWeight: 500,
        }}>
          Por isso, a Mestre Maya preparou
        </p>
      </Reveal>

      <Reveal delay={120} as="h2" style={{
        fontFamily: "'Cormorant Garamond', serif",
        fontSize: "38px",
        fontWeight: 400,
        lineHeight: 1.05,
        margin: "0 0 6px",
        background: `linear-gradient(180deg, ${tweaks.gold} 0%, #8a6628 100%)`,
        WebkitBackgroundClip: "text",
        WebkitTextFillColor: "transparent",
        backgroundClip: "text",
        letterSpacing: "-0.02em",
      }}>
        Combo Completo
      </Reveal>

      <Reveal delay={180} as="h3" style={{
        fontFamily: "'Cormorant Garamond', serif",
        fontStyle: "italic",
        fontSize: "26px",
        fontWeight: 400,
        color: tweaks.dark ? "#f5ede0" : "#1a1410",
        margin: "0 0 32px",
      }}>
        da Alma Gêmea
      </Reveal>

      <Reveal delay={250}>
        <ComboMockup tweaks={tweaks} />
      </Reveal>

      <Reveal delay={400}>
        <p style={{
          fontFamily: "'Inter Tight', sans-serif",
          fontSize: "16px",
          lineHeight: 1.55,
          color: tweaks.dark ? "#c8b8a8" : "#5a4a3e",
          margin: "32px auto 0",
          maxWidth: "320px",
          textWrap: "pretty",
        }}>
          Para quem realmente quer <strong style={{ color: tweaks.dark ? "#f5ede0" : "#1a1410", fontWeight: 600 }}>viver essa conexão</strong> ainda nessa vida.
        </p>
      </Reveal>
    </section>
  );
};

// Mockup visual do combo (cards empilhados representando os entregáveis)
const ComboMockup = ({ tweaks }) => {
  const items = [
    { icon: "🔮", label: "Carta Psíquica", color: "#9d6cb8" },
    { icon: "📍", label: "Localização", color: "#6c8eb8" },
    { icon: "🎨", label: "Retrato Colorido", color: "#b88c6c" },
    { icon: "✦", label: "Preságio", color: "#b86c8c" },
    { icon: "⏳", label: "Vidas Passadas", color: "#8cb86c" },
  ];

  return (
    <div style={{ position: "relative", maxWidth: "300px", margin: "0 auto", padding: "20px 0" }}>
      {/* glow de fundo */}
      <div style={{
        position: "absolute",
        inset: "-30px",
        background: `radial-gradient(circle at center, ${tweaks.gold}33 0%, transparent 60%)`,
        filter: "blur(20px)",
        zIndex: 0,
      }} />

      {/* Card central — retrato colorido */}
      <div style={{
        position: "relative",
        zIndex: 2,
        margin: "0 auto",
        width: "150px",
      }}>
        <PortraitFrame accentColor={tweaks.gold}>
          <Portrait colored={true} blur={1.5} />
        </PortraitFrame>
      </div>

      {/* Cards de itens em volta */}
      <div style={{
        marginTop: "20px",
        display: "grid",
        gridTemplateColumns: "1fr 1fr",
        gap: "10px",
        position: "relative",
        zIndex: 1,
      }}>
        {items.map((item, i) => (
          <div
            key={i}
            style={{
              background: tweaks.dark ? "rgba(245,237,224,0.05)" : "#fff",
              border: `1px solid ${tweaks.dark ? "rgba(184,137,61,0.25)" : "#ead9c9"}`,
              borderRadius: "8px",
              padding: "12px 10px",
              display: "flex",
              alignItems: "center",
              gap: "8px",
              boxShadow: tweaks.dark ? "none" : "0 2px 6px rgba(60,40,20,0.04)",
              gridColumn: i === 4 ? "1 / -1" : "auto",
            }}
          >
            <div style={{
              fontSize: "20px",
              width: "32px",
              height: "32px",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              borderRadius: "6px",
              background: `${item.color}22`,
              flexShrink: 0,
            }}>{item.icon}</div>
            <div style={{
              fontFamily: "'Inter Tight', sans-serif",
              fontSize: "12px",
              fontWeight: 500,
              color: tweaks.dark ? "#f5ede0" : "#1a1410",
              lineHeight: 1.2,
            }}>{item.label}</div>
          </div>
        ))}
      </div>
    </div>
  );
};

// Seção 4 e 5: Benefícios narrativos
const BenefitSection = ({ tweaks, kicker, title, body, highlight, footer, ornament }) => {
  return (
    <section
      style={{
        padding: "56px 24px",
        textAlign: "center",
        background: tweaks.dark ? "#15100c" : "#fbf6ee",
        borderTop: `1px solid ${tweaks.dark ? "#2a1f18" : "#ead9c9"}`,
      }}
    >
      <Reveal>
        <div style={{
          fontFamily: "'Inter Tight', sans-serif",
          fontSize: "11px",
          letterSpacing: "0.22em",
          textTransform: "uppercase",
          color: tweaks.gold,
          marginBottom: "14px",
          fontWeight: 600,
        }}>
          {kicker}
        </div>
      </Reveal>

      <Reveal delay={100} as="h2" style={{
        fontFamily: "'Cormorant Garamond', serif",
        fontSize: "30px",
        fontWeight: 400,
        lineHeight: 1.15,
        color: tweaks.dark ? "#f5ede0" : "#1a1410",
        margin: "0 0 24px",
        letterSpacing: "-0.015em",
        textWrap: "pretty",
      }}>
        {title}
      </Reveal>

      <Reveal delay={200}>
        <p style={{
          fontFamily: "'Inter Tight', sans-serif",
          fontSize: "16px",
          lineHeight: 1.6,
          color: tweaks.dark ? "#c8b8a8" : "#5a4a3e",
          margin: "0 auto 20px",
          maxWidth: "320px",
          textWrap: "pretty",
        }}>{body}</p>
      </Reveal>

      {highlight && (
        <Reveal delay={300}>
          <div style={{
            background: tweaks.dark ? "rgba(184,137,61,0.08)" : "#fdf8ef",
            border: `1px solid ${tweaks.gold}55`,
            borderRadius: "6px",
            padding: "18px 18px",
            margin: "0 auto 20px",
            maxWidth: "320px",
            position: "relative",
          }}>
            <div style={{
              position: "absolute",
              top: "-9px",
              left: "50%",
              transform: "translateX(-50%)",
              background: tweaks.dark ? "#15100c" : "#fbf6ee",
              padding: "0 10px",
            }}>
              <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
                <path d="M8 1 L9.5 6 L14.5 6.5 L10.5 9.5 L12 14.5 L8 11.5 L4 14.5 L5.5 9.5 L1.5 6.5 L6.5 6 Z" fill={tweaks.gold} />
              </svg>
            </div>
            <p style={{
              fontFamily: "'Cormorant Garamond', serif",
              fontStyle: "italic",
              fontSize: "18px",
              lineHeight: 1.4,
              color: tweaks.dark ? "#f5ede0" : "#2a1f18",
              margin: 0,
              fontWeight: 500,
              textWrap: "pretty",
            }}>{highlight}</p>
          </div>
        </Reveal>
      )}

      {footer && (
        <Reveal delay={400}>
          <p style={{
            fontFamily: "'Cormorant Garamond', serif",
            fontStyle: "italic",
            fontSize: "18px",
            lineHeight: 1.4,
            color: tweaks.dark ? "#e8c8a8" : "#7a4a28",
            margin: "8px auto 0",
            maxWidth: "320px",
            textWrap: "pretty",
          }}>{footer}</p>
        </Reveal>
      )}

      {ornament}
    </section>
  );
};

window.ProgressBanner = ProgressBanner;
window.HeroSection = HeroSection;
window.PainSection = PainSection;
window.ComboHeroSection = ComboHeroSection;
window.BenefitSection = BenefitSection;
window.Reveal = Reveal;
window.useReveal = useReveal;
