/* global React, Icon, Reveal, IMG, LAUNCHES, WA_LINK */

// ============================================================
// LAUNCHES OVERVIEW PAGE
// ============================================================
const Launches = ({ setPage, setLaunchId }) => {
  const [slide, setSlide] = React.useState(0);
  React.useEffect(() => {
    const id = setInterval(() => setSlide(s => (s + 1) % LAUNCHES.length), 6500);
    return () => clearInterval(id);
  }, []);

  const open = (id) => () => {
    setLaunchId(id);
    setPage("launch-detail");
    window.scrollTo({ top: 0, behavior: "smooth" });
  };

  const current = LAUNCHES[slide];

  return (
    <div className="bn-page launches-page">
      {/* Cover with rotating videos */}
      <section className="launches-hero">
        <div className="bg">
          {LAUNCHES.map((l, i) => (
            <div key={l.id} className={`slide ${i === slide ? "active" : ""}`}>
              <img src={l.cover} alt={l.name} />
            </div>
          ))}
        </div>
        <div className="content">
          <div className="meta-top">
            <span className="eyebrow">Lançamentos · Empreendimentos · Loteamentos</span>
            <span className="live-indicator">
              <span className="dot"></span> Em destaque · {String(slide + 1).padStart(2, "0")} / {String(LAUNCHES.length).padStart(2, "0")}
            </span>
          </div>

          <h1>O futuro<br/>de morar em<br/><em>Ijuí</em>.</h1>

          <div className="bottom-row">
            <p className="tagline">
              Cinco empreendimentos em fase de lançamento e obras — residenciais, comerciais e loteamentos selecionados com a mesma curadoria que aplicamos ao portfólio Bene. Aqui você encontra plantas, vídeos institucionais e tabela exclusiva antes de qualquer outro canal.
            </p>
            <div className="now-playing" onClick={open(current.id)} style={{ cursor: "pointer" }}>
              <div style={{ width: 60, height: 60, position: "relative", flexShrink: 0, overflow: "hidden" }}>
                <img src={current.cover} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} />
                <div style={{ position: "absolute", inset: 0, display: "grid", placeItems: "center", background: "rgba(0,0,0,0.3)" }}>
                  <span style={{ color: "var(--bg)", fontSize: 16 }}>▶</span>
                </div>
              </div>
              <div style={{ flex: 1 }}>
                <div className="label">Tocando agora · vídeo institucional</div>
                <div className="name">{current.name}</div>
                <div className="loc">{current.loc}</div>
              </div>
              <div style={{ color: "var(--gold)", fontSize: 18 }}>→</div>
            </div>
          </div>
        </div>

        {/* Slide indicators */}
        <div className="hero-indicators" style={{ bottom: 24 }}>
          {LAUNCHES.map((_, i) => (
            <span key={i} className={`ind ${i === slide ? "active" : ""}`} onClick={() => setSlide(i)}></span>
          ))}
        </div>
      </section>

      {/* Filter / Intro strip */}
      <section className="section" style={{ paddingBottom: 0 }}>
        <div className="section-head wide-title">
          <Reveal>
            <span className="eyebrow" style={{ marginBottom: 16, display: "inline-block" }}>Portfólio em lançamento</span>
            <h2 className="section-title">
              Empreendimentos<br/>com história <em><i style={{ fontStyle: "italic" }}>antes</i></em><br/>do tijolo.
            </h2>
          </Reveal>
          <Reveal delay={0.1}>
            <p className="section-lead">
              Para cada lançamento, fazemos uma curadoria das informações que importam: arquiteto, construtora, materiais, estudo de insolação, projeção de valorização. Você decide com dados — não com folder.
            </p>
            <div style={{ display: "flex", gap: 8, marginTop: 24, flexWrap: "wrap" }}>
              {["Todos", "Residencial", "Comercial", "Loteamento"].map((c, i) => (
                <button key={c} className={`filter-chip ${i === 0 ? "active" : ""}`}>{c}</button>
              ))}
            </div>
          </Reveal>
        </div>
      </section>

      {/* Launch cards */}
      <div className="launches-grid">
        {LAUNCHES.map((l, i) => (
          <Reveal key={l.id} delay={i * 0.08} as="article" className="launch-card">
            <div onClick={open(l.id)}>
              <div className="img-wrap">
                <img src={l.cover} alt={l.name} />
                <div className="video-pip"><span className="dot"></span> VÍDEO INSTITUCIONAL</div>
                <div className="stage">{l.stage}</div>
              </div>
              <div className="info">
                <div className="typology">{l.typology}</div>
                <h3>{l.name}</h3>
                <div className="loc">{l.loc}</div>
                <div className="specs">
                  <div>
                    <div className="lbl">Unidades</div>
                    <div className="val">{l.units}</div>
                  </div>
                  <div>
                    <div className="lbl">Configuração</div>
                    <div className="val" style={{ fontSize: 15 }}>{l.floors}</div>
                  </div>
                  <div>
                    <div className="lbl">Entrega</div>
                    <div className="val">{l.delivery}</div>
                  </div>
                </div>
                <div className="cta">
                  <div className="price">
                    <small>A partir de</small>
                    {l.price.replace("A partir de ", "")}
                  </div>
                  <button className="btn-arrow">Ver empreendimento <span className="arr">→</span></button>
                </div>
              </div>
            </div>
          </Reveal>
        ))}
      </div>

      {/* WhatsApp reserve CTA */}
      <section className="cta-block" style={{ background: "var(--ink)" }}>
        <Reveal>
          <h2>Reserve sua<br/>unidade antes<br/>do <em><i style={{ fontStyle: "italic" }}>público</i></em>.</h2>
        </Reveal>
        <Reveal delay={0.15} className="cta-side">
          <p>
            Clientes Bene têm acesso antecipado a unidades, tabelas exclusivas e condições especiais de lançamento. Cadastre seu interesse — escolhemos juntos a unidade certa.
          </p>
          <div style={{ display: "flex", gap: 12, flexWrap: "wrap" }}>
            <a className="btn btn-gold" href={WA_LINK} target="_blank" rel="noopener">
              <Icon name="wa" size={14} /> Reservar pelo WhatsApp
            </a>
            <button className="btn btn-ghost" onClick={() => { setPage("contact"); window.scrollTo(0, 0); }}>
              Falar por formulário <Icon name="arrow" />
            </button>
          </div>
        </Reveal>
      </section>
    </div>
  );
};

