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

// ============================================
// Logo
// ============================================
function Logo({ size = "md" }) {
  const sizeClass = size === "xl" ? "logo logo-xl" : "logo";
  return (
    <span className={sizeClass}>
      <span>FL</span>
      <span className="l-i">i</span>
      <span>NKS</span>
    </span>
  );
}

// ============================================
// Cursor
// ============================================
function Cursor() {
  const dotRef = useRef(null);
  const ringRef = useRef(null);

  useEffect(() => {
    let dotX = window.innerWidth / 2, dotY = window.innerHeight / 2;
    let ringX = dotX, ringY = dotY;
    let mx = dotX, my = dotY;

    const onMove = (e) => { mx = e.clientX; my = e.clientY; };
    window.addEventListener('mousemove', onMove);

    let raf;
    const tick = () => {
      dotX += (mx - dotX) * 0.5;
      dotY += (my - dotY) * 0.5;
      ringX += (mx - ringX) * 0.15;
      ringY += (my - ringY) * 0.15;
      if (dotRef.current) dotRef.current.style.transform = `translate(${dotX}px, ${dotY}px) translate(-50%, -50%)`;
      if (ringRef.current) ringRef.current.style.transform = `translate(${ringX}px, ${ringY}px) translate(-50%, -50%)`;
      raf = requestAnimationFrame(tick);
    };
    tick();

    const onOver = (e) => {
      const isInteractive = e.target.closest('a, button, .pillar, .case, .stack-item, .chip, .faq-q, input, textarea');
      if (dotRef.current) dotRef.current.classList.toggle('hover', !!isInteractive);
      if (ringRef.current) ringRef.current.classList.toggle('hover', !!isInteractive);
    };
    document.addEventListener('mouseover', onOver);

    return () => {
      window.removeEventListener('mousemove', onMove);
      document.removeEventListener('mouseover', onOver);
      cancelAnimationFrame(raf);
    };
  }, []);

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

// ============================================
// Nav
// ============================================
function Nav({ page, setPage, lang, setLang, t }) {
  const links = [
    { id: 'home', n: '01', label: t.nav.home },
    { id: 'services', n: '02', label: t.nav.services },
    { id: 'about', n: '03', label: t.nav.about },
    { id: 'contact', n: '04', label: t.nav.contact }
  ];
  return (
    <nav className="nav">
      <a href="#" onClick={(e) => { e.preventDefault(); setPage('home'); }}>
        <Logo />
      </a>
      <ul className="nav-links">
        {links.map(l => (
          <li key={l.id}>
            <a href="#"
               className={`nav-link ${page === l.id ? 'active' : ''}`}
               onClick={(e) => { e.preventDefault(); setPage(l.id); }}>
              <span className="num">{l.n}</span>{l.label}
            </a>
          </li>
        ))}
      </ul>
      <div className="nav-right">
        <button className="lang-toggle" onClick={() => setLang(lang === 'pt' ? 'en' : 'pt')}>
          <span className={lang === 'pt' ? 'lang-active' : ''}>PT</span>
          <span className="lang-sep">/</span>
          <span className={lang === 'en' ? 'lang-active' : ''}>EN</span>
        </button>
      </div>
    </nav>
  );
}

// ============================================
// Footer
// ============================================
function Footer({ t, setPage }) {
  const [email, setEmail] = useState('');
  const [subscribed, setSubscribed] = useState(false);
  return (
    <footer className="footer">
      <div className="container">
        <div style={{display: 'grid', gridTemplateColumns: '1fr', gap: '4rem', marginBottom: '4rem'}}>
          <div>
            <Logo size="xl" />
            <p style={{maxWidth: '36ch', marginTop: '1.5rem', fontSize: '1.05rem'}}>{t.footer.tag}</p>
          </div>
        </div>
        <div className="footer-grid">
          <div className="footer-col footer-newsletter">
            <h4>{t.footer.newsletter_title}</h4>
            <p style={{fontSize: '0.9rem', color: 'var(--fg-2)', maxWidth: '36ch'}}>{t.footer.newsletter_desc}</p>
            <form onSubmit={(e) => { e.preventDefault(); if (email) setSubscribed(true); }}>
              <input type="email"
                     placeholder={t.footer.newsletter_placeholder}
                     value={email}
                     onChange={(e) => setEmail(e.target.value)}
                     required />
              <button type="submit">{subscribed ? '✓' : t.footer.newsletter_btn}</button>
            </form>
          </div>
          <div className="footer-col">
            <h4>{t.footer.services_h}</h4>
            <ul>
              {t.footer.services.map((s, i) => (
                <li key={i}><a href="#" onClick={(e) => { e.preventDefault(); setPage('services'); }}>{s}</a></li>
              ))}
            </ul>
          </div>
          <div className="footer-col">
            <h4>{t.footer.company_h}</h4>
            <ul>
              {t.footer.company.map((c, i) => (
                <li key={i}><a href="#" onClick={(e) => { e.preventDefault(); setPage(i === 0 ? 'about' : 'home'); }}>{c}</a></li>
              ))}
            </ul>
          </div>
          <div className="footer-col">
            <h4>{t.footer.contact_h}</h4>
            <ul>
              <li><a href="mailto:contato@flinks.digital">contato@flinks.digital</a></li>
              <li><a href="https://wa.me/5521969112803" target="_blank" rel="noopener">+55 (21) 96911-2803</a></li>
              <li><a href="https://maps.google.com/?q=Av.+Pastor+Martin+Luther+King+Jr.,+126+Sala+812,+Del+Castilho,+Rio+de+Janeiro" target="_blank" rel="noopener">Av. Pastor Martin Luther King Jr., 126<br/>Sala 812 · Del Castilho<br/>Rio de Janeiro / RJ · 21211-080</a></li>
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          <span>{t.footer.bottom_left}</span>
          <span className="footer-status">
            <span className="dot"></span>
            {t.footer.bottom_right}
          </span>
        </div>
      </div>
    </footer>
  );
}

// ============================================
// Reveal helper
// ============================================
function Reveal({ children, delay = 0, className = "", as: Tag = "div" }) {
  const ref = useRef(null);
  const [shown, setShown] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) { setTimeout(() => setShown(true), delay); io.disconnect(); }
    }, { threshold: 0.15 });
    io.observe(el);
    return () => io.disconnect();
  }, [delay]);
  return <Tag ref={ref} className={`reveal ${shown ? 'in' : ''} ${className}`}>{children}</Tag>;
}

