/* global React */
/*
  Shared site sections — Navbar, animated Hero (V2 baseline), DualPain, ProductShowcase, FinalCTA, Footer.
  Reuses primitives from hero-styles.css + animations from site-styles.css.
*/

const { useState, useEffect, useRef } = React;

/* ---------- Hooks ---------- */

function useReveal() {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            e.target.classList.add("in");
            io.unobserve(e.target);
          }
        });
      },
      { threshold: 0.15 }
    );
    el.querySelectorAll(".reveal").forEach((n) => io.observe(n));
    return () => io.disconnect();
  }, []);
  return ref;
}

function useCountUp(target, { duration = 1400, startWhenVisible = true } = {}) {
  const [val, setVal] = useState(0);
  const ref = useRef(null);
  const started = useRef(false);
  useEffect(() => {
    if (!startWhenVisible) return runAnim();
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting && !started.current) {
            started.current = true;
            runAnim();
            io.unobserve(e.target);
          }
        });
      },
      { threshold: 0.4 }
    );
    io.observe(el);
    return () => io.disconnect();
    function runAnim() {
      const start = performance.now();
      const tick = (now) => {
        const t = Math.min(1, (now - start) / duration);
        const eased = 1 - Math.pow(1 - t, 3);
        setVal(Math.round(target * eased));
        if (t < 1) requestAnimationFrame(tick);
      };
      requestAnimationFrame(tick);
    }
  }, [target, duration, startWhenVisible]);
  return [val, ref];
}

/* ---------- Navbar ---------- */

function useIsMobile(bp = 860) {
  // Trata como "mobile" telas estreitas E celular deitado (paisagem baixa):
  // assim um celular na horizontal (largura > 860 mas altura <= 500) usa a
  // coluna única compacta em vez do layout desktop com mockup gigante.
  const calc = () =>
    window.innerWidth <= bp ||
    (window.innerWidth > window.innerHeight && window.innerHeight <= 500);
  const [m, setM] = useState(typeof window !== "undefined" ? calc() : false);
  useEffect(() => {
    const onResize = () => setM(calc());
    onResize();
    window.addEventListener("resize", onResize);
    window.addEventListener("orientationchange", onResize);
    return () => {
      window.removeEventListener("resize", onResize);
      window.removeEventListener("orientationchange", onResize);
    };
  }, [bp]);
  return m;
}

/* Links do menu — alinhados às seções REAIS do site */
const NAV_LINKS = [
  { label: "Home", href: "#topo" },
  { label: "Solução", href: "#fluxo" },
  { label: "Produto", href: "#produto" },
  { label: "Metodologia", href: "#metodologia" },
  { label: "Equipe", href: "#equipe" },
  { label: "Planos", href: "#planos" },
];

