/* global React, TAND, A_Icons */
const { useState, useRef, useEffect } = React;
const { IconArrow, IconCheck, IconStar, IconWhatsApp, IconPlus, IconGoogle } = A_Icons;

// ————— Differentiators —————

// Video tall bento — purple cover + white logo; reveals when card is
// roughly centered in the viewport, then starts playing.
const VideoBentoCard = () => {
  const cardRef = useRef(null);
  const videoRef = useRef(null);
  const [revealed, setRevealed] = useState(false);

  useEffect(() => {
    const card = cardRef.current;
    if (!card) return;

    const triggerReveal = () => {
      if (revealed) return;
      setRevealed(true);
      const v = videoRef.current;
      if (v) {
        const p = v.play();
        if (p && typeof p.catch === "function") p.catch(() => {});
      }
    };

    if (typeof window.IntersectionObserver !== "function") {
      triggerReveal();
      return;
    }

    const obs = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            triggerReveal();
            obs.unobserve(entry.target);
          }
        });
      },
      { threshold: 0.01, rootMargin: "-35% 0px -35% 0px" }
    );
    obs.observe(card);
    return () => obs.disconnect();
  }, [revealed]);

  return (
    <div
      ref={cardRef}
      className={`A-diff-card A-diff-card-media A-reveal A-reveal-up ${revealed ? "is-revealed" : ""}`}
      style={{ gridArea: "img", "--child-i": 1 }}
    >
      <video ref={videoRef} muted loop playsInline preload="auto">
        <source src="tand/assets/bento-video.mp4" type="video/mp4" />
      </video>
      <div className="A-diff-media-cover" aria-hidden="true">
        <img className="A-diff-media-cover-logo" src="tand/assets/logo.png" alt="" />
      </div>
      <div className="A-diff-media-tag">
        <span className="A-dot-live" /> Sede Arcos · Querétaro
      </div>
    </div>
  );
};

