// components.jsx — TecnoWolf landing components
const { useState, useEffect, useRef } = React;

/* ============================================================
   Nav
   ============================================================ */
function Nav({ t, lang, setLang, theme, setTheme }) {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  const [active, setActive] = useState('top');
  const [progress, setProgress] = useState(0);

  useEffect(() => {
    const on = () => {
      const y = window.scrollY;
      setScrolled(y > 24);
      const max = document.documentElement.scrollHeight - window.innerHeight;
      setProgress(max > 0 ? y / max : 0);
    };
    on();
    window.addEventListener('scroll', on, { passive: true });
    return () => window.removeEventListener('scroll', on);
  }, []);

  useEffect(() => {
    const ids = ['about','tech','process','contact'];
    const obs = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting) setActive(e.target.id);
      });
    }, { rootMargin: '-40% 0px -55% 0px', threshold: 0 });
    ids.forEach(id => { const el = document.getElementById(id); if (el) obs.observe(el); });
    return () => obs.disconnect();
  }, []);

  const links = [
    { id: 'about', label: t.nav.about },
    { id: 'tech', label: t.nav.tech },
    { id: 'process', label: t.nav.process },
    { id: 'contact', label: t.nav.contact },
  ];
  const go = (e, id) => {
    e.preventDefault();
    setOpen(false);
    const el = document.getElementById(id);
    if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
  };
  return (
    <nav className={"nav " + (scrolled ? 'is-scrolled' : '')}>
      <a href="#top" className="brand" onClick={(e)=>go(e,'top')}>
        <img src="assets/img/logo/logo%20sin%20fondo.png" alt="TecnoWolf" className="brand-logo-img" />
        <span className="brand-name">TECNO<span className="brand-accent">WOLF</span><span className="brand-code"> &lt;/&gt;</span></span>
      </a>
      <div className={"nav-links " + (open ? 'is-open' : '')}>
        {links.map(l => (
          <a key={l.id} href={"#"+l.id} onClick={(e)=>go(e,l.id)}
             className={active === l.id ? 'is-active' : ''}>
            {l.label}
          </a>
        ))}
      </div>
      <div className="nav-actions">
        <button className="lang-btn" onClick={()=>setLang(lang==='es'?'en':'es')} aria-label="Language">
          <span className={lang==='es'?'active':''}>ES</span>
          <span style={{opacity:0.3}}>/</span>
          <span className={lang==='en'?'active':''}>EN</span>
        </button>
        <button className="icon-btn" onClick={()=>setTheme(theme==='dark'?'light':'dark')} aria-label="Theme">
          {theme === 'dark' ? <Icon.Sun /> : <Icon.Moon />}
        </button>
        <a href="#contact" onClick={(e)=>go(e,'contact')} className="cta-pill">
          {t.nav.cta} <Icon.Arrow style={{width:14,height:14}}/>
        </a>
        <button className="icon-btn menu-btn" onClick={()=>setOpen(!open)} aria-label="Menu">
          <Icon.Menu />
        </button>
      </div>
      <div className="nav-progress" style={{['--p']: progress.toFixed(3)}} />
    </nav>
  );
}

/* ============================================================
   CountUp — animates a number into view
   ============================================================ */
function CountUp({ value }) {
  const ref = useRef(null);
  const [text, setText] = useState(value);

  useEffect(() => {
    // Parse a "+50" / "8 yrs" / "24/7" pattern. We animate only if a single
    // integer-like number is present; otherwise just render as-is.
    const m = String(value).match(/^(\D*)(\d+)(.*)$/);
    if (!m) { setText(value); return; }
    const prefix = m[1];
    const num = parseInt(m[2], 10);
    const suffix = m[3];

    let started = false;
    const obs = new IntersectionObserver((entries) => {
      if (started) return;
      if (entries[0].isIntersecting) {
        started = true;
        const dur = 1400;
        const t0 = performance.now();
        const step = (t) => {
          const k = Math.min(1, (t - t0) / dur);
          const eased = 1 - Math.pow(1 - k, 3);
          const cur = Math.round(num * eased);
          setText(prefix + cur + suffix);
          if (k < 1) requestAnimationFrame(step);
        };
        requestAnimationFrame(step);
      }
    }, { threshold: 0.4 });
    if (ref.current) obs.observe(ref.current);
    return () => obs.disconnect();
  }, [value]);

  return <span ref={ref} className="stat-num is-counting">{text}</span>;
}