function SiteNavbar({ variant = "v1" }) {
  const isMobile = useIsMobile();
  const [open, setOpen] = useState(false);
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 20);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return (
    <header className={`nav-glass${scrolled ? " nav-scrolled" : ""}`}>
      <div
        style={{
          maxWidth: 1440,
          margin: "0 auto",
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          padding: isMobile
            ? (scrolled ? "8px 20px" : "12px 20px")
            : (scrolled ? "10px 56px" : "16px 56px"),
          transition: "padding 0.3s ease",
        }}
      >
        <div className="lh-lockup">
          <div className="mark">
            <img src="assets/logo.png" alt="Lomiens" />
          </div>
          <div className="word">
            <span className="name">LOMIENS</span>
            <span className="tag">data analysis</span>
          </div>
        </div>

        {!isMobile && (
          <nav style={{ display: "flex", alignItems: "center", gap: 26 }}>
          {NAV_LINKS.map((l) => (
            <a
              key={l.href}
              href={l.href}
              data-x={`#${"".replace(/[\u0300-\u036f]/g, "")}`}
              style={{
                fontSize: 10,
                fontWeight: 800,
                color: "rgba(255,255,255,0.55)",
                letterSpacing: "0.25em",
                textTransform: "uppercase",
                textDecoration: "none",
                transition: "color 0.3s",
              }}
              onMouseOver={(e) => (e.currentTarget.style.color = "#fff")}
              onMouseOut={(e) => (e.currentTarget.style.color = "rgba(255,255,255,0.55)")}
            >
              {l.label}
            </a>
          ))}
          </nav>
        )}

        {!isMobile ? (
          <a
            href="#contato"
            className="btn-arrow-anim"
            style={{
              background: "#2f6bff",
              border: "none",
              color: "#fff",
              padding: "12px 20px",
              borderRadius: 999,
              fontSize: 10,
              fontWeight: 900,
              letterSpacing: "0.18em",
              textTransform: "uppercase",
              textDecoration: "none",
              cursor: "pointer",
              boxShadow: "0 10px 30px -10px rgba(47,107,255,0.6)",
            }}
          >
            Falar com a Lomiens
            <i className="fa-solid fa-arrow-right" style={{ fontSize: 10 }}></i>
          </a>
        ) : (
          <button
            onClick={() => setOpen((o) => !o)}
            aria-label="Menu"
            style={{
              background: "rgba(255,255,255,0.06)",
              border: "1px solid rgba(255,255,255,0.14)",
              color: "#fff",
              width: 44,
              height: 44,
              borderRadius: 12,
              cursor: "pointer",
              fontSize: 18,
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
            }}
          >
            <i className={`fa-solid ${open ? "fa-xmark" : "fa-bars"}`}></i>
          </button>
        )}
      </div>

      {isMobile && open && (
        <div
          style={{
            borderTop: "1px solid rgba(255,255,255,0.08)",
            padding: "12px 20px 20px",
            display: "flex",
            flexDirection: "column",
            gap: 2,
            background: "rgba(10,25,60,0.97)",
            backdropFilter: "blur(20px)",
          }}
        >
          {NAV_LINKS.map((l) => (
            <a
              key={l.href}
              href={l.href}
              onClick={() => setOpen(false)}
              style={{
                padding: "13px 8px",
                color: "rgba(255,255,255,0.85)",
                textDecoration: "none",
                fontSize: 12,
                fontWeight: 800,
                letterSpacing: "0.18em",
                textTransform: "uppercase",
                borderRadius: 8,
              }}
            >
              {l.label}
            </a>
          ))}
          <a
            href="#contato"
            onClick={() => setOpen(false)}
            className="lh-btn-primary"
            style={{ marginTop: 10, width: "100%", textDecoration: "none" }}
          >
            Falar com a Lomiens
            <i className="fa-solid fa-arrow-right" style={{ fontSize: 10 }}></i>
          </a>
        </div>
      )}
    </header>
  );
}

/* ---------- Site Hero (Hero V2 evolved + reveals + bobbing mockups) ---------- */