const Differentiators = () => {
  const d = TAND.differentiators;
  const Card = ({ i, area, variant, ci = 0, iconBottom = false }) => (
    <article
      className={`A-diff-card A-reveal A-reveal-up ${variant ? "A-diff-card-" + variant : ""} ${iconBottom ? "A-diff-card-icon-bottom" : ""}`}
      style={{ gridArea: area, "--child-i": ci }}
    >
      {!iconBottom && (
        <div className="A-diff-icon">
          <img src={`tand/assets/icons/${d[i].icon}.png`} alt="" aria-hidden="true" />
        </div>
      )}
      <h3 className="A-diff-title">{d[i].title}</h3>
      <p className="A-diff-body">{d[i].body}</p>
      {iconBottom && (
        <div className="A-diff-icon A-diff-icon-bottom">
          <img src={`tand/assets/icons/${d[i].icon}.png`} alt="" aria-hidden="true" />
        </div>
      )}
    </article>
  );

  return (
    <section className="A-section A-diff" id="diferenciales">
      <div className="A-section-head A-section-head-center A-reveal A-reveal-up">
        <h2 className="A-h2">Una clínica dental <em>sin los peros</em> de siempre.</h2>
        <p className="A-section-lede">
          Cinco decisiones que cambian cómo se siente ir al dentista. Desde la garantía real hasta la llamada del día siguiente para saber cómo te sentiste.
        </p>
      </div>

      <div className="A-diff-bento A-reveal-stagger">
        {/* Garantía — highlight morada */}
        <article className="A-diff-card A-diff-card-highlight A-reveal A-reveal-up" style={{ gridArea: "g", "--child-i": 0 }}>
          <div className="A-diff-icon">
            <img src={`tand/assets/icons/${d[0].icon}.png`} alt="" aria-hidden="true" />
          </div>
          <h3 className="A-diff-title">{d[0].title}</h3>
          <p className="A-diff-body">{d[0].body}</p>
          <div className="A-diff-guarantee">
            <span>Garantía incondicional</span>
            <em>{TAND.slogan}</em>
          </div>
        </article>

        {/* Video tall — recorrido por la clínica */}
        <VideoBentoCard />

        {/* Cuidado / No juicio — blanca */}
        <Card i={5} area="c" ci={2} iconBottom />

        {/* Tecnología — accent con fondo de imagen */}
        <article className="A-diff-card A-diff-card-accent A-reveal A-reveal-up" style={{ gridArea: "t", "--child-i": 3 }}>
          <div className="A-diff-icon">
            <img src={`tand/assets/icons/${d[3].icon}.png`} alt="" aria-hidden="true" />
          </div>
          <h3 className="A-diff-title">{d[3].title}</h3>
          <p className="A-diff-body">{d[3].body}</p>
        </article>

        {/* Seguimiento — card grande (spans 2 rows) con mock de chat */}
        <article className="A-diff-card A-diff-card-large A-reveal A-reveal-up" style={{ gridArea: "s", "--child-i": 4 }}>
          <div className="A-diff-icon">
            <img src={`tand/assets/icons/${d[1].icon}.png`} alt="" aria-hidden="true" />
          </div>
          <div className="A-mock-chat" aria-hidden="true">
            <div className="A-mock-chat-head">
              <div className="A-mock-chat-avatar">N</div>
              <div className="A-mock-chat-name">
                <strong>Dra. Nicole</strong>
                <span>Especialista tand</span>
              </div>
              <span className="A-mock-chat-dot" />
            </div>
            <div className="A-mock-chat-body">
              <div className="A-mock-bubble A-mock-bubble-them A-mock-bubble-1">
                Hola Ana 👋 ¿Cómo te sentiste después de la cita?
              </div>
              <div className="A-mock-bubble A-mock-bubble-me A-mock-bubble-2">
                Súper bien, sin molestias 🙌
              </div>
              <div className="A-mock-bubble A-mock-bubble-them A-mock-bubble-typing">
                <span /><span /><span />
              </div>
            </div>
          </div>
          <h3 className="A-diff-title">{d[1].title}</h3>
          <p className="A-diff-body">{d[1].body}</p>
        </article>

        {/* Financiamiento — blanca */}
        <Card i={2} area="f" ci={5} />
      </div>
    </section>
  );
};

// ————— Tools (Quoter inline) —————