/* ============================================================
   Hero
   ============================================================ */
function Hero({ t }) {
  const visualRef = useRef(null);
  const ringsRef = useRef(null);
  const frameRef = useRef(null);
  const cornersRef = useRef(null);

  // Mouse parallax — translates HUD layers based on pointer position
  useEffect(() => {
    const wrap = visualRef.current;
    if (!wrap) return;
    let raf = 0;
    let tx = 0, ty = 0, cx = 0, cy = 0;

    const onMove = (e) => {
      const rect = wrap.getBoundingClientRect();
      const px = (e.clientX - rect.left - rect.width / 2) / rect.width;
      const py = (e.clientY - rect.top - rect.height / 2) / rect.height;
      tx = Math.max(-1, Math.min(1, px * 2));
      ty = Math.max(-1, Math.min(1, py * 2));
    };
    const onLeave = () => { tx = 0; ty = 0; };

    const loop = () => {
      cx += (tx - cx) * 0.08;
      cy += (ty - cy) * 0.08;
      if (ringsRef.current)
        ringsRef.current.style.transform =
          `translate3d(${cx * 14}px, ${cy * 14}px, 0) rotateY(${cx * 6}deg) rotateX(${-cy * 6}deg)`;
      if (frameRef.current)
        frameRef.current.style.transform = `translate3d(${cx * 6}px, ${cy * 6}px, 0)`;
      if (cornersRef.current)
        cornersRef.current.style.transform = `translate3d(${cx * 8}px, ${cy * 8}px, 0)`;
      raf = requestAnimationFrame(loop);
    };

    window.addEventListener('mousemove', onMove);
    window.addEventListener('mouseleave', onLeave);
    raf = requestAnimationFrame(loop);
    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener('mousemove', onMove);
      window.removeEventListener('mouseleave', onLeave);
    };
  }, []);

  return (
    <section className="hero" id="top">
      <div className="container">
        <div className="hero-inner">
          <div className="hero-text">
            <span className="eyebrow">{t.hero.eyebrow}</span>
            <h1>
              {t.hero.h1_a} <span className="italic grad">{t.hero.h1_b}</span> <span className="grad">{t.hero.h1_c}</span>
            </h1>
            <p className="lead">{t.hero.lead}</p>
            <div className="hero-cta">
              <a href="#contact" className="btn btn-primary" onClick={(e)=>{e.preventDefault();document.getElementById('contact')?.scrollIntoView({behavior:'smooth'});}}>
                {t.hero.cta_primary} <Icon.Arrow style={{width:16,height:16}}/>
              </a>
              <a href="#process" className="btn btn-ghost" onClick={(e)=>{e.preventDefault();document.getElementById('process')?.scrollIntoView({behavior:'smooth'});}}>
                <Icon.Play style={{width:14,height:14}}/> {t.hero.cta_secondary}
              </a>
            </div>
          </div>
          <div className="hero-visual" ref={visualRef}>
            <div className="hud-frame" ref={frameRef} />
            <div className="hud-corners-2" ref={cornersRef} />
            <div className="hud-data top mono">{t.hero.hud_top}</div>
            <div className="hud-data bot mono">{t.hero.hud_bot}</div>
            <div className="hud-data left mono">{t.hero.hud_left}</div>
            <div className="hud-data right mono">{t.hero.hud_right}</div>
            <div className="hud-rings" ref={ringsRef}>
              <div className="hud-ring r1"><span className="tick"></span></div>
              <div className="hud-ring r2"><span className="tick"></span></div>
              <div className="hud-ring r3"><span className="tick"></span></div>
              <div className="hud-wolf">
                <img src="assets/img/logo/logo%20sin%20fondo.png" alt="TecnoWolf" style={{width:'72%',height:'72%',objectFit:'contain',filter:'drop-shadow(0 0 16px var(--a1)) drop-shadow(0 0 32px var(--a1-glow))'}} />
              </div>
            </div>
          </div>
        </div>
        <div className="stats-strip">
          {[1,2,3,4].map(i => (
            <div className="stat" key={i}>
              <CountUp value={t.hero[`stat_${i}_n`]} />
              <div className="stat-lbl">{t.hero[`stat_${i}_l`]}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ============================================================
   About
   ============================================================ */
function About({ t }) {
  const vIcons = [Icon.Shield, Icon.Heart, Icon.Bolt];
  return (
    <section id="about">
      <div className="container">
        <div className="about-grid">
          <div className="about-image reveal">
            <img src="assets/img/logo/logo%20sin%20fondo.png" alt="TecnoWolf" loading="lazy" className="about-logo-img" />
            <div className="img-corner mono">{t.about.img_corner}</div>
          </div>
          <div className="about-content reveal">
            <span className="eyebrow">{t.about.eyebrow}</span>
            <h2 style={{marginTop:16}}>
              {t.about.h2_a} <span className="grad">{t.about.h2_b}</span>
            </h2>
            <p>{t.about.p1}</p>
            <p>{t.about.p2}</p>
            <ul className="values-list">
              {[1,2,3].map(i => {
                const Vi = vIcons[i-1];
                return (
                  <li key={i}>
                    <span className="vicon"><Vi /></span>
                    <div>
                      <b>{t.about[`val_${i}_t`]}</b>
                      <span>{t.about[`val_${i}_d`]}</span>
                    </div>
                  </li>
                );
              })}
            </ul>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============================================================
   Tech
   ============================================================ */
function TechCard({ card, Ci, i }) {
  const ref = useRef(null);
  const onMove = (e) => {
    const el = ref.current;
    if (!el) return;
    const r = el.getBoundingClientRect();
    const px = (e.clientX - r.left) / r.width - 0.5;
    const py = (e.clientY - r.top) / r.height - 0.5;
    el.style.transform = `translateY(-4px) rotateX(${-py * 8}deg) rotateY(${px * 8}deg)`;
  };
  const reset = () => {
    if (ref.current) ref.current.style.transform = '';
  };
  return (
    <div className="tech-card reveal" ref={ref}
         onMouseMove={onMove} onMouseLeave={reset}
         style={{transitionDelay: `${i*60}ms`}}>
      <div className="logo"><Ci /></div>
      <h4>{card.t}</h4>
      <div className="tags">
        {card.tags.map((tag, ti) => <button className="tag-btn" key={tag} type="button" style={{animationDelay:`${ti*0.4}s`}}>{tag}</button>)}
      </div>
    </div>
  );
}

function Tech({ t }) {
  const cardIcons = [Icon.Browser, Icon.Server, Icon.Mobile, Icon.Cloud, Icon.Brain, Icon.Cart, Icon.Doc, Icon.Shield];
  const marqueeWords = ['React','Next.js','Node.js','TypeScript','Python','AWS','Docker','Flutter','PostgreSQL','GraphQL','Kubernetes','OpenAI','Stripe','Figma'];
  const double = [...marqueeWords, ...marqueeWords];
  return (
    <section id="tech">
      <div className="container">
        <div className="section-head reveal">
          <span className="eyebrow">{t.tech.eyebrow}</span>
          <h2>{t.tech.h2_a} <span className="grad">{t.tech.h2_b}</span></h2>
          <p>{t.tech.lead}</p>
        </div>
        <div className="tech-grid">
          {t.tech.cards.map((c, i) => {
            const Ci = cardIcons[i] || Icon.Spark;
            return <TechCard key={i} card={c} Ci={Ci} i={i} />;
          })}
        </div>
        <div className="tech-marquee">
          <div className="tech-marquee-track">
            {double.map((w, i) => (
              <span key={i}><em>◢</em>{w}</span>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============================================================
   Process
   ============================================================ */
function Process({ t }) {
  return (
    <section id="process">
      <div className="container">
        <div className="section-head reveal">
          <span className="eyebrow">{t.process.eyebrow}</span>
          <h2>{t.process.h2_a} <span className="grad">{t.process.h2_b}</span></h2>
          <p>{t.process.lead}</p>
        </div>
        <div className="process-list">
          {t.process.steps.map((s, i) => (
            <div className="process-step reveal" key={i} style={{transitionDelay: `${i*80}ms`}}>
              <div className="step-num">{String(i+1).padStart(2,'0')}</div>
              <div className="step-body">
                <h4>{s.t}</h4>
                <p>{s.d}</p>
              </div>
              <div className="step-time mono">{s.time}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ============================================================
   Contact + CTA Final
   ============================================================ */
function Contact({ t }) {
  const [sent, setSent] = useState(false);
  const cIcons = [Icon.Mail, Icon.Phone, Icon.Pin, Icon.Clock];
  const submit = (e) => {
    e.preventDefault();
    setSent(true);
    setTimeout(()=>setSent(false), 4000);
  };
  return (
    <section id="contact">
      <div className="container">
        <div className="contact-wrap">
          <div className="contact-info reveal">
            <span className="eyebrow">{t.contact.eyebrow}</span>
            <h2 style={{marginTop:16}}>{t.contact.h2_a} <span className="grad">{t.contact.h2_b}</span></h2>
            <p>{t.contact.lead}</p>
            <ul className="contact-list">
              {t.contact.items.map((it, i) => {
                const Ci = cIcons[i];
                return (
                  <li key={i}>
                    <span className="cicon"><Ci /></span>
                    <div>
                      <div className="clbl">{it.l}</div>
                      <div className="cval">{it.v}</div>
                    </div>
                  </li>
                );
              })}
            </ul>
          </div>
          <form className="contact-form reveal" onSubmit={submit}>
            <div className="field">
              <label>{t.contact.form.name}</label>
              <input type="text" required placeholder="Hanns Wolf" />
            </div>
            <div className="field">
              <label>{t.contact.form.email}</label>
              <input type="email" required placeholder="hola@empresa.com" />
            </div>
            <div className="field">
              <label>{t.contact.form.company}</label>
              <input type="text" placeholder="Acme Inc." />
            </div>
            <div className="field">
              <label>{t.contact.form.service}</label>
              <select required defaultValue="">
                <option value="" disabled>—</option>
                {t.contact.form.service_opts.map(o => <option key={o}>{o}</option>)}
              </select>
            </div>
            <div className="field">
              <label>{t.contact.form.message}</label>
              <textarea required placeholder="..."></textarea>
            </div>
            <button type="submit" className="btn btn-primary form-submit">
              {sent ? <><Icon.Check style={{width:16,height:16}}/> {t.contact.form.success}</> : <>{t.contact.form.submit} <Icon.Arrow style={{width:16,height:16}}/></>}
            </button>
          </form>
        </div>
      </div>
    </section>
  );
}

function CTAFinal({ t, waUrl }) {
  return (
    <section id="cta" style={{paddingBottom: 60}}>
      <div className="container">
        <div className="cta-final reveal">
          <span className="eyebrow">{t.cta.eyebrow}</span>
          <h2 style={{marginTop:20}}>{t.cta.h2_a} <span className="grad">{t.cta.h2_b}</span></h2>
          <p>{t.cta.lead}</p>
          <div className="hero-cta">
            <a href="#contact" className="btn btn-primary" onClick={(e)=>{e.preventDefault();document.getElementById('contact')?.scrollIntoView({behavior:'smooth'});}}>
              {t.cta.btn_primary} <Icon.Arrow style={{width:16,height:16}}/>
            </a>
            <a href={waUrl} target="_blank" rel="noopener" className="btn btn-ghost">
              <Icon.Whatsapp style={{width:16,height:16}}/> {t.cta.btn_secondary}
            </a>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============================================================
   Footer
   ============================================================ */
function Footer({ t, updated }) {
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-grid">
          <div className="footer-brand">
            <a href="#top" className="brand" onClick={(e)=>{e.preventDefault();window.scrollTo({top:0,behavior:'smooth'});}}>
              <img src="assets/img/logo/logo%20sin%20fondo.png" alt="TecnoWolf" className="brand-logo-img" />
              <span className="brand-name">TECNO<span className="brand-accent">WOLF</span><span className="brand-code"> &lt;/&gt;</span></span>
            </a>
            <p>{t.footer.tagline}</p>
            <div className="footer-social">
              <a href="#" aria-label="LinkedIn"><Icon.Linkedin /></a>
              <a href="#" aria-label="Instagram"><Icon.Instagram /></a>
              <a href="#" aria-label="GitHub"><Icon.GitHub /></a>
            </div>
          </div>
          <div className="footer-col">
            <h5>{t.footer.col_company}</h5>
            <ul>{t.footer.links_company.map(x => <li key={x}><a href="#">{x}</a></li>)}</ul>
          </div>
          <div className="footer-col">
            <h5>{t.footer.col_services}</h5>
            <ul>{t.footer.links_services.map(x => <li key={x}><a href="#">{x}</a></li>)}</ul>
          </div>
          <div className="footer-col">
            <h5>{t.footer.col_legal}</h5>
            <ul>{t.footer.links_legal.map(x => <li key={x}><a href="#">{x}</a></li>)}</ul>
          </div>
        </div>
        <div className="footer-bottom">
          <span>{t.footer.rights}</span>
          <span>{t.footer.developed}</span>
        </div>
      </div>
    </footer>
  );
}

/* ============================================================
   Floating WhatsApp
   ============================================================ */
function FloatingWA({ t, url }) {
  return (
    <a href={url} target="_blank" rel="noopener" className="fab-wa" aria-label="WhatsApp">
      <Icon.Whatsapp />
      <span className="fab-wa-tooltip">{t.wa_tooltip}</span>
    </a>
  );
}

/* ============================================================
   Portfolio — GIF showcase grid
   ============================================================ */
const PORTFOLIO_PROJECTS = [
  {
    img:   'assets/img/empresas/Infinity.png',
    label: 'Infinity FQP',
    desc:  'Plataforma corporativa',
    url:   'https://www.infinityfqp.com.co/',
  },
  {
    img:   'assets/img/empresas/Polla.png',
    label: 'Polla Mundialista',
    desc:  'E-commerce & apuestas deportivas',
    url:   'https://pollamundialista.com.co/',
  },
  {
    img:   'assets/img/empresas/pollab2b.png',
    label: 'Polla B2B',
    desc:  'Landing page B2B',
    url:   'https://www.pollamundialistab2b.com.co/',
  },
  {
    img:   'assets/img/empresas/innovacion.png',
    label: 'Innovación Emtelco',
    desc:  'Landing de innovación',
    url:   'https://www.innovacionemtelco.digital/',
  },
];

function Portfolio({ t }) {
  return (
    <section id="portfolio">
      <div className="container">
        <div className="section-head reveal">
          <span className="eyebrow">{t.portfolio.eyebrow}</span>
          <h2>{t.portfolio.h2_a} <span className="grad">{t.portfolio.h2_b}</span></h2>
          <p>{t.portfolio.lead}</p>
        </div>
        <div className="portfolio-grid">
          {PORTFOLIO_PROJECTS.map((item, i) => (
            <a
              href={item.url}
              target="_blank"
              rel="noopener noreferrer"
              className="portfolio-card reveal"
              key={i}
              style={{ transitionDelay: `${i * 80}ms` }}
            >
              <img src={item.img} alt={item.label} loading="lazy" />
              <div className="portfolio-card-overlay">
                <div>
                  <span className="portfolio-card-title">{item.label}</span>
                  <span className="portfolio-card-desc">{item.desc}</span>
                </div>
                <Icon.Arrow style={{width:16,height:16,color:'var(--a1)',flexShrink:0}} />
              </div>
            </a>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ============================================================
   Scroll reveal hook
   ============================================================ */
function useScrollReveal() {
  useEffect(() => {
    const obs = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting) {
          e.target.classList.add('in');
          obs.unobserve(e.target);
        }
      });
    }, { threshold: 0.12 });
    document.querySelectorAll('.reveal').forEach(el => obs.observe(el));
    return () => obs.disconnect();
  });
}

/* ============================================================
   Background layer
   ============================================================ */
function BgLayer() {
  return (
    <>
      <Starfield />
      <div className="bg-layer">
        <div className="bg-grid" />
        <div className="bg-orb bg-orb-1" />
        <div className="bg-orb bg-orb-2" />
        <div className="bg-orb bg-orb-3" />
        <div className="bg-scanline" />
      </div>
    </>
  );
}

// Export to window so other Babel scripts can find them
Object.assign(window, {
  Nav, Hero, About, Tech, Process, Portfolio, Contact, CTAFinal, Footer, FloatingWA, BgLayer, useScrollReveal
});
