// RDG — Layout components: Nav, Hero, Footer
const { useState, useEffect, useRef } = React;

// ---------- NAVBAR ----------
function Nav({ t, lang, setLang, theme, toggleTheme }) {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 12);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  const links = [
    { href: '#services', label: t.nav.services },
    { href: '#about', label: t.nav.about },
    { href: '#cases', label: t.nav.cases },
    { href: '#pricing', label: t.nav.pricing },
    { href: '#contact', label: t.nav.contact },
  ];

  return (
    <header className={`rdg-nav ${scrolled ? 'scrolled' : ''}`}>
      <div className="container rdg-nav-inner">
        <a href="#top" className="rdg-brand" aria-label="RDG Tecnology">
          <RdgMark />
          <span className="rdg-brand-text">
            <span className="rdg-brand-name">RDG</span>
            <span className="rdg-brand-sub">Tecnology</span>
          </span>
        </a>

        <nav className="rdg-nav-links" aria-label="Primary">
          {links.map(l => <a key={l.href} href={l.href}>{l.label}</a>)}
        </nav>

        <div className="rdg-nav-actions">
          <div className="rdg-lang" role="group" aria-label="Language">
            <button onClick={() => setLang('es')} className={lang === 'es' ? 'on' : ''} aria-pressed={lang === 'es'}>ES</button>
            <span>/</span>
            <button onClick={() => setLang('en')} className={lang === 'en' ? 'on' : ''} aria-pressed={lang === 'en'}>EN</button>
          </div>
          <button className="rdg-theme-btn" onClick={toggleTheme} aria-label="Toggle theme">
            {theme === 'dark' ? <SunIcon /> : <MoonIcon />}
          </button>
          <a href="#contact" className="btn btn-primary rdg-cta-desktop">
            {t.nav.cta} <ArrowIcon />
          </a>
          <button className="rdg-burger" onClick={() => setOpen(o => !o)} aria-label="Menu" aria-expanded={open}>
            <span /><span /><span />
          </button>
        </div>
      </div>

      <div className={`rdg-mobile ${open ? 'open' : ''}`}>
        <div className="rdg-mobile-inner">
          {links.map(l => (
            <a key={l.href} href={l.href} onClick={() => setOpen(false)}>{l.label}</a>
          ))}
          <a href="#contact" className="btn btn-primary" onClick={() => setOpen(false)}>{t.nav.cta}</a>
        </div>
      </div>
    </header>
  );
}

function RdgMark() {
  return (
    <svg viewBox="0 0 64 64" width="36" height="36" aria-hidden="true" className="rdg-mark">
      <defs>
        <linearGradient id="rdg-g" x1="0" y1="0" x2="1" y2="1">
          <stop offset="0%" stopColor="#1e4a7a" />
          <stop offset="100%" stopColor="#36a8a8" />
        </linearGradient>
      </defs>
      <path d="M32 4 L56 18 L56 46 L32 60 L8 46 L8 18 Z"
            fill="none" stroke="url(#rdg-g)" strokeWidth="2.5" strokeLinejoin="round" />
      <text x="32" y="40" textAnchor="middle" fontSize="20"
            fontFamily="Inter Tight, sans-serif" fontWeight="700"
            fill="url(#rdg-g)" letterSpacing="-1">RDG</text>
    </svg>
  );
}

function ArrowIcon() {
  return <svg className="arrow" width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M3 7h8m0 0L7.5 3.5M11 7l-3.5 3.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" /></svg>;
}
function SunIcon() {
  return <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><circle cx="12" cy="12" r="4" /><path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41" strokeLinecap="round" /></svg>;
}
function MoonIcon() {
  return <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z" strokeLinejoin="round" /></svg>;
}

