/* global React, Icon, Logo, useReveal, CTA */
const { useState, useEffect, useRef, useMemo, useCallback } = React;

// ─── Hero ───
function Hero() {
  return (
    <section className="hero" id="top">
      <div className="hero-bg"/>
      <div className="hero-orbs">
        <div className="orb orb--cream"/>
        <div className="orb orb--white"/>
        <div className="orb orb--small"/>
      </div>
      <div className="hero-topbar">
        <div className="shell">
          <a href="#top" className="hero-logo">
            <img src="assets/logo-full.png" alt="CCA Cosmetologia Consciente aplicada" className="hero-logo-img"/>
          </a>
        </div>
      </div>
      <div className="hero-portrait-wrap reveal reveal-delay-2">
        <div className="hero-arabesque"/>
        <div className="hero-portrait-glow"/>
        <div className="hero-portrait" role="img" aria-label="Especialista em Cosmetologia Consciente aplicada"/>
      </div>
      <div className="shell hero-content">
        <div className="hero-text">
          <h1 className="h1 reveal reveal-delay-1">
            Você não precisa decorar protocolos quando aprende a <em>pensar como uma cosmetóloga.</em>
          </h1>
          <p className="hero-sub reveal reveal-delay-2">
            Aprenda a analisar fórmulas, montar estratégias personalizadas, conduzir consultorias e tomar decisões com segurança sem depender da opinião dos outros.
          </p>
        </div>
      </div>
    </section>
  );
}