function SiteHero({ variant = "v1" }) {
  const ref = useReveal();
  const isMobile = useIsMobile();
  return (
    <div ref={ref} id="topo" className="lh-stage" style={{ paddingBottom: 0 }}>
      <div className="lh-bg">
        <div className="lh-aurora">
          <div className="lh-blob a"></div>
          <div className="lh-blob b"></div>
        </div>
        <div className="lh-hex"></div>
        <div className="lh-hex-glow"></div>
      </div>

      <div
        style={{
          position: "relative",
          zIndex: 2,
          padding: isMobile ? "16px 20px 0" : "32px 56px 0",
          display: "grid",
          gridTemplateColumns: isMobile ? "minmax(0, 1fr)" : "1.05fr 0.95fr",
          gap: isMobile ? 28 : 56,
          alignItems: "center",
          maxWidth: 1440,
          margin: "0 auto",
          minHeight: isMobile ? 0 : 720,
          width: "100%",
          boxSizing: "border-box",
        }}
      >
        {/* LEFT */}
        <div style={{ minWidth: 0 }}>
          <div className="lh-badge reveal">
            <span className="dot"></span>
            <span>Inteligência operacional para hotelaria</span>
          </div>

          <h1
            className="reveal delay-1"
            style={{
              fontSize: isMobile ? "clamp(30px, 8.5vw, 38px)" : "clamp(40px, 5vw, 64px)",
              fontWeight: 900,
              letterSpacing: "-0.038em",
              lineHeight: 1.04,
              margin: "28px 0 0",
              color: "rgba(255,255,255,0.94)",
              textWrap: "balance",
            }}
          >
            Pedidos se perdem. A recepção lota. Falta mão de obra.
          </h1>

          <div
            className="reveal delay-2"
            style={{
              display: "flex",
              alignItems: "center",
              gap: 12,
              margin: "26px 0 18px",
            }}
          >
            <span
              style={{
                fontSize: 10,
                fontWeight: 900,
                color: "#2f6bff",
                letterSpacing: "0.4em",
                textTransform: "uppercase",
              }}
            >
              Vira o jogo
            </span>
            <div
              style={{
                height: 1,
                flex: 1,
                background: "linear-gradient(to right, rgba(47,107,255,0.5), transparent)",
              }}
            ></div>
          </div>

          <h2
            className="lh-shine reveal delay-2"
            style={{
              fontSize: isMobile ? "clamp(23px, 6.4vw, 28px)" : "clamp(28px, 3.5vw, 46px)",
              fontWeight: 900,
              letterSpacing: "-0.03em",
              lineHeight: 1.08,
              margin: 0,
              textWrap: "balance",
            }}
          >
            A LOMIENS organiza tudo num só fluxo.
          </h2>

          <p
            className="reveal delay-3"
            style={{
              color: "rgba(255,255,255,0.65)",
              fontSize: 17,
              fontWeight: 300,
              lineHeight: 1.55,
              margin: "26px 0 0",
              maxWidth: 540,
            }}
          >
            Concierge digital via QR Code, painel único para a equipe e dashboard com IA.{" "}
            <span style={{ color: "#fff", fontWeight: 500 }}>Sem instalar nada.</span>
          </p>

          <div className="reveal delay-4" style={{ display: "flex", flexDirection: isMobile ? "column" : "row", gap: 14, marginTop: 32 }}>
            <a href="#contato" className="lh-btn-primary btn-arrow-anim" style={{ textDecoration: "none" }}>
              <span>Vamos conversar sobre seu hotel <i className="fa-solid fa-arrow-right" style={{ fontSize: 10 }}></i></span>
            </a>
            <a href="#fluxo" className="lh-btn-outline" style={{ textDecoration: "none" }}><span>Ver a solução</span></a>
          </div>
        </div>

        {/* RIGHT — composição animada */}
        {!isMobile && (
        <div
          style={{
            position: "relative",
            height: 600,
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
          }}
        >
          {/* Glow */}
          <div
            style={{
              position: "absolute",
              inset: "10% 8% 10% 8%",
              borderRadius: "50%",
              background: "rgba(47,107,255,0.28)",
              filter: "blur(90px)",
              zIndex: 0,
            }}
          ></div>

          {/* Browser mockup back */}
          <div
            className="lh-card bob-slow reveal delay-3"
            style={{
              position: "absolute",
              top: 30,
              left: 0,
              width: 380,
              borderRadius: 24,
              padding: 6,
              transform: "rotate(-4deg)",
              zIndex: 1,
              boxShadow: "0 30px 70px -25px rgba(0,0,0,0.7), 0 0 60px -22px rgba(47,107,255,0.45)",
            }}
          >
            <div style={{ display: "flex", alignItems: "center", gap: 6, padding: "10px 12px" }}>
              <span style={{ width: 8, height: 8, borderRadius: "50%", background: "#ff5f57" }}></span>
              <span style={{ width: 8, height: 8, borderRadius: "50%", background: "#febc2e" }}></span>
              <span style={{ width: 8, height: 8, borderRadius: "50%", background: "#28c840" }}></span>
              <div
                style={{
                  marginLeft: 8, flex: 1, background: "rgba(255,255,255,0.1)",
                  borderRadius: 6, padding: "4px 10px", fontSize: 9,
                  color: "rgba(255,255,255,0.55)", letterSpacing: "0.05em",
                }}
              >
                app.lomiens.com/quarto-412
              </div>
            </div>
            <div style={{ background: "#0a1830", borderRadius: 16, overflow: "hidden", height: 230 }}>
              <img
                className="zoomable"
                src="assets/area_colaborador.png"
                alt="Painel do colaborador Lomiens"
                style={{ width: "100%", height: "100%", objectFit: "cover", objectPosition: "top", display: "block" }}
              />
            </div>
          </div>

          {/* QR Code */}
          <div
            className="lh-glass reveal delay-4"
            style={{
              position: "absolute", top: 18, right: 8, padding: 16,
              borderRadius: 22, zIndex: 3,
              boxShadow: "0 20px 50px -20px rgba(0,0,0,0.6)",
              transform: "rotate(6deg)",
            }}
          >
            <QrSvg />
            <div
              style={{
                fontSize: 8, fontWeight: 900, color: "#2f6bff",
                letterSpacing: "0.28em", textTransform: "uppercase",
                textAlign: "center", marginTop: 8,
              }}
            >
              Aponte. Pronto.
            </div>
          </div>

          {/* Phone front */}
          <div
            className="bob reveal delay-2"
            style={{
              position: "absolute", bottom: 0, right: 24, width: 240, height: 480,
              borderRadius: 38,
              background: "linear-gradient(180deg, #16284d 0%, #101e3d 60%, #0b1730 100%)",
              border: "1px solid rgba(255,255,255,0.15)",
              padding: 8, zIndex: 2,
              boxShadow: "0 40px 80px -20px rgba(0,0,0,0.8), 0 0 80px -20px rgba(47,107,255,0.55)",
              transform: "rotate(4deg)",
            }}
          >
            <div
              style={{
                position: "absolute", top: 14, left: "50%",
                transform: "translateX(-50%)", width: 90, height: 22,
                borderRadius: 999, background: "#001529", zIndex: 3,
              }}
            ></div>
            <div style={{ width: "100%", height: "100%", borderRadius: 32, overflow: "hidden", background: "#0a1830" }}>
              <img
                className="zoomable"
                src="assets/LOMIENS_APP_home.png"
                alt="App Lomiens"
                style={{ width: "100%", height: "100%", objectFit: "cover", objectPosition: "top" }}
              />
            </div>
          </div>
        </div>
        )}
      </div>

      {/* Stats strip */}
      <HeroStatsStrip variant={variant} />
    </div>
  );
}

