/* global React */
const { useState, useEffect, useRef } = React;

// ============================================
// LOGO
// ============================================
window.Logo = function Logo({ size = 26 }) {
  return (
    <img
      src="Images/image01.png"
      alt="AICO Agency"
      className="nav-logo-img"
      style={{ height: size + "px" }}
    />
  );
};

// ============================================
// MAGNETIC CURSOR
// ============================================
window.MagnetCursor = function MagnetCursor() {
  const dotRef = useRef(null);
  const ringRef = useRef(null);

  useEffect(() => {
    if (window.matchMedia("(max-width: 720px)").matches) return;

    let mouseX = window.innerWidth / 2, mouseY = window.innerHeight / 2;
    let ringX = mouseX, ringY = mouseY;
    let raf;

    const onMove = (e) => {
      mouseX = e.clientX; mouseY = e.clientY;
      if (dotRef.current) {
        dotRef.current.style.left = mouseX + "px";
        dotRef.current.style.top = mouseY + "px";
      }
      const el = document.elementFromPoint(mouseX, mouseY);
      const interactive = el && el.closest && el.closest("a, button, .cta, .svc-card, .stack-cell, [data-magnet]");
      const textArea = el && el.closest && el.closest("input, textarea, [contenteditable]");
      if (dotRef.current && ringRef.current) {
        dotRef.current.classList.toggle("large", !!interactive);
        dotRef.current.classList.toggle("text", !!textArea);
        ringRef.current.classList.toggle("hidden", !!interactive);
      }
    };

    const tick = () => {
      ringX += (mouseX - ringX) * 0.18;
      ringY += (mouseY - ringY) * 0.18;
      if (ringRef.current) {
        ringRef.current.style.left = ringX + "px";
        ringRef.current.style.top = ringY + "px";
      }
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);

    window.addEventListener("mousemove", onMove);
    return () => {
      window.removeEventListener("mousemove", onMove);
      cancelAnimationFrame(raf);
    };
  }, []);

  return (
    <>
      <div ref={dotRef} className="magnet-cursor"/>
      <div ref={ringRef} className="magnet-ring"/>
    </>
  );
};

// ============================================
// REVEAL ON SCROLL
// ============================================
window.useReveal = function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll(".reveal");
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting) {
          e.target.classList.add("in");
          io.unobserve(e.target);
        }
      });
    }, { threshold: 0.12, rootMargin: "0px 0px -80px 0px" });
    els.forEach(el => io.observe(el));
    return () => io.disconnect();
  });
};

// ============================================
// ANIMATED COUNTER
// ============================================
window.Counter = function Counter({ value, suffix = "", duration = 1600 }) {
  const [current, setCurrent] = useState(0);
  const ref = useRef(null);
  const startedRef = useRef(false);

  useEffect(() => {
    const node = ref.current;
    if (!node) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting && !startedRef.current) {
          startedRef.current = true;
          const start = performance.now();
          const animate = (t) => {
            const p = Math.min(1, (t - start) / duration);
            const eased = 1 - Math.pow(1 - p, 3);
            setCurrent(Math.round(eased * value));
            if (p < 1) requestAnimationFrame(animate);
          };
          requestAnimationFrame(animate);
        }
      });
    }, { threshold: 0.4 });
    io.observe(node);
    return () => io.disconnect();
  }, [value, duration]);

  return (
    <span ref={ref}>
      {current}
      <span className="unit">{suffix}</span>
    </span>
  );
};

// ============================================
// LANGUAGE TOGGLE
// ============================================
window.LangToggle = function LangToggle({ lang, setLang }) {
  return (
    <div className="lang-toggle" data-magnet>
      <button className={lang === "es" ? "active" : ""} onClick={() => setLang("es")}>ES</button>
      <button className={lang === "en" ? "active" : ""} onClick={() => setLang("en")}>EN</button>
    </div>
  );
};