const Tools = () => {
  const [step, setStep] = useState(0);
  const [specialty, setSpecialty] = useState("ortodoncia");
  const [treatment, setTreatment] = useState("Invisalign Full");
  const [financing, setFinancing] = useState("24");

  const prices = {
    "Invisalign Full": 58000,
    "Invisalign Lite": 38000,
    "Brackets estéticos": 28000,
    "Blanqueamiento": 4800,
    "Carillas cerámicas (x8)": 72000,
    "Diseño de sonrisa": 96000,
    "Implante + corona": 32000,
    "Limpieza profunda": 1200,
    "Endodoncia": 5600,
  };
  const treatmentAssets = {
    "Invisalign Full": "invisalign-case",
    "Invisalign Lite": "aligners",
    "Brackets estéticos": "brackets-clear",
    "Blanqueamiento": "wellness",
    "Carillas cerámicas (x8)": "veneer",
    "Diseño de sonrisa": "veneer",
    "Implante + corona": "implant",
    "Limpieza profunda": "polishing",
    "Endodoncia": "endodontia",
  };
  const groups = {
    ortodoncia: ["Invisalign Full", "Invisalign Lite", "Brackets estéticos"],
    estetica: ["Blanqueamiento", "Carillas cerámicas (x8)", "Diseño de sonrisa"],
    implantes: ["Implante + corona"],
    bienestar: ["Limpieza profunda", "Endodoncia"],
  };

  const price = prices[treatment] || 0;
  const monthly = Math.round(price / parseInt(financing, 10));

  return (
    <section className="A-section A-tools" id="herramientas">
      <div className="A-section-head A-reveal A-reveal-up">
        <h2 className="A-h2">Resuelve tus dudas <em>antes</em> de la primera cita.</h2>
        <p className="A-section-lede">
          Cotiza tu tratamiento, simula tu resultado o habla con una especialista por WhatsApp. Sin moverte de donde estás.
        </p>
      </div>

      <div className="A-tools-grid">
        <div className="A-quoter A-reveal A-reveal-up" id="cotizar" style={{ "--reveal-delay": "80ms" }}>
          <div className="A-quoter-head">
            <div className="A-eyebrow A-eyebrow-dark">Cotizador online</div>
            <div className="A-quoter-step">Paso {step + 1} de 3</div>
          </div>

          <div className="A-quoter-body">
            <div className="A-quoter-field">
              <label>Especialidad</label>
              <div className="A-quoter-options">
                {Object.keys(groups).map((g) => (
                  <button
                    key={g}
                    className={`A-chip ${specialty === g ? "is-active" : ""}`}
                    onClick={() => {
                      setSpecialty(g);
                      setTreatment(groups[g][0]);
                    }}
                  >
                    {g[0].toUpperCase() + g.slice(1)}
                  </button>
                ))}
              </div>
            </div>

            <div className="A-quoter-field">
              <label>Tratamiento</label>
              <div className="A-quoter-options">
                {groups[specialty].map((t) => (
                  <button
                    key={t}
                    className={`A-chip ${treatment === t ? "is-active" : ""}`}
                    onClick={() => setTreatment(t)}
                  >
                    {t}
                  </button>
                ))}
              </div>
            </div>

            <div className="A-quoter-field">
              <label>Financiamiento</label>
              <div className="A-quoter-options">
                {["1", "12", "18", "24"].map((f) => (
                  <button
                    key={f}
                    className={`A-chip ${financing === f ? "is-active" : ""}`}
                    onClick={() => setFinancing(f)}
                  >
                    {f === "1" ? "Contado" : `${f} MSI`}
                  </button>
                ))}
              </div>
            </div>
          </div>

          <div className="A-quoter-result">
            <div className="A-quoter-result-visual">
              <img
                key={treatment}
                className="A-quoter-asset"
                src={`tand/assets/dental/${treatmentAssets[treatment] || "wellness"}.png`}
                alt=""
                aria-hidden="true"
              />
            </div>
            <div className="A-quoter-result-info">
              <div className="A-quoter-result-row">
                <span>Tratamiento</span>
                <strong>{treatment}</strong>
              </div>
              <div className="A-quoter-result-row">
                <span>Precio total</span>
                <strong>${price.toLocaleString("es-MX")} MXN</strong>
              </div>
              <div className="A-quoter-result-row A-quoter-result-monthly">
                <span>{financing === "1" ? "Pago único" : `${financing} meses sin intereses`}</span>
                <strong>
                  ${monthly.toLocaleString("es-MX")}<small>{financing === "1" ? "" : "/mes"}</small>
                </strong>
              </div>
              <div className="A-quoter-actions">
                <a href="#agendar" className="A-btn A-btn-primary">
                  Agendar y confirmar plan <IconArrow />
                </a>
                <a href="#wa" className="A-btn A-btn-ghost">
                  <img src="tand/assets/WhatsApp.png" alt="" aria-hidden="true" className="A-wa-logo" />
                  Hablar con una especialista
                </a>
              </div>
              <p className="A-quoter-foot">
                Precio de referencia. Tu plan definitivo lo armamos en la primera cita, con diagnóstico 3D incluido y sin costo.
              </p>
            </div>
          </div>
        </div>

        <aside className="A-tools-side A-reveal-stagger">
          <article className="A-tool-card A-reveal A-reveal-up" style={{ "--child-i": 0 }}>
            <div className="A-tool-card-num A-tool-card-num-bare">
              <img src="tand/assets/icons/tecnologia.png" alt="" aria-hidden="true" />
            </div>
            <h3>Simulador de sonrisa</h3>
            <p>Sube una foto y mira en 90 segundos cómo se vería tu sonrisa con blanqueamiento, carillas o alineación.</p>
            <a href="#sim" className="A-btn A-btn-text">Probar el simulador <IconArrow /></a>
          </article>
          <article className="A-tool-card A-reveal A-reveal-up" style={{ "--child-i": 1 }}>
            <div className="A-tool-card-num A-tool-card-num-bare">
              <img src="tand/assets/WhatsApp.png" alt="WhatsApp" className="A-wa-logo A-wa-logo-lg" />
            </div>
            <h3>Videoconsulta gratis</h3>
            <p>15 minutos por WhatsApp con una especialista de tand. Resuelve dudas reales, sin costo y sin compromiso.</p>
            <a href="#wa" className="A-btn A-btn-text">Empezar por WhatsApp <IconArrow /></a>
          </article>
          <article className="A-tool-card A-tool-card-dark A-reveal A-reveal-up" style={{ "--child-i": 2 }}>
            <h3>Agendamiento online</h3>
            <p>Elige sede, especialista y horario. Recibes la confirmación al instante por WhatsApp.</p>
            <a href="#agendar" className="A-btn A-btn-white">Agendar cita <IconArrow /></a>
          </article>
        </aside>
      </div>
    </section>
  );
};