// ─── Prática (cream) ───
function Pratica() {
  const data = window.CCA_DATA.practicePoints;
  return (
    <section className="section section--cream" id="pratica">
      <div className="shell">
        <div className="section-head">
          <h2 className="h2">O CCA na prática</h2>
          <p className="lead">Um método estruturado para quem quer parar de improvisar e entregar consultoria de skincare com autoridade clínica.</p>
        </div>
        <div className="pratica-grid">
          {data.map((p, i) => {
            const IconEl = Icon[p.icon] || Icon.check;
            return (
              <div key={i} className="pratica-item reveal" style={{transitionDelay: `${i * 0.06}s`}}>
                <div className="icon"><IconEl/></div>
                <div>
                  <h4>{p.title}</h4>
                  <p>{p.body}</p>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
}

// ─── Testimonials carousel ───
function Testimonials() {
  const items = window.CCA_DATA.testimonials;
  const [page, setPage] = useState(0);
  const [perPage, setPerPage] = useState(3);
  useEffect(() => {
    const update = () => {
      const w = window.innerWidth;
      setPerPage(w < 800 ? 1 : w < 1100 ? 2 : 3);
    };
    update();
    window.addEventListener("resize", update);
    return () => window.removeEventListener("resize", update);
  }, []);
  const pages = Math.max(1, Math.ceil(items.length / perPage));
  useEffect(() => { setPage(p => Math.min(p, pages - 1)); }, [pages]);
  const visible = items.slice(page * perPage, page * perPage + perPage);

  return (
    <section className="section" id="depoimentos">
      <div className="shell">
        <div className="section-head">
          <h2 className="h2 cream-text">O que as alunas estão dizendo</h2>
          <p className="lead">+1.200 profissionais já aplicam o método CCA nos seus atendimentos.</p>
        </div>
        <div className="testimonials">
          <div className="testimonial-track" key={page}>
            {visible.map((t, i) => (
              <article key={`${page}-${i}`} className="testimonial-card reveal" style={{transitionDelay: `${i * 0.08}s`}}>
                <div className="stars">
                  {Array.from({length: t.stars}).map((_, k) => (
                    <Icon.star key={k} style={{width: 14, height: 14}}/>
                  ))}
                </div>
                <blockquote>{t.quote}</blockquote>
                <div className="person">
                  <div className="avatar">{t.initials}</div>
                  <div>
                    <b>{t.name}</b>
                    <span>{t.role}</span>
                  </div>
                </div>
              </article>
            ))}
          </div>
          <div className="testimonial-controls">
            {Array.from({length: pages}).map((_, i) => (
              <button
                key={i}
                className={`testimonial-dot ${i === page ? "is-active" : ""}`}
                onClick={() => setPage(i)}
                aria-label={`Página ${i + 1}`}
              />
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

// ─── Resultados (infinite marquee of real before/after) ───
function Resultados() {
  const cases = window.CCA_DATA.cases;
  // Duplicate the array 2x so the CSS animation translateX(-50%) loops seamlessly
  const loop = [...cases, ...cases];

  return (
    <section className="section section--results" id="resultados">
      <div className="shell">
        <div className="section-head">
          <h2 className="h2 cream-text">Resultados do método CCA</h2>
          <p className="lead">Antes e depois de alunas que seguiram protocolos personalizados elaborados através da Cosmetologia Consciente Aplicada, de forma online e sem procedimentos estéticos.</p>
        </div>
      </div>

      <div className="marquee" aria-label="Carrossel infinito de antes e depois">
        <div className="marquee-track">
          {loop.map((c, i) => (
            <div key={i} className="case-tile" aria-hidden={i >= cases.length}>
              <img src={c.image} alt={`Antes e depois: ${c.label}`} loading="lazy"/>
              <div className="case-tile-labels">
                <span>Antes</span>
                <span>Depois</span>
              </div>
              <div className="case-tile-caption">
                <b>{c.label}</b>
                <span>{c.duration}</span>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ─── Video Testimonials (3 × 9:16, click → fullscreen lightbox) ───
function VideoTestimonials() {
  const items = window.CCA_DATA.videoTestimonials || [];
  const [openIdx, setOpenIdx] = useState(null);
  const videoRefs = useRef([]);
  const lightboxVideoRef = useRef(null);

  // Lock body scroll while lightbox open + ESC to close
  useEffect(() => {
    if (openIdx === null) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    const onKey = (e) => { if (e.key === "Escape") setOpenIdx(null); };
    window.addEventListener("keydown", onKey);
    // auto-play when opens
    requestAnimationFrame(() => {
      const v = lightboxVideoRef.current;
      if (v) { try { v.currentTime = 0; v.play(); } catch (_) {} }
    });
    return () => {
      document.body.style.overflow = prev;
      window.removeEventListener("keydown", onKey);
    };
  }, [openIdx]);

  const open = (i) => {
    // pause any inline preview
    videoRefs.current.forEach((vid) => { if (vid) { try { vid.pause(); } catch(_) {} } });
    setOpenIdx(i);
  };
  const close = () => setOpenIdx(null);

  return (
    <section className="section section--video-testimonials" id="depoimentos-video">
      <div className="shell">
        <div className="section-head">
          <h2 className="h2 cream-text">Quem aplica o método CCA</h2>
          <p className="lead">Profissionais reais contando como o método mudou a forma de conduzir consultoria.</p>
        </div>

        <div className="video-grid">
          {items.map((v, i) => (
            <article key={i} className="video-card">
              <button
                type="button"
                className="video-card-frame"
                onClick={() => open(i)}
                aria-label={`Assistir depoimento de ${v.name}`}
              >
                {v.src ? (
                  <video
                    ref={(el) => (videoRefs.current[i] = el)}
                    src={v.src}
                    poster={v.poster || undefined}
                    playsInline
                    muted
                    preload="metadata"
                    tabIndex={-1}
                  />
                ) : (
                  <div className="video-card-placeholder">
                    <svg viewBox="0 0 24 24" fill="currentColor" width="32" height="32">
                      <path d="M8 5v14l11-7z"/>
                    </svg>
                    <span>Vídeo {i + 1}</span>
                  </div>
                )}
                <span className="video-card-play" aria-hidden="true">
                  <svg viewBox="0 0 24 24" width="22" height="22" fill="currentColor">
                    <path d="M8 5v14l11-7z"/>
                  </svg>
                </span>
              </button>
              <div className="video-card-meta">
                <b>{v.name}</b>
                <span>{v.role}</span>
              </div>
            </article>
          ))}
        </div>
      </div>

      {openIdx !== null && items[openIdx] && (
        <div
          className="video-lightbox"
          role="dialog"
          aria-modal="true"
          aria-label={`Depoimento de ${items[openIdx].name}`}
          onClick={close}
        >
          <button
            type="button"
            className="video-lightbox-close"
            onClick={close}
            aria-label="Fechar vídeo"
          >
            <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
              <path d="M6 6l12 12M18 6L6 18"/>
            </svg>
          </button>
          <div className="video-lightbox-frame" onClick={(e) => e.stopPropagation()}>
            <video
              ref={lightboxVideoRef}
              src={items[openIdx].src}
              poster={items[openIdx].poster || undefined}
              controls
              autoPlay
              playsInline
              preload="metadata"
            />
            <div className="video-lightbox-meta">
              <b>{items[openIdx].name}</b>
              <span>{items[openIdx].role}</span>
            </div>
          </div>
        </div>
      )}
    </section>
  );
}

Object.assign(window, {Hero, Pratica, Testimonials, Resultados, VideoTestimonials});