// ============================================================
// LAUNCH DETAIL PAGE
// ============================================================
const LaunchDetail = ({ setPage, launchId, setLaunchId }) => {
  const l = LAUNCHES.find(x => x.id === launchId) || LAUNCHES[0];
  const isLot = /loteamento/i.test(l.typology);
  const [tab, setTab] = React.useState(0);
  const [galSlide, setGalSlide] = React.useState(0);
  const [videoAr, setVideoAr] = React.useState("16-9");

  React.useEffect(() => {
    const id = setInterval(() => setGalSlide(s => (s + 1) % l.gallery.length), 5000);
    return () => clearInterval(id);
  }, [l.gallery.length]);

  const open = (id) => () => {
    setLaunchId(id);
    setTab(0);
    window.scrollTo({ top: 0, behavior: "smooth" });
  };

  return (
    <div className="bn-page launch-detail">
      {/* Breadcrumb */}
      <div style={{ position: "absolute", top: 140, left: "clamp(20px, 5vw, 80px)", zIndex: 3, fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase", color: "rgba(255,255,255,0.7)" }}>
        <span style={{ cursor: "pointer" }} onClick={() => { setPage("home"); window.scrollTo(0,0); }}>Início</span>
        <span style={{ margin: "0 12px" }}>/</span>
        <span style={{ cursor: "pointer" }} onClick={() => { setPage("launches"); window.scrollTo(0,0); }}>Lançamentos</span>
        <span style={{ margin: "0 12px" }}>/</span>
        <span style={{ color: "var(--gold)" }}>{l.name}</span>
      </div>

      {/* Cover */}
      <section className="launch-cover">
        <div className="bg"><img src={l.cover} alt={l.name} /></div>
        <div className="content">
          <div className="top-tags">
            <span className="tag">{l.stage}</span>
            <span>·</span>
            <span>{l.typology}</span>
          </div>

          <h1>
            {l.name.split(" ").map((w, i, arr) => (
              <span key={i}>
                {i === arr.length - 1 ? <em>{w}</em> : w}
                {i < arr.length - 1 && " "}
              </span>
            ))}
          </h1>

          <div className="sub-info">
            <div><div className="lbl">Localização</div><div className="val">{l.loc.split("·")[0].trim()}</div></div>
            <div><div className="lbl">Unidades</div><div className="val"><em>{l.units}</em></div></div>
            <div><div className="lbl">Configuração</div><div className="val" style={{ fontSize: 20 }}>{l.floors}</div></div>
            <div><div className="lbl">Entrega prevista</div><div className="val"><em>{l.delivery}</em></div></div>
          </div>
        </div>
      </section>

      {/* Pitch + Video */}
      <section className="section">
        <div className="editorial">
          <Reveal>
            <span className="eyebrow" style={{ marginBottom: 16, display: "inline-block" }}>Conceito</span>
            <h2 style={{ fontFamily: "var(--f-display)", fontSize: "clamp(36px, 4.5vw, 60px)", lineHeight: 1, marginBottom: 28 }}>
              {l.pitch.split(".")[0]}.
            </h2>
            <p style={{ fontSize: 17, lineHeight: 1.7, color: "var(--ink-soft)" }}>
              {l.pitch.split(".").slice(1).join(".").trim()}
            </p>
            <ul className="editorial-list">
              <li><span>Arquitetura</span><span>{l.architect.split("·")[0].trim()}</span></li>
              <li><span>Construção</span><span>{l.construction.split("·")[0].trim()}</span></li>
              <li><span>Status</span><span>{l.stage}</span></li>
              <li><span>Investimento mínimo</span><span>{l.price.replace("A partir de ", "")}</span></li>
            </ul>
          </Reveal>

          <Reveal className="">
            <div className="video-toggle">
              <button className={videoAr === "16-9" ? "active" : ""} onClick={() => setVideoAr("16-9")}>▭ 16:9</button>
              <button className={videoAr === "9-16" ? "active" : ""} onClick={() => setVideoAr("9-16")}>▯ 9:16</button>
            </div>
            <div className={`video-player ar-${videoAr}`}>
              <img src={videoAr === "9-16" ? l.accent : l.cover} alt="" />
              <div className="video-play">
                <div className="circle">▶</div>
              </div>
              <div className="pip-label"><span className="ind"></span> {videoAr === "9-16" ? "Reels institucional" : "Vídeo institucional · 4K"}</div>
              <div className="pip-duration">{videoAr === "9-16" ? "00:48" : "02:24"}</div>
            </div>
            <p style={{ marginTop: 14, fontSize: 12, opacity: 0.65 }}>Vídeo institucional do empreendimento. Aceitamos formatos 16:9 e 9:16.</p>
          </Reveal>
        </div>
      </section>

      {/* Story */}
      <section className="launch-story" style={{ background: "var(--bg-soft)" }}>
        <div className="columns">
          <Reveal>
            <span className="eyebrow" style={{ marginBottom: 16, display: "inline-block" }}>História do projeto</span>
            <h2>
              O conceito<br/>por <em><i style={{ fontStyle: "italic" }}>trás</i></em><br/>do projeto.
            </h2>
          </Reveal>
          <Reveal delay={0.15} className="body">
            <p>{l.story}</p>
          </Reveal>
        </div>
      </section>

      {/* Gallery carousel */}
      <section className="section">
        <div className="section-head">
          <Reveal>
            <span className="eyebrow" style={{ marginBottom: 16, display: "inline-block" }}>Galeria do projeto</span>
            <h2 className="section-title">Imagens<br/>do <em><i style={{ fontStyle: "italic" }}>projeto</i></em></h2>
          </Reveal>
          <Reveal delay={0.1}>
            <p className="section-lead">
              Imagens conceituais e fotografias da obra em andamento. Atualizamos mensalmente.
            </p>
          </Reveal>
        </div>

        <div className="carousel" style={{ aspectRatio: "16/9" }}>
          <div className="carousel-dots">
            {l.gallery.map((_, i) => (
              <span key={i} className={`d ${i === galSlide ? "active" : ""}`} onClick={() => setGalSlide(i)}></span>
            ))}
          </div>
          <div className="carousel-track" style={{ transform: `translateX(-${galSlide * 100}%)` }}>
            {l.gallery.map((img, i) => (
              <div className="carousel-slide" key={i}>
                <img src={img} alt="" style={{ aspectRatio: "16/9" }} />
                <div className="caption">
                  <small>{String(i + 1).padStart(2, "0")} / {String(l.gallery.length).padStart(2, "0")}</small>
                  {i === 0 ? "Fachada principal" : i === 1 ? "Sala social — sugestão de decoração" : i === 2 ? "Área externa" : "Vista do andar tipo"}
                </div>
              </div>
            ))}
          </div>
          <div className="carousel-nav">
            <button onClick={() => setGalSlide(s => (s - 1 + l.gallery.length) % l.gallery.length)}>‹</button>
            <button onClick={() => setGalSlide(s => (s + 1) % l.gallery.length)}>›</button>
          </div>
        </div>
      </section>

      {/* Plant viewer / typologies */}
      <section className="plant-section">
        <div className="section-head">
          <Reveal>
            <span className="eyebrow" style={{ marginBottom: 16, display: "inline-block" }}>{isLot ? "Tipos de lote" : "Plantas e tipologias"}</span>
            <h2 className="section-title">{isLot ? "Escolha seu" : "Escolha sua"}<br/><em><i style={{ fontStyle: "italic" }}>{isLot ? "lote" : "configuração"}</i></em></h2>
          </Reveal>
          <Reveal delay={0.1}>
            <p className="section-lead">
              {l.typologies.length} {isLot ? "tipos de lote" : "tipologias"} disponíveis. Selecione abaixo para ver {isLot ? "o diagrama e dimensões do lote" : "a planta e tabela"}.
            </p>
          </Reveal>
        </div>

        <div className="plant-grid">
          <div className="plant-tabs">
            {l.typologies.map((t, i) => (
              <button key={i} className={`plant-tab ${tab === i ? "active" : ""}`} onClick={() => setTab(i)}>
                {t.label}
                <div className="sub">{t.sub} · {t.value}</div>
              </button>
            ))}
          </div>
          <div className="plant-canvas">
            {isLot ? <LotPlan idx={tab} typology={l.typologies[tab]} /> : <FloorPlan idx={tab} />}
            <div style={{ position: "absolute", bottom: 24, right: 24, fontFamily: "var(--f-mono)", fontSize: 11, letterSpacing: "0.1em", opacity: 0.55 }}>
              {l.typologies[tab].label} · esc 1:{isLot ? "500" : "100"}
            </div>
            <div style={{ position: "absolute", top: 24, left: 24, fontSize: 11, letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--gold-deep)", fontWeight: 500 }}>
              {isLot ? "Lote" : "Tipologia"} {String(tab + 1).padStart(2, "0")}
            </div>
          </div>
        </div>
      </section>

      {/* Differentials */}
      <section className="section">
        <div className="section-head">
          <Reveal>
            <span className="eyebrow" style={{ marginBottom: 16, display: "inline-block" }}>Diferenciais</span>
            <h2 className="section-title">Por que<br/>este <em><i style={{ fontStyle: "italic" }}>empreendimento</i></em>?</h2>
          </Reveal>
          <Reveal delay={0.1}>
            <p className="section-lead">
              Cada decisão de projeto foi pensada para entregar mais qualidade de vida — não mais metros quadrados.
            </p>
          </Reveal>
        </div>

        <div className="diff-list" style={{ borderTop: "1px solid var(--line)" }}>
          {l.differentials.map((d, i) => (
            <Reveal key={d.t} delay={i * 0.05} className="diff-item">
              <h4>{d.t}</h4>
              <p>{d.d}</p>
            </Reveal>
          ))}
        </div>
      </section>

      {/* Reserve CTA */}
      <section className="reserve-cta">
        <Reveal>
          <span className="eyebrow" style={{ color: "var(--gold)", marginBottom: 16, display: "inline-block" }}>Reserva antecipada</span>
          <h2>Garanta a melhor<br/>unidade <em><i style={{ fontStyle: "italic" }}>antes</i></em><br/>do público.</h2>
        </Reveal>
        <Reveal delay={0.15}>
          <p style={{ fontSize: 16, lineHeight: 1.6, opacity: 0.85 }}>
            Clientes Bene têm preferência nas primeiras unidades e condições especiais de pagamento. Reserva sem custo — vinculada apenas à intenção de compra.
          </p>
          <div className="meta-grid">
            <div>
              <div className="lbl">Sinal de reserva</div>
              <div className="val">R$ 0</div>
            </div>
            <div>
              <div className="lbl">Validade</div>
              <div className="val">48 horas</div>
            </div>
          </div>
          <div style={{ display: "flex", gap: 12, flexWrap: "wrap" }}>
            <a className="btn btn-gold" href={WA_LINK} target="_blank" rel="noopener">
              <Icon name="wa" size={14} /> Reservar pelo WhatsApp
            </a>
            <button className="btn btn-ghost" onClick={() => { setPage("contact"); window.scrollTo(0, 0); }}>
              Falar por formulário <Icon name="arrow" />
            </button>
          </div>
        </Reveal>
      </section>

      {/* Other launches */}
      <section className="section" style={{ borderTop: "1px solid var(--line)" }}>
        <div className="section-head">
          <Reveal>
            <span className="eyebrow" style={{ marginBottom: 16, display: "inline-block" }}>Outros empreendimentos</span>
            <h2 className="section-title">Continue<br/><em><i style={{ fontStyle: "italic" }}>explorando</i></em></h2>
          </Reveal>
        </div>
        <div className="launches-grid" style={{ padding: 0 }}>
          {LAUNCHES.filter(x => x.id !== l.id).slice(0, 2).map((other, i) => (
            <Reveal key={other.id} delay={i * 0.1} as="article" className="launch-card">
              <div onClick={open(other.id)}>
                <div className="img-wrap">
                  <img src={other.cover} alt={other.name} />
                  <div className="stage">{other.stage}</div>
                </div>
                <div className="info">
                  <div className="typology">{other.typology}</div>
                  <h3>{other.name}</h3>
                  <div className="loc">{other.loc}</div>
                  <div className="cta">
                    <div className="price"><small>A partir de</small>{other.price.replace("A partir de ", "")}</div>
                    <button className="btn-arrow">Ver <span className="arr">→</span></button>
                  </div>
                </div>
              </div>
            </Reveal>
          ))}
        </div>
      </section>
    </div>
  );
};

// ===== Simple SVG floor plan placeholder
const FloorPlan = ({ idx = 0 }) => {
  const plans = [
    // 145 m²
    <svg viewBox="0 0 400 250" key="a">
      <g stroke="#14181D" strokeWidth="1.5" fill="none">
        <rect x="20" y="20" width="360" height="210"/>
        <line x1="180" y1="20" x2="180" y2="230"/>
        <line x1="20" y1="130" x2="180" y2="130"/>
        <line x1="180" y1="100" x2="280" y2="100"/>
        <line x1="280" y1="20" x2="280" y2="230"/>
        <line x1="280" y1="125" x2="380" y2="125"/>
      </g>
      <g fontFamily="var(--f-mono)" fontSize="9" fill="#14181D" opacity="0.75" letterSpacing="0.1em">
        <text x="60" y="70">SALA</text>
        <text x="60" y="180">COZINHA</text>
        <text x="200" y="55">SUÍTE 01</text>
        <text x="200" y="155">SUÍTE 02</text>
        <text x="290" y="70">SUÍTE</text>
        <text x="290" y="85">MASTER</text>
        <text x="290" y="170">CLOSET</text>
        <text x="290" y="200">BANHO</text>
      </g>
      <g fontFamily="var(--f-display)" fontSize="14" fill="#A6864F">
        <text x="20" y="245">145 m² · 3 suítes</text>
      </g>
    </svg>,
    // 188 m²
    <svg viewBox="0 0 400 250" key="b">
      <g stroke="#14181D" strokeWidth="1.5" fill="none">
        <rect x="20" y="20" width="360" height="210"/>
        <line x1="200" y1="20" x2="200" y2="230"/>
        <line x1="20" y1="140" x2="200" y2="140"/>
        <line x1="200" y1="90" x2="290" y2="90"/>
        <line x1="290" y1="20" x2="290" y2="230"/>
        <line x1="290" y1="125" x2="380" y2="125"/>
        <line x1="200" y1="170" x2="380" y2="170"/>
      </g>
      <g fontFamily="var(--f-mono)" fontSize="9" fill="#14181D" opacity="0.75" letterSpacing="0.1em">
        <text x="60" y="75">SALA + ESTAR</text>
        <text x="60" y="190">COZINHA GOURMET</text>
        <text x="220" y="55">SUÍTE 01</text>
        <text x="220" y="135">SUÍTE 02</text>
        <text x="220" y="210">SUÍTE 03</text>
        <text x="300" y="70">SUÍTE MASTER</text>
        <text x="300" y="155">CLOSET</text>
        <text x="300" y="210">SERVIÇO</text>
      </g>
      <g fontFamily="var(--f-display)" fontSize="14" fill="#A6864F">
        <text x="20" y="245">188 m² · 4 suítes</text>
      </g>
    </svg>,
    // 245 m²
    <svg viewBox="0 0 400 250" key="c">
      <g stroke="#14181D" strokeWidth="1.5" fill="none">
        <rect x="20" y="20" width="360" height="210"/>
        <line x1="180" y1="20" x2="180" y2="160"/>
        <line x1="20" y1="160" x2="380" y2="160"/>
        <line x1="180" y1="80" x2="380" y2="80"/>
        <line x1="280" y1="80" x2="280" y2="160"/>
        <line x1="100" y1="160" x2="100" y2="230"/>
        <line x1="220" y1="160" x2="220" y2="230"/>
        <line x1="300" y1="160" x2="300" y2="230"/>
      </g>
      <g fontFamily="var(--f-mono)" fontSize="9" fill="#14181D" opacity="0.75" letterSpacing="0.1em">
        <text x="60" y="100">SALA + JANTAR</text>
        <text x="200" y="55">VARANDA GOURMET</text>
        <text x="200" y="120">SUÍTE 01</text>
        <text x="290" y="120">SUÍTE 02</text>
        <text x="40" y="200">COZINHA</text>
        <text x="130" y="200">SUÍTE 03</text>
        <text x="240" y="200">SUÍTE MASTER</text>
        <text x="310" y="200">ESCRITÓRIO</text>
      </g>
      <g fontFamily="var(--f-display)" fontSize="14" fill="#A6864F">
        <text x="20" y="245">245 m² · 4 suítes + escritório</text>
      </g>
    </svg>,
    // 320 m² cobertura
    <svg viewBox="0 0 400 250" key="d">
      <g stroke="#14181D" strokeWidth="1.5" fill="none">
        <rect x="20" y="20" width="360" height="210"/>
        <line x1="20" y1="140" x2="380" y2="140"/>
        <line x1="200" y1="20" x2="200" y2="140"/>
        <line x1="120" y1="20" x2="120" y2="140"/>
        <line x1="290" y1="20" x2="290" y2="140"/>
        <line x1="200" y1="140" x2="200" y2="230"/>
        <line x1="20" y1="190" x2="200" y2="190"/>
      </g>
      <circle cx="290" cy="195" r="40" stroke="#A6864F" strokeWidth="1" fill="rgba(196,165,123,0.1)"/>
      <g fontFamily="var(--f-mono)" fontSize="9" fill="#14181D" opacity="0.75" letterSpacing="0.1em">
        <text x="40" y="80">ENTRADA</text>
        <text x="140" y="80">LIVING</text>
        <text x="215" y="80">SUÍTE MASTER</text>
        <text x="300" y="80">CLOSET</text>
        <text x="50" y="170">COZINHA</text>
        <text x="50" y="220">SERVIÇO</text>
        <text x="220" y="220">TERRAÇO</text>
        <text x="265" y="200">PISCINA</text>
      </g>
      <g fontFamily="var(--f-display)" fontSize="14" fill="#A6864F">
        <text x="20" y="245">320 m² · Cobertura duplex</text>
      </g>
    </svg>,
  ];
  return plans[idx % plans.length];
};

Object.assign(window, { Launches, LaunchDetail });