// ————— Testimonials —————

const Testimonials = () => {
  const [active, setActive] = useState(0);
  const t = TAND.testimonials[active];
  const initial = t.name.trim().charAt(0).toUpperCase();
  return (
    <section className="A-section A-test">
      <div className="A-section-head A-section-head-split A-reveal A-reveal-up">
        <div>
          <h2 className="A-h2">Pacientes que llegaron <em>con miedo</em> y<br/>se quedaron por años.</h2>
        </div>
        <a className="A-test-rating" href="https://www.google.com/maps" target="_blank" rel="noopener">
          <div className="A-test-rating-logo"><IconGoogle size={26} /></div>
          <div className="A-test-rating-info">
            <div className="A-test-rating-score">
              <span className="A-test-rating-num">{TAND.googleRating.score}</span>
              <span className="A-test-rating-stars">
                {[0,1,2,3,4].map((i) => <IconStar key={i} />)}
              </span>
            </div>
            <div className="A-test-rating-meta">{TAND.googleRating.count} reseñas verificadas en Google</div>
          </div>
        </a>
      </div>

      <article className="A-test-card A-reveal A-reveal-scale">
        <div key={active} className="A-test-card-body">
          <div className="A-test-card-stars">
            {[0,1,2,3,4].map((i) => <IconStar key={i} size={18} />)}
          </div>
          <blockquote>"{t.quote}"</blockquote>
          <div className="A-test-card-foot">
            <div className="A-test-card-author">
              <div className="A-test-avatar" data-letter={initial}>{initial}</div>
              <div className="A-test-card-name">
                <strong>{t.name}</strong>
                <span>{t.age}</span>
              </div>
            </div>
            <div className="A-test-card-treatment">
              <span>Tratamiento</span>
              <strong>{t.treatment}</strong>
            </div>
          </div>
        </div>
      </article>

      <div className="A-test-strip A-reveal A-reveal-up A-reveal-stagger">
        {TAND.testimonials.map((x, i) => (
          <button
            key={x.name}
            onClick={() => setActive(i)}
            className={`A-test-chip ${active === i ? "is-active" : ""}`}
            aria-pressed={active === i}
            style={{ "--child-i": i }}
          >
            <span className="A-test-chip-avatar">{x.name.trim().charAt(0).toUpperCase()}</span>
            <span className="A-test-chip-info">
              <span className="A-test-chip-name">{x.name}</span>
              <span className="A-test-chip-treatment">{x.treatment}</span>
            </span>
          </button>
        ))}
      </div>
    </section>
  );
};

// ————— Locations —————