// ============================================
// STATUS BAR + NAV
// ============================================
window.StatusBar = function StatusBar({ t }) {
  const [time, setTime] = useState("");
  useEffect(() => {
    const update = () => {
      const d = new Date();
      const h = String(d.getUTCHours()).padStart(2, "0");
      const m = String(d.getUTCMinutes()).padStart(2, "0");
      const s = String(d.getUTCSeconds()).padStart(2, "0");
      setTime(`${h}:${m}:${s} UTC`);
    };
    update();
    const i = setInterval(update, 1000);
    return () => clearInterval(i);
  }, []);
  return (
    <div className="statusbar">
      <div className="statusbar-inner">
        <div className="statusbar-left">
          <span><span className="status-dot"/>{t.status.label}</span>
          <span className="hide-mobile">{t.status.loc}</span>
        </div>
        <div className="statusbar-right">
          <span className="hide-mobile">{t.status.uptime}</span>
          <span className="status-time">{time}</span>
        </div>
      </div>
    </div>
  );
};

window.Footer = function Footer({ t }) {
  return (
    <footer className="footer">
      <div className="wrap">
        <div className="footer-inner">
          <span>{t.footer.left}</span>
          <span>{t.footer.mid}</span>
          <span>{t.footer.right}</span>
        </div>
      </div>
    </footer>
  );
};

window.Nav = function Nav({ t, lang, setLang, direction, setDirection, navLinks, navCtaHref }) {
  const [menuOpen, setMenuOpen] = useState(false);
  const links = navLinks || [
    { href: "#services", idx: "01", label: t.nav.services },
    { href: "#process", idx: "02", label: t.nav.process },
    { href: "#stack", idx: "03", label: t.nav.stack },
    { href: "#contact", idx: "04", label: t.nav.contact },
  ];

  useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") setMenuOpen(false); };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, []);

  useEffect(() => {
    document.body.style.overflow = menuOpen ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [menuOpen]);

  const close = () => setMenuOpen(false);

  return (
    <nav className={`nav${menuOpen ? " nav-open" : ""}`}>
      <div className="nav-inner">
        <a href="/" className="nav-logo" data-magnet>
          <Logo/>
          <span>AICO/AGENCY</span>
        </a>
        <div id="main-nav-links" className={`nav-links${menuOpen ? " open" : ""}`} onClick={close}>
          {links.map((l, i) => (
            <a key={i} href={l.href} onClick={close}><span className="idx">{l.idx}</span>{l.label}</a>
          ))}
          <a href={navCtaHref || "#contact"} className="cta nav-drawer-cta" onClick={close}>
            {t.nav.cta} <span className="arrow">→</span>
          </a>
        </div>
        <div className="nav-right">
          <LangToggle lang={lang} setLang={setLang}/>
          <button
            className="theme-toggle"
            onClick={() => setDirection(direction === "a" ? "b" : "a")}
            aria-label="Toggle color mode"
            title={direction === "a" ? "Modo claro" : "Modo oscuro"}
          >
            {direction === "a"
              ? <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><circle cx="7" cy="7" r="6" stroke="currentColor" strokeWidth="1.2"/><path d="M7 1 A6 6 0 0 1 7 13 Z" fill="currentColor"/></svg>
              : <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><circle cx="7" cy="7" r="6" stroke="currentColor" strokeWidth="1.2"/><path d="M7 1 A6 6 0 0 0 7 13 Z" fill="currentColor"/></svg>
            }
          </button>
          <button
            className="nav-ai-btn"
            id="chatToggle"
            aria-expanded="false"
            aria-label="Abrir Aico AI"
          >
            <svg fill="none" viewBox="0 0 20 20">
              <path d="M10 2L11.8 7.2L17 9L11.8 10.8L10 16L8.2 10.8L3 9L8.2 7.2L10 2Z" fill="currentColor"/>
              <path d="M16 1L16.9 3.1L19 4L16.9 4.9L16 7L15.1 4.9L13 4L15.1 3.1L16 1Z" fill="currentColor" opacity="0.6"/>
            </svg>
            <span>Aico AI</span>
          </button>
          <a href={navCtaHref || "#contact"} className="cta nav-desktop-cta">
            {t.nav.cta} <span className="arrow">→</span>
          </a>
          <button
            className="nav-hamburger"
            onClick={() => setMenuOpen(o => !o)}
            aria-label={menuOpen ? "Cerrar menú" : "Abrir menú"}
            aria-expanded={menuOpen}
            aria-controls="main-nav-links"
          >
            {menuOpen ? "✕" : "☰"}
          </button>
        </div>
      </div>
    </nav>
  );
};