function HeroStatsStrip({ variant }) {
  const isMobile = useIsMobile();
  const stats = [
    { value: 88, suffix: "%", label: "tiveram problemas com pedidos em hotéis" },
    { value: 69, suffix: "%", label: "evitam ligar pra pedir room service" },
    { value: 96, suffix: "%", label: "querem agendar spa e jantar pelo app" },
    { value: 76, suffix: "%", label: "preferem WebApp via QR Code" },
  ];
  return (
    <div
      style={{
        position: "relative", zIndex: 2,
        padding: isMobile ? "36px 20px 48px" : "60px 56px 80px",
        maxWidth: 1440, margin: "0 auto",
      }}
    >
      <div
        style={{
          display: "flex", alignItems: "center", gap: 12, marginBottom: 18,
        }}
      >
        <span
          style={{
            fontSize: 10, fontWeight: 900, color: "#2f6bff",
            letterSpacing: "0.36em", textTransform: "uppercase", whiteSpace: "nowrap",
          }}
        >
          O que os hóspedes já mostram
        </span>
        <div
          style={{
            height: 1, flex: 1,
            background: "linear-gradient(to right, rgba(47,107,255,0.4), transparent)",
          }}
        ></div>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: isMobile ? "repeat(2, 1fr)" : "repeat(4, 1fr)", gap: isMobile ? 12 : 18 }}>
        {stats.map((s, i) => <StatCard key={i} {...s} />)}
      </div>
    </div>
  );
}

function StatCard({ value, suffix, label }) {
  const [v, ref] = useCountUp(value);
  return (
    <div
      ref={ref}
      className="lh-card kpi-card"
      style={{
        borderRadius: 24, padding: "22px 24px 20px",
        display: "flex", alignItems: "center", gap: 18,
      }}
    >
      <div
        className="lh-laser counter"
        style={{
          fontSize: 44, fontWeight: 900, letterSpacing: "-0.04em", lineHeight: 1,
        }}
      >
        {v}{suffix}
      </div>
      <p
        style={{
          color: "rgba(255,255,255,0.65)", fontSize: 12, fontWeight: 300,
          lineHeight: 1.4, margin: 0,
        }}
      >
        {label}
      </p>
    </div>
  );
}

/* QR svg */
function QrSvg() {
  return (
    <div
      style={{
        width: 92, height: 92, borderRadius: 12, background: "#fff",
        padding: 8, display: "flex", alignItems: "center", justifyContent: "center",
      }}
    >
      <svg viewBox="0 0 29 29" style={{ width: "100%", height: "100%" }}>
        <rect width="29" height="29" fill="#fff" />
        {[[0, 0], [22, 0], [0, 22]].map(([x, y], i) => (
          <g key={i} transform={`translate(${x} ${y})`}>
            <rect width="7" height="7" fill="#001529" />
            <rect x="1" y="1" width="5" height="5" fill="#fff" />
            <rect x="2" y="2" width="3" height="3" fill="#001529" />
          </g>
        ))}
        {[
          [9, 1], [10, 2], [12, 1], [14, 3], [16, 2], [18, 1], [20, 3],
          [9, 4], [11, 5], [13, 4], [15, 6], [17, 5], [19, 4],
          [1, 10], [3, 12], [5, 11], [7, 13], [9, 12], [11, 11], [13, 10],
          [15, 12], [17, 11], [19, 13], [21, 10], [23, 12], [25, 11], [27, 10],
          [2, 15], [4, 17], [6, 14], [8, 16], [10, 15], [12, 14], [14, 16],
          [16, 17], [18, 14], [20, 16], [22, 15], [24, 17], [26, 14],
          [9, 22], [11, 24], [13, 23], [15, 22], [17, 24], [19, 23],
          [21, 22], [23, 24], [25, 23], [27, 22],
          [9, 26], [12, 25], [14, 27], [16, 26], [18, 25], [21, 27],
          [24, 25], [26, 27],
        ].map(([x, y], i) => (
          <rect key={i} x={x} y={y} width="1" height="1" fill="#001529" />
        ))}
      </svg>
    </div>
  );
}

Object.assign(window, {
  SiteNavbar, SiteHero, useReveal, useCountUp, StatCard, useIsMobile,
});