const Locations = () => (
  <section className="A-section A-loc" id="sedes">
    <div className="A-section-head A-reveal A-reveal-up">
      <h2 className="A-h2"><em>Dos sedes</em> en Querétaro. Una tercera, en camino.</h2>
      <p className="A-section-lede">
        Mismo equipo, misma garantía, mismo trato. Elige la sede que más te quede a la mano.
      </p>
    </div>

    <div className="A-loc-grid A-reveal-stagger">
      {TAND.locations.map((l, idx) => (
        <article
          key={l.id}
          className={`A-loc-card A-reveal A-reveal-up ${l.soon ? "is-soon" : ""}`}
          style={{ "--child-i": idx }}
        >
          <div className="A-loc-map">
            {l.lat && l.lng ? (
              <iframe
                className="A-loc-map-iframe"
                src={`https://www.openstreetmap.org/export/embed.html?bbox=${l.lng - 0.006},${l.lat - 0.004},${l.lng + 0.006},${l.lat + 0.004}&layer=mapnik&marker=${l.lat},${l.lng}`}
                title={`Mapa tand ${l.name}`}
                loading="lazy"
                referrerPolicy="no-referrer-when-downgrade"
              />
            ) : (
              <>
                <div className="A-loc-map-grid" />
                <div className="A-loc-map-pin">
                  <span>{l.name[0]}</span>
                </div>
              </>
            )}
          </div>
          <div className="A-loc-body">
            <h3>tand {l.name}</h3>
            <p className="A-loc-addr">{l.address}</p>
            <p className="A-loc-hours">{l.hours}</p>
            {!l.soon && (
              <div className="A-loc-actions">
                <a href="#agendar" className="A-btn A-btn-dark A-btn-sm">Agendar en esta sede</a>
                <a href={l.mapLink || "#map"} target="_blank" rel="noreferrer" className="A-btn A-btn-text">Cómo llegar</a>
              </div>
            )}
            {l.soon && <div className="A-loc-soon">Próxima apertura · 2026</div>}
          </div>
        </article>
      ))}
    </div>
  </section>
);

// ————— Blog + FAQ —————