// ---------- HERO ----------
function Hero({ t }) {
  const heroRef = useRef(null);

  return (
    <section className="rdg-hero" ref={heroRef} id="top">
      <div className="rdg-hero-bg" aria-hidden="true">
        <div className="rdg-hero-grid" />
        <HeroCanvas />
        <div className="rdg-hero-glow" />
      </div>

      <div className="container rdg-hero-inner">
        <div className="rdg-hero-eyebrow reveal">
          <span className="rdg-pulse" />
          <span>{t.hero.eyebrow}</span>
        </div>

        <h1 className="h-display rdg-hero-title reveal">
          <span>{t.hero.title[0]}</span><br />
          <span className="rdg-hero-accent">{t.hero.title[1]}</span>
        </h1>

        <p className="lead rdg-hero-sub reveal">{t.hero.subtitle}</p>

        <div className="rdg-hero-ctas reveal">
          <a href="#services" className="btn btn-primary">
            {t.hero.ctaPrimary} <ArrowIcon />
          </a>
          <a href="#contact" className="btn btn-ghost">{t.hero.ctaSecondary}</a>
        </div>

        <div className="rdg-hero-stats reveal-stagger">
          <Stat n="9" l={t.hero.stat1} />
          <Stat n="99.97%" l={t.hero.stat2} />
          <Stat n="14" l={t.hero.stat3} />
        </div>
      </div>

      <div className="rdg-hero-marquee" aria-hidden="true">
        <div className="rdg-marquee-track">
          {[...Array(2)].map((_, i) => (
            <div key={i} className="rdg-marquee-row">
              {t.services.list.map(s => (
                <span key={s.id + i} className="rdg-marquee-item">
                  <span className="rdg-marquee-dot" />
                  {s.name}
                  <span className="rdg-marquee-tag">{s.tag}</span>
                </span>
              ))}
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function Stat({ n, l }) {
  return (
    <div className="rdg-stat">
      <div className="rdg-stat-n">{n}</div>
      <div className="rdg-stat-l">{l}</div>
    </div>
  );
}

// ---------- HERO CANVAS (interactive cursor animation) ----------
function HeroCanvas() {
  const canvasRef = useRef(null);

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    let w = 0, h = 0, dpr = Math.min(window.devicePixelRatio || 1, 2);
    let raf;
    let mouse = { x: -9999, y: -9999, active: false };
    let nodes = [];

    const getColors = () => {
      const isDark = document.documentElement.getAttribute('data-theme') === 'dark';
      return {
        node: isDark ? 'rgba(135, 212, 211, 0.45)' : 'rgba(42, 142, 142, 0.55)',
        nodeStrong: isDark ? 'rgba(135, 212, 211, 0.95)' : 'rgba(31, 110, 110, 0.95)',
        line: isDark ? 'rgba(88, 192, 191, ' : 'rgba(42, 142, 142, ',
        cursor: isDark ? 'rgba(135, 212, 211, ' : 'rgba(42, 142, 142, ',
      };
    };

    const setup = () => {
      const rect = canvas.parentElement.getBoundingClientRect();
      w = rect.width;
      h = rect.height;
      canvas.width = w * dpr;
      canvas.height = h * dpr;
      canvas.style.width = w + 'px';
      canvas.style.height = h + 'px';
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);

      // Build node grid
      const spacing = 56;
      const cols = Math.ceil(w / spacing) + 1;
      const rows = Math.ceil(h / spacing) + 1;
      nodes = [];
      for (let i = 0; i < cols; i++) {
        for (let j = 0; j < rows; j++) {
          const ox = i * spacing;
          const oy = j * spacing;
          nodes.push({
            ox, oy,
            x: ox, y: oy,
            vx: 0, vy: 0,
            // tiny random drift seed
            seed: Math.random() * Math.PI * 2,
          });
        }
      }
    };

    const onMove = (e) => {
      const rect = canvas.getBoundingClientRect();
      mouse.x = e.clientX - rect.left;
      mouse.y = e.clientY - rect.top;
      mouse.active = true;
    };
    const onLeave = () => { mouse.active = false; mouse.x = -9999; mouse.y = -9999; };

    const tick = (time) => {
      const c = getColors();
      ctx.clearRect(0, 0, w, h);

      const t = time * 0.0006;
      const radius = 180;
      const radius2 = radius * radius;

      // Update nodes
      for (const n of nodes) {
        // gentle ambient drift
        const drift = 0.6;
        const dx0 = Math.cos(t + n.seed) * drift;
        const dy0 = Math.sin(t * 1.1 + n.seed) * drift;

        const tx = n.ox + dx0;
        const ty = n.oy + dy0;

        // mouse repulsion / attraction
        let mx = 0, my = 0;
        if (mouse.active) {
          const ddx = n.x - mouse.x;
          const ddy = n.y - mouse.y;
          const d2 = ddx * ddx + ddy * ddy;
          if (d2 < radius2 && d2 > 0.5) {
            const d = Math.sqrt(d2);
            const force = (1 - d / radius) * 28;
            mx = (ddx / d) * force;
            my = (ddy / d) * force;
          }
        }

        // spring back to target with displacement
        const targetX = tx + mx;
        const targetY = ty + my;
        n.vx += (targetX - n.x) * 0.08;
        n.vy += (targetY - n.y) * 0.08;
        n.vx *= 0.78;
        n.vy *= 0.78;
        n.x += n.vx;
        n.y += n.vy;
      }

      // Draw connections (only nearby, only if mouse near)
      if (mouse.active) {
        for (const n of nodes) {
          const ddx = n.x - mouse.x;
          const ddy = n.y - mouse.y;
          const d2 = ddx * ddx + ddy * ddy;
          if (d2 < radius2) {
            const a = (1 - Math.sqrt(d2) / radius) * 0.55;
            ctx.strokeStyle = c.line + a + ')';
            ctx.lineWidth = 1;
            ctx.beginPath();
            ctx.moveTo(mouse.x, mouse.y);
            ctx.lineTo(n.x, n.y);
            ctx.stroke();
          }
        }

        // cursor halo
        const halo = ctx.createRadialGradient(mouse.x, mouse.y, 0, mouse.x, mouse.y, radius);
        halo.addColorStop(0, c.cursor + '0.18)');
        halo.addColorStop(1, c.cursor + '0)');
        ctx.fillStyle = halo;
        ctx.beginPath();
        ctx.arc(mouse.x, mouse.y, radius, 0, Math.PI * 2);
        ctx.fill();
      }

      // Draw nodes
      for (const n of nodes) {
        let isNear = false;
        let scale = 1;
        if (mouse.active) {
          const ddx = n.x - mouse.x;
          const ddy = n.y - mouse.y;
          const d2 = ddx * ddx + ddy * ddy;
          if (d2 < radius2) {
            isNear = true;
            scale = 1 + (1 - Math.sqrt(d2) / radius) * 2.2;
          }
        }
        ctx.fillStyle = isNear ? c.nodeStrong : c.node;
        ctx.beginPath();
        ctx.arc(n.x, n.y, 1.2 * scale, 0, Math.PI * 2);
        ctx.fill();
      }

      raf = requestAnimationFrame(tick);
    };

    setup();
    raf = requestAnimationFrame(tick);

    const ro = new ResizeObserver(setup);
    ro.observe(canvas.parentElement);

    window.addEventListener('mousemove', onMove);
    window.addEventListener('mouseleave', onLeave);

    // Touch support
    const onTouch = (e) => {
      if (e.touches && e.touches[0]) {
        onMove({ clientX: e.touches[0].clientX, clientY: e.touches[0].clientY });
      }
    };
    window.addEventListener('touchmove', onTouch, { passive: true });
    window.addEventListener('touchend', onLeave);

    return () => {
      cancelAnimationFrame(raf);
      ro.disconnect();
      window.removeEventListener('mousemove', onMove);
      window.removeEventListener('mouseleave', onLeave);
      window.removeEventListener('touchmove', onTouch);
      window.removeEventListener('touchend', onLeave);
    };
  }, []);

  return <canvas ref={canvasRef} className="rdg-hero-canvas" />;
}

// ---------- FOOTER ----------
function Footer({ t }) {
  return (
    <footer className="rdg-footer">
      <div className="container">
        <div className="rdg-footer-top">
          <div className="rdg-footer-brand">
            <a href="#top" className="rdg-brand" aria-label="RDG Tecnology">
              <RdgMark />
              <span className="rdg-brand-text">
                <span className="rdg-brand-name">RDG</span>
                <span className="rdg-brand-sub">Tecnology</span>
              </span>
            </a>
            <p className="rdg-footer-tag">{t.footer.tagline}</p>
            <div className="rdg-footer-contact">
              <a href={`mailto:${t.contact.info.email}`}>{t.contact.info.email}</a>
              <span>{t.contact.info.address}</span>
            </div>
          </div>

          <div className="rdg-footer-cols">
            <div>
              <h4 className="rdg-footer-h">{t.footer.products}</h4>
              <ul>
                {t.services.list.slice(0, 5).map(s => (
                  <li key={s.id}><a href={`https://${s.domain}`} target="_blank" rel="noopener">{s.name}</a></li>
                ))}
              </ul>
            </div>
            <div>
              <h4 className="rdg-footer-h">&nbsp;</h4>
              <ul>
                {t.services.list.slice(5).map(s => (
                  <li key={s.id}><a href={`https://${s.domain}`} target="_blank" rel="noopener">{s.name}</a></li>
                ))}
              </ul>
            </div>
            <div>
              <h4 className="rdg-footer-h">{t.footer.company}</h4>
              <ul>
                <li><a href="#about">{t.footer.links.about}</a></li>
                <li><a href="#cases">{t.footer.links.cases}</a></li>
                <li><a href="#">{t.footer.links.careers}</a></li>
                <li><a href="#">{t.footer.links.blog}</a></li>
              </ul>
            </div>
            <div>
              <h4 className="rdg-footer-h">{t.footer.legal}</h4>
              <ul>
                <li><a href="#">{t.footer.links.privacy}</a></li>
                <li><a href="#">{t.footer.links.terms}</a></li>
                <li><a href="#">{t.footer.links.security}</a></li>
                <li><a href="#">{t.footer.links.sla}</a></li>
              </ul>
            </div>
          </div>
        </div>

        <div className="rdg-footer-bottom">
          <span>{t.footer.copy}</span>
          <span className="rdg-status">
            <span className="rdg-pulse" /> All systems operational
          </span>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { Nav, Hero, Footer, RdgMark, ArrowIcon, SunIcon, MoonIcon });
