/* global React */
// Shared primitives + working navigation + motion helpers

const { useState, useEffect, useRef } = React;

// --- Lucide icon wrapper -------------------------------------------------
function Icon({ name, size = 20, stroke = 1.6, className = "", style = {} }) {
  const ref = useRef(null);
  useEffect(() => {
    if (ref.current && window.lucide) {
      ref.current.innerHTML = "";
      const el = document.createElement("i");
      el.setAttribute("data-lucide", name);
      ref.current.appendChild(el);
      window.lucide.createIcons({
        attrs: { width: size, height: size, "stroke-width": stroke },
        nameAttr: "data-lucide",
      });
    }
  }, [name, size, stroke]);
  return <span ref={ref} className={"tf-ico " + className} style={{ display: "inline-flex", ...style }} />;
}

function Eyebrow({ children, light = false, center = false }) {
  return (
    <div className={"tf-eyebrow" + (light ? " on-dark" : "") + (center ? " center" : "")}>
      <span className="rule" />
      {children}
    </div>
  );
}

// Smooth-scroll to an on-page anchor; otherwise let the browser navigate
function navTo(e, href) {
  if (href && href.charAt(0) === "#") {
    const el = document.querySelector(href);
    if (el) { e.preventDefault(); el.scrollIntoView({ behavior: "smooth", block: "start" }); }
  }
}

function Button({ children, variant = "primary", size = "md", icon, iconRight, onClick, href }) {
  const cls = `tf-btn tf-btn-${variant} tf-btn-${size}`;
  const inner = (
    <>
      {icon && <Icon name={icon} size={size === "lg" ? 20 : 18} />}
      <span>{children}</span>
      {iconRight && <Icon name={iconRight} size={size === "lg" ? 20 : 18} />}
      <span className="tf-btn-shine" />
    </>
  );
  if (href) return <a className={cls} href={href} onClick={(e) => { navTo(e, href); onClick && onClick(e); }}>{inner}</a>;
  return <button className={cls} onClick={onClick}>{inner}</button>;
}

function Logo({ onDark = false, size = 46, showText = true, href = "index.html" }) {
  const src = onDark ? "assets/logo-tf-ondark.png" : "assets/logo-tf.png";
  return (
    <a className="tf-logo" href={href} onClick={(e) => navTo(e, href)}>
      <img src={src} alt="Thays Fernandes" style={{ width: size, height: size }} />
      {showText && (
        <div className="tf-logo-txt">
          <span className={"name" + (onDark ? " on-dark" : "")}>Thays Fernandes</span>
          <span className="sub">Tricologista</span>
        </div>
      )}
    </a>
  );
}

// --- Navbar --------------------------------------------------------------
// base = "" on the home page (anchors are #id); "index.html" on sub-pages.
function Navbar({ onBook, base = "" }) {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 24);
    window.addEventListener("scroll", onScroll);
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  const links = [
    { l: "Início", h: base + "#topo" },
    { l: "Tratamentos", h: base + "#tratamentos" },
    { l: "Tecnologia", h: base + "#tecnologia" },
    { l: "Método", h: base + "#metodo" },
    { l: "Sobre", h: base + "#sobre" },
    { l: "Contato", h: base + "#contato" },
  ];
  return (
    <header className={"tf-nav" + (scrolled ? " scrolled" : "")}>
      <div className="tf-nav-inner">
        <Logo href={base || "#topo"} />
        <nav className="tf-nav-links">
          {links.map((x, i) => (
            <a key={x.l} href={x.h} className={i === 0 && base === "" ? "active" : ""} onClick={(e) => navTo(e, x.h)}>{x.l}</a>
          ))}
        </nav>
        <div className="tf-nav-actions">
          <a className="tf-nav-phone" href={(window.TF_CONTACT&&window.TF_CONTACT.whatsapp)||"#"} target="_blank" rel="noreferrer">
            <Icon name="phone" size={16} /> {(window.TF_CONTACT&&window.TF_CONTACT.phoneDisplay)||"WhatsApp"}
          </a>
          <Button variant="primary" size="sm" icon="calendar-check" onClick={onBook}>Agendar avaliação</Button>
        </div>
      </div>
    </header>
  );
}