// ============================================
// TypeReveal — char-by-char
// ============================================
function TypeReveal({ text, className = "", as: Tag = "span", delay = 0 }) {
  const ref = useRef(null);
  const [shown, setShown] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) { setTimeout(() => setShown(true), delay); io.disconnect(); }
    }, { threshold: 0.2 });
    io.observe(el);
    return () => io.disconnect();
  }, [delay]);
  const chars = String(text).split('');
  return (
    <Tag ref={ref} className={`type-reveal ${shown ? 'in' : ''} ${className}`}>
      {chars.map((c, i) => (
        <span key={i} className="char" style={{transitionDelay: `${i * 22}ms`}}>
          {c === ' ' ? '\u00A0' : c}
        </span>
      ))}
    </Tag>
  );
}

// ============================================
// Hero particles canvas
// ============================================
function HeroParticles() {
  const ref = useRef(null);
  useEffect(() => {
    const canvas = ref.current;
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    let w = canvas.width = canvas.offsetWidth * devicePixelRatio;
    let h = canvas.height = canvas.offsetHeight * devicePixelRatio;
    const onResize = () => {
      w = canvas.width = canvas.offsetWidth * devicePixelRatio;
      h = canvas.height = canvas.offsetHeight * devicePixelRatio;
    };
    window.addEventListener('resize', onResize);

    const N = 60;
    const nodes = Array.from({length: N}, () => ({
      x: Math.random() * w,
      y: Math.random() * h,
      vx: (Math.random() - 0.5) * 0.3,
      vy: (Math.random() - 0.5) * 0.3,
      r: Math.random() * 1.6 + 0.4
    }));

    let raf;
    const draw = () => {
      ctx.clearRect(0, 0, w, h);
      // edges
      for (let i = 0; i < N; i++) {
        for (let j = i + 1; j < N; j++) {
          const dx = nodes[i].x - nodes[j].x;
          const dy = nodes[i].y - nodes[j].y;
          const d = Math.hypot(dx, dy);
          const max = 180 * devicePixelRatio;
          if (d < max) {
            const a = (1 - d / max) * 0.35;
            ctx.strokeStyle = `oklch(0.72 0.24 295 / ${a})`;
            ctx.lineWidth = 1;
            ctx.beginPath();
            ctx.moveTo(nodes[i].x, nodes[i].y);
            ctx.lineTo(nodes[j].x, nodes[j].y);
            ctx.stroke();
          }
        }
      }
      // dots
      nodes.forEach(n => {
        n.x += n.vx;
        n.y += n.vy;
        if (n.x < 0 || n.x > w) n.vx *= -1;
        if (n.y < 0 || n.y > h) n.vy *= -1;
        ctx.fillStyle = 'oklch(0.82 0.16 220 / 0.7)';
        ctx.beginPath();
        ctx.arc(n.x, n.y, n.r * devicePixelRatio, 0, Math.PI * 2);
        ctx.fill();
      });
      raf = requestAnimationFrame(draw);
    };
    draw();
    return () => { cancelAnimationFrame(raf); window.removeEventListener('resize', onResize); };
  }, []);
  return <canvas ref={ref} className="hero-particles"></canvas>;
}

// ============================================
// Marquee
// ============================================
function Marquee({ items }) {
  const doubled = [...items, ...items, ...items];
  return (
    <div className="marquee">
      <div className="marquee-track">
        {doubled.map((item, i) => (
          <span key={i} className="marquee-item">
            {item}
            <span className="dot"></span>
          </span>
        ))}
      </div>
    </div>
  );
}

// Export
Object.assign(window, { Logo, Cursor, Nav, Footer, Reveal, TypeReveal, HeroParticles, Marquee });