const BlogFaq = () => {
  const [openIdx, setOpenIdx] = useState(0);
  return (
    <section className="A-section A-blogfaq" id="blog">
      <div className="A-blogfaq-grid">
        <div className="A-blog A-reveal A-reveal-up">
          <h2 className="A-h3 A-blogfaq-head">Cuida tu sonrisa, <em>también desde casa</em>.</h2>
          <ul className="A-blog-list A-reveal-stagger">
            {TAND.blog.map((b, idx) => (
              <li key={b.title} className="A-reveal A-reveal-up" style={{ "--child-i": idx }}>
                <span className="A-blog-tag">{b.tag}</span>
                <span className="A-blog-title">{b.title}</span>
                <span className="A-blog-meta">{b.read} <IconArrow size={12}/></span>
              </li>
            ))}
          </ul>
          <a href="#todas" className="A-btn A-btn-text">Ver todas las notas del blog <IconArrow /></a>
        </div>

        <div className="A-faq A-reveal A-reveal-up" style={{ "--reveal-delay": "120ms" }}>
          <h2 className="A-h3 A-blogfaq-head">Las dudas que <em>todos tienen</em><br/>antes de agendar.</h2>
          <div className="A-faq-list A-reveal-stagger">
            {TAND.faqs.map((f, i) => (
              <div key={f.q} className={`A-faq-item A-reveal A-reveal-up ${openIdx === i ? "is-open" : ""}`} style={{ "--child-i": i }}>
                <button onClick={() => setOpenIdx(openIdx === i ? -1 : i)}>
                  <span>{f.q}</span>
                  <IconPlus />
                </button>
                <div className="A-faq-answer"><p>{f.a}</p></div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
};

// ————— CTA + Footer —————

const BigCTA = () => (
  <section className="A-bigcta" id="agendar">
    <img className="A-bigcta-deco A-bigcta-deco-l" src="tand/assets/dental/wellness.png" alt="" aria-hidden="true" />
    <img className="A-bigcta-deco A-bigcta-deco-r" src="tand/assets/dental/aligners.png" alt="" aria-hidden="true" />
    <div className="A-bigcta-inner A-reveal A-reveal-scale">
      <h2 className="A-bigcta-title"><em>Amarás</em> venir al dentista.<br/><span>Y si no, te regresamos la cita.</span></h2>
      <p className="A-bigcta-lede">
        Diagnóstico 3D, plan de tratamiento y cotización detallada en menos de una hora. Sin presión para continuar, sin juicio sobre tu historia dental.
      </p>
      <div className="A-bigcta-actions">
        <a href="#agendar" className="A-btn A-btn-white A-btn-lg">Agendar mi primera cita <IconArrow /></a>
        <a href={TAND.phoneHref} className="A-btn A-btn-outline-light A-btn-lg">Llamar al {TAND.phone}</a>
      </div>
    </div>
  </section>
);

const Footer = () => (
  <footer className="A-footer">
    <div className="A-footer-inner">
      <div className="A-footer-brand">
        <img src="tand/assets/logo-purple.png" alt="tand Dental Wellness" />
        <p>Clínica dental integral en Querétaro. Dos sedes, especialistas propios para cada área, cero juicio y un seguimiento que no se olvida de ti.</p>
        <div className="A-footer-contact">
          <a href={TAND.phoneHref}>{TAND.phone}</a>
          <a href="#wa">WhatsApp</a>
          <a href="mailto:hola@tand.mx">hola@tand.mx</a>
        </div>
      </div>

      <div className="A-footer-cols">
        <div>
          <h4>Especialidades</h4>
          <ul>{TAND.services.map(s => <li key={s.id}><a href={`${s.id}.html`}>{s.title}</a></li>)}</ul>
        </div>
        <div>
          <h4>La clínica</h4>
          <ul>
            <li><a href="#">Sobre tand</a></li>
            <li><a href="#">Nuestro equipo</a></li>
            <li><a href="#">Sedes en Querétaro</a></li>
            <li><a href="#">Blog</a></li>
            <li><a href="#">Trabaja con nosotros</a></li>
          </ul>
        </div>
        <div>
          <h4>Para ti</h4>
          <ul>
            <li><a href="#">Portal del paciente</a></li>
            <li><a href="#">Cotizador online</a></li>
            <li><a href="#">Financiamiento</a></li>
            <li><a href="#">Videoconsulta gratis</a></li>
          </ul>
        </div>
        <div>
          <h4>Legal</h4>
          <ul>
            <li><a href="#">Aviso de privacidad</a></li>
            <li><a href="#">Garantía de tratamientos</a></li>
            <li><a href="#">Permiso Cofepris: 2322015036X00477</a></li>
            <li><a href="#">Resp. sanitario: Dra. Nicole Cruz Hinojosa · Ced. 10980043</a></li>
          </ul>
        </div>
      </div>
    </div>

    <div className="A-footer-bottom">
      <span>© 2026 tand · "Amarás venir al dentista" y "Amo ir al dentista" son marcas registradas propiedad de tand.</span>
      <span>Hecho con cuidado clínico, en Querétaro.</span>
    </div>
  </footer>
);

// ————— Sticky mobile bar —————

const StickyBar = () => (
  <div className="A-sticky">
    <a href={TAND.phoneHref} className="A-sticky-item">Llamar</a>
    <a href="#wa" className="A-sticky-item">WhatsApp</a>
    <a href="#cotizar" className="A-sticky-item">Cotizar</a>
    <a href="#agendar" className="A-sticky-item A-sticky-primary">Agendar cita</a>
  </div>
);

Object.assign(window, {
  A_Differentiators: Differentiators,
  A_Tools: Tools,
  A_Testimonials: Testimonials,
  A_Locations: Locations,
  A_BlogFaq: BlogFaq,
  A_BigCTA: BigCTA,
  A_Footer: Footer,
  A_StickyBar: StickyBar,
});