// --- Footer --------------------------------------------------------------
function Footer({ onBook, base = "" }) {
  return (
    <footer className="tf-footer tf-glow tf-glow-gold">
      <div className="tf-footer-halo" />
      <div className="tf-footer-inner">
        <div className="tf-footer-cta">
          <Eyebrow light>Comece hoje</Eyebrow>
          <h2 className="tf-footer-h">A saúde do seu cabelo<br/>começa no diagnóstico.</h2>
          <Button variant="gold" size="lg" icon="calendar-check" onClick={onBook}>Agendar avaliação</Button>
        </div>
        <div className="tf-footer-grid">
          <div className="tf-footer-brand">
            <Logo onDark size={52} href={base || "#topo"} />
            <p>Terapia capilar e tricologia. Tratamentos personalizados para queda, calvície e fios danificados.</p>
            <div className="tf-socials">
              <a href={(window.TF_CONTACT&&window.TF_CONTACT.instagram)||"#"} target="_blank" rel="noreferrer" aria-label="Instagram"><Icon name="camera" size={18}/></a>
              <a href={(window.TF_CONTACT&&window.TF_CONTACT.whatsapp)||"#"} target="_blank" rel="noreferrer" aria-label="WhatsApp"><Icon name="message-circle" size={18}/></a>
              <a href={"mailto:"+((window.TF_CONTACT&&window.TF_CONTACT.email)||"")} aria-label="E-mail"><Icon name="mail" size={18}/></a>
            </div>
          </div>
          <div className="tf-footer-col">
            <h4>Tratamentos</h4>
            <a href="tratamento.html?id=avaliacao">Avaliação tricológica</a>
            <a href="tratamento.html?id=terapia">Terapia capilar</a>
            <a href="tratamento.html?id=queda">Queda e calvície</a>
            <a href="tratamento.html?id=fios">Fios danificados</a>
          </div>
          <div className="tf-footer-col">
            <h4>Atendimento</h4>
            <a href={(window.TF_CONTACT&&window.TF_CONTACT.whatsapp)||"#"} target="_blank" rel="noreferrer"><Icon name="phone" size={15}/> {(window.TF_CONTACT&&window.TF_CONTACT.phoneDisplay)||""}</a>
            <a href="#" onClick={(e)=>e.preventDefault()}><Icon name="map-pin" size={15}/> Clínica Med Clin · Serro/MG</a>
            <a href="#" onClick={(e)=>e.preventDefault()}><Icon name="clock" size={15}/> Seg–Sáb · 9h às 19h</a>
          </div>
        </div>
        <div className="tf-footer-base">
          <span>© 2026 Thays Fernandes · Tricologista</span>
          <span>Resposta em até 24h</span>
        </div>
      </div>
    </footer>
  );
}

// --- Motion: scroll-reveal + smooth cursor spotlight ---------------------
function initMotion() {
  // reveal on scroll
  const io = new IntersectionObserver((entries) => {
    entries.forEach((en) => { if (en.isIntersecting) { en.target.classList.add("in"); io.unobserve(en.target); } });
  }, { threshold: 0.12, rootMargin: "0px 0px -8% 0px" });
  document.querySelectorAll("[data-reveal]").forEach((el) => io.observe(el));

  initSpotlight();
}

/* Global Cursor Spotlight — one continuous layer that follows the cursor across
   the whole site (header, sides, all sections) with no per-section clipping.
   - #tf-spotlight: a single fixed, viewport-sized green radial-gradient, shown
     through the transparent light-section backgrounds (z-index 1, behind the
     z-index-2 sections) so it only ever appears in the background.
   - dark sections (method/footer) are opaque, so each gets a .tf-darkglow gold
     layer behind its content.
   - smooth rAF position lerp; green fades out / gold fades in when the cursor
     crosses into a dark section (and vice-versa) for a soft colour transition.
   - disabled on touch / very small screens for performance. */
function initSpotlight() {
  const coarse = window.matchMedia("(hover: none), (pointer: coarse)").matches;
  if (coarse || window.innerWidth < 768) return;

  const page = document.querySelector(".tf-page");
  if (!page) return;

  let spot = page.querySelector(":scope > #tf-spotlight");
  if (!spot) {
    spot = document.createElement("div");
    spot.id = "tf-spotlight";
    page.insertBefore(spot, page.firstChild);
  }

  const darks = Array.from(document.querySelectorAll(".tf-method, .tf-footer")).map((el) => {
    let glow = el.querySelector(":scope > .tf-darkglow");
    if (!glow) {
      glow = document.createElement("div");
      glow.className = "tf-darkglow";
      el.insertBefore(glow, el.firstChild);
    }
    return { el, glow };
  });

  const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
  const ease = reduce ? 1 : 0.16;
  let tx = 0, ty = 0, cx = 0, cy = 0, gOp = 0;
  const dOp = darks.map(() => 0);
  let moved = false, raf = 0;

  function inRect(r, x, y) { return x >= r.left && x <= r.right && y >= r.top && y <= r.bottom; }

  function frame() {
    cx += (tx - cx) * ease;
    cy += (ty - cy) * ease;

    // which dark section is the cursor over? (viewport coords; spotlight is fixed)
    let active = -1;
    for (let i = 0; i < darks.length; i++) {
      if (inRect(darks[i].el.getBoundingClientRect(), tx, ty)) { active = i; break; }
    }

    // global green: visible everywhere EXCEPT over a dark section
    const gTarget = (moved && active === -1) ? 1 : 0;
    gOp += (gTarget - gOp) * ease;
    spot.style.setProperty("--sx", cx + "px");
    spot.style.setProperty("--sy", cy + "px");
    spot.style.opacity = gOp.toFixed(3);

    // per dark section gold glow
    darks.forEach((d, i) => {
      const t = (moved && active === i) ? 1 : 0;
      dOp[i] += (t - dOp[i]) * ease;
      d.glow.style.opacity = dOp[i].toFixed(3);
      if (active === i) {
        const r = d.el.getBoundingClientRect();
        d.glow.style.setProperty("--dx", (cx - r.left) + "px");
        d.glow.style.setProperty("--dy", (cy - r.top) + "px");
      }
    });

    raf = requestAnimationFrame(frame);
  }

  window.addEventListener("mousemove", (e) => { tx = e.clientX; ty = e.clientY; moved = true; }, { passive: true });
  window.addEventListener("mouseleave", () => { moved = false; });
  raf = requestAnimationFrame(frame);
}

Object.assign(window, { Icon, Eyebrow, Button, Logo, Navbar, Footer, navTo, initMotion });
