// GuerrerosCR — Sections: Hero, Problem, Services
const { useState, useEffect, useRef } = React;

// === Inline SVG icons (original, simple geometric)
const Icon = ({ name, size = 20 }) => {
  const s = size;
  const stroke = { stroke: "currentColor", strokeWidth: 1.7, strokeLinecap: "round", strokeLinejoin: "round", fill: "none" };
  switch (name) {
    case "app":
      return (<svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><rect x="3" y="4" width="18" height="16" rx="2"/><path d="M3 9h18M7 6.5h.01M10 6.5h.01"/></svg>);
    case "bolt":
      return (<svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><path d="M13 3L5 14h6l-1 7 8-11h-6l1-7z"/></svg>);
    case "link":
      return (<svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><path d="M10 14a5 5 0 0 0 7 0l3-3a5 5 0 0 0-7-7l-1 1"/><path d="M14 10a5 5 0 0 0-7 0l-3 3a5 5 0 0 0 7 7l1-1"/></svg>);
    case "globe":
      return (<svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3a13 13 0 0 1 0 18M12 3a13 13 0 0 0 0 18"/></svg>);
    case "chart":
      return (<svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><path d="M3 3v18h18"/><path d="M7 14l4-4 3 3 5-6"/></svg>);
    case "shield":
      return (<svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><path d="M12 3l8 3v6c0 5-3.5 8-8 9-4.5-1-8-4-8-9V6l8-3z"/><path d="M9 12l2 2 4-4"/></svg>);
    case "wa":
      return (<svg width={s} height={s} viewBox="0 0 24 24" fill="currentColor"><path d="M17.5 14.4c-.3-.2-1.8-.9-2-1-.3-.1-.5-.1-.7.1l-1 1.1c-.2.2-.4.2-.6.1-.8-.4-1.8-1-2.6-2-.2-.3-.2-.5.1-.7.1-.1.5-.5.7-.8.1-.2.1-.4 0-.6-.1-.2-.7-1.6-1-2.2-.2-.5-.4-.4-.6-.4h-.6c-.2 0-.5.1-.8.4-.3.3-1 1-1 2.5s1.1 2.9 1.2 3.1c.1.2 2.1 3.2 5.1 4.3.7.3 1.3.5 1.7.6.7.2 1.4.2 1.9.1.6-.1 1.8-.7 2-1.4.3-.7.3-1.3.2-1.4-.1-.1-.3-.2-.6-.3zM12 2C6.5 2 2 6.5 2 12c0 1.8.5 3.5 1.3 5L2 22l5.1-1.3c1.4.8 3.1 1.3 4.9 1.3 5.5 0 10-4.5 10-10S17.5 2 12 2z"/></svg>);
    case "arrow":
      return (<svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><path d="M5 12h14M13 5l7 7-7 7"/></svg>);
    case "check":
      return (<svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><path d="M4 12l5 5L20 6"/></svg>);
    case "lightning":
      return (<svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><path d="M13 2L4 14h7l-1 8 9-12h-7l1-8z"/></svg>);
    case "users":
      return (<svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><circle cx="9" cy="8" r="3"/><path d="M3 20c0-3 3-5 6-5s6 2 6 5"/><circle cx="17" cy="7" r="2.5"/><path d="M16 14c3 0 5 2 5 5"/></svg>);
    case "db":
      return (<svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><ellipse cx="12" cy="5" rx="8" ry="2.5"/><path d="M4 5v6c0 1.4 3.6 2.5 8 2.5s8-1.1 8-2.5V5"/><path d="M4 11v6c0 1.4 3.6 2.5 8 2.5s8-1.1 8-2.5v-6"/></svg>);
    case "send":
      return (<svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><path d="M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"/></svg>);
    case "mail":
      return (<svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3 7l9 6 9-6"/></svg>);
    case "pin":
      return (<svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><path d="M12 21s-7-6-7-12a7 7 0 1 1 14 0c0 6-7 12-7 12z"/><circle cx="12" cy="9" r="2.5"/></svg>);
    case "phone":
      return (<svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><path d="M22 16.9v3a2 2 0 0 1-2.2 2 19.8 19.8 0 0 1-8.6-3.1 19.5 19.5 0 0 1-6-6A19.8 19.8 0 0 1 2.1 4.2 2 2 0 0 1 4.1 2h3a2 2 0 0 1 2 1.7c.1 1 .3 1.9.6 2.8a2 2 0 0 1-.5 2.1L8 9.8a16 16 0 0 0 6 6l1.3-1.3a2 2 0 0 1 2.1-.5c.9.3 1.8.5 2.8.6a2 2 0 0 1 1.7 2z"/></svg>);
    case "sun":
      return (<svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"/></svg>);
    case "moon":
      return (<svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 1 0 9.8 9.8z"/></svg>);
    default: return null;
  }
};
window.Icon = Icon;

// === Nav ===
function Nav({ onContact }) {
  const isEn = window.location.pathname.startsWith("/en");
  const base = isEn ? "/en" : "";
  const [active, setActive] = useState("inicio");
  const [isDark, setIsDark] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);
  const [langIsEn, setLangIsEn] = useState(isEn);
  const sections = ["inicio", "servicios", "proyectos", "nosotros", "blog", "contacto"];

  useEffect(() => {
    const theme = document.documentElement.getAttribute("data-theme");
    setIsDark(theme === "dark");
    setLangIsEn(window.location.pathname.startsWith("/en"));
  }, []);

  useEffect(() => {
    const onScroll = () => {
      let cur = "inicio";
      for (const id of sections) {
        const el = document.getElementById(id);
        if (el && el.getBoundingClientRect().top < 120) cur = id;
      }
      setActive(cur);
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const go = (id) => (e) => {
    e.preventDefault();
    const el = document.getElementById(id);
    if (el) {
      const top = el.getBoundingClientRect().top + window.scrollY - 70;
      window.scrollTo({ top, behavior: "smooth" });
    }
    setMenuOpen(false);
  };

  const toggleTheme = () => {
    const nextDark = !isDark;
    document.documentElement.setAttribute("data-theme", nextDark ? "dark" : "light");
    try {
      localStorage.setItem("gc_theme", nextDark ? "dark" : "light");
    } catch (e) {}
    setIsDark(nextDark);
  };

  const links = [
    { id: "inicio", label: isEn ? "Home" : "Inicio", href: `${base}/#inicio`, type: "section" },
    { id: "servicios", label: isEn ? "Services" : "Servicios", href: `${base}/#servicios`, type: "section" },
    { id: "proyectos", label: isEn ? "Projects" : "Proyectos", href: `${base}/#proyectos`, type: "section" },
    { id: "nosotros", label: isEn ? "About" : "Nosotros", href: `${base}/#nosotros`, type: "section" },
    { id: "blog", label: "Blog", href: `${base}/blog`, type: "page" },
    { id: "contacto", label: isEn ? "Contact" : "Contacto", href: `${base}/contacto`, type: "page" },
  ];

  return (
    <nav className="nav">
      <div className="nav-inner">
        <a href={`${base}/#inicio`} onClick={go("inicio")} className="brand">
          <img className="brand-logo" src="/logoGuerreros-transparent.png" alt="GuerrerosCR" />
        </a>

        <div className={`nav-links ${menuOpen ? "open" : ""}`} id="nav-links">
          {links.map((link) => (
            <a
              key={link.id}
              href={link.href}
              onClick={link.type === "section" ? go(link.id) : () => setMenuOpen(false)}
              className={`nav-link ${link.type === "section" && active === link.id ? "active" : ""}`}
            >
              {link.label}
            </a>
          ))}
          <a href={`${base}/contacto`} className="btn btn-primary nav-link-mobile-cta" onClick={() => setMenuOpen(false)}>
            {isEn ? "Get a quote" : "Solicitar consulta"}
          </a>
        </div>

        <div className="nav-cta">
          <button
            type="button"
            className="btn btn-ghost theme-toggle"
            onClick={toggleTheme}
            aria-label={isDark ? (isEn ? "Switch to light mode" : "Cambiar a modo claro") : (isEn ? "Switch to dark mode" : "Cambiar a modo oscuro")}
            title={isDark ? (isEn ? "Light mode" : "Modo claro") : (isEn ? "Dark mode" : "Modo oscuro")}
          >
            <Icon name={isDark ? "sun" : "moon"} size={16} />
            <span>{isDark ? (isEn ? "Light" : "Claro") : (isEn ? "Dark" : "Oscuro")}</span>
          </button>

          <a href={langIsEn ? "/" : "/en/"} className="btn btn-ghost lang-toggle" aria-label="Switch language">
            {langIsEn ? "ES" : "EN"}
          </a>

          <button
            type="button"
            className="nav-burger"
            id="nav-burger"
            aria-label={menuOpen ? (isEn ? "Close menu" : "Cerrar menu") : (isEn ? "Open menu" : "Abrir menu")}
            aria-expanded={menuOpen}
            aria-controls="nav-links"
            onClick={() => setMenuOpen(!menuOpen)}
          >
            <span></span>
            <span></span>
            <span></span>
          </button>

          <a href={`${base}/contacto`} className="btn btn-primary nav-desktop-cta">
            {isEn ? "Get a quote" : "Solicitar consulta"} <Icon name="arrow" size={14} />
          </a>
        </div>
      </div>
    </nav>
  );
}
window.Nav = Nav;

// === Hero ===
function Hero() {
  const isEn = window.location.pathname.startsWith("/en");
  const base = isEn ? "/en" : "";
  const go = (id) => (e) => {
    e.preventDefault();
    const el = document.getElementById(id);
    if (el) {
      const top = el.getBoundingClientRect().top + window.scrollY - 70;
      window.scrollTo({ top, behavior: "smooth" });
    }
  };
  return (
    <section id="inicio" className="hero">
      <div className="grid-bg" />
      <div className="hero-inner">
        <div>
          <span className="eyebrow"><span className="dot"></span>{isEn ? "Digital solutions for businesses — Costa Rica" : "Soluciones digitales para empresas — Costa Rica"}</span>
          <h1 style={{ marginTop: 20 }}>
            {isEn ? <>Technology for companies that want to grow with <span className="accent">order</span>, <span className="accent">automation</span>, and <span className="accent2">control</span>.</> : <>Tecnología para empresas que quieren crecer con <span className="accent">orden</span>, <span className="accent">automatización</span> y <span className="accent2">control</span>.</>}
          </h1>
          <p className="hero-lead">
            {isEn ? "We build web applications, automations, ERP integrations, and professional websites so your company can reduce manual work, centralize information, and make better decisions." : "Desarrollamos aplicaciones web, automatizaciones, integraciones con ERP y sitios profesionales para que su empresa reduzca trabajo manual, centralice información y tome mejores decisiones."}
          </p>
          <div className="hero-ctas">
            <a href={`${base}/#contacto`} onClick={go("contacto")} className="btn btn-primary btn-lg">
              {isEn ? "Get a quote" : "Solicitar consulta"} <Icon name="arrow" size={14} />
            </a>
            <a href={`${base}/#servicios`} onClick={go("servicios")} className="btn btn-ghost btn-lg">
              {isEn ? "View services" : "Ver servicios"}
            </a>
          </div>
          <div className="hero-meta">
            <div><b>+10</b>{isEn ? "Years of IT experience" : "Años de experiencia en TI"}</div>
            <div><b>ERP · SQL · APIs</b>{isEn ? "Enterprise systems" : "Sistemas empresariales"}</div>
            <div><b>CR</b>{isEn ? "Local team · direct support" : "Equipo local · soporte directo"}</div>
          </div>
        </div>
        <div className="hero-mock">
          <div className="float-chip tl">
            <span className="ico"><Icon name="check" size={14} /></span>
            <span>{isEn ? "Approval sent" : "Aprobación enviada"} · <b style={{color:'var(--ink)'}}>2.3s</b></span>
          </div>
          <div className="float-chip br">
            <span className="ico"><Icon name="lightning" size={14} /></span>
            <span>{isEn ? "−68% manual time" : "−68% tiempo manual"}</span>
          </div>
          <div className="mock-bar">
            <span></span><span></span><span></span>
            <div className="mock-tabs">
              <span className="mock-tab active">{isEn ? "Operations" : "Operación"}</span>
              <span className="mock-tab">{isEn ? "Approvals" : "Aprobaciones"}</span>
              <span className="mock-tab">{isEn ? "Reports" : "Reportes"}</span>
            </div>
          </div>
          <div className="mock-grid">
            <div className="mock-kpi">
              <div className="mock-kpi-label">{isEn ? "Requests / month" : "Solicitudes / mes"}</div>
              <div className="mock-kpi-val">1,284</div>
              <div className="mock-kpi-delta">↑ 23%</div>
            </div>
            <div className="mock-kpi">
              <div className="mock-kpi-label">{isEn ? "Approval time" : "Tiempo aprobación"}</div>
              <div className="mock-kpi-val">4h 12m</div>
              <div className="mock-kpi-delta">↓ 68%</div>
            </div>
            <div className="mock-chart">
              <div className="mock-chart-title">{isEn ? "Requests by department " : "Solicitudes por departamento "}<span>{isEn ? "last 30 days" : "últimos 30 días"}</span></div>
              <svg viewBox="0 0 280 110" preserveAspectRatio="none">
                <defs>
                  <linearGradient id="hgrad" x1="0" y1="0" x2="0" y2="1">
                    <stop offset="0%" stopColor="#2563EB" stopOpacity="0.35"/>
                    <stop offset="100%" stopColor="#2563EB" stopOpacity="0"/>
                  </linearGradient>
                </defs>
                <path d="M0,80 L20,72 L40,76 L60,55 L80,60 L100,40 L120,48 L140,30 L160,42 L180,25 L200,30 L220,18 L240,28 L260,15 L280,22 L280,110 L0,110 Z" fill="url(#hgrad)" />
                <path d="M0,80 L20,72 L40,76 L60,55 L80,60 L100,40 L120,48 L140,30 L160,42 L180,25 L200,30 L220,18 L240,28 L260,15 L280,22" stroke="#2563EB" strokeWidth="2" fill="none" />
                <path d="M0,95 L20,90 L40,92 L60,80 L80,85 L100,70 L120,75 L140,65 L160,72 L180,55 L200,60 L220,48 L240,55 L260,45 L280,50" stroke="#22C55E" strokeWidth="1.5" fill="none" strokeDasharray="3 3" />
              </svg>
            </div>
            <div className="mock-list">
              <div className="mock-row">
                <span className="mock-row-status"></span>
                <span className="mock-row-name">{isEn ? "Reimbursement #4821 · M. Solís" : "Reembolso #4821 · M. Solís"}</span>
                <span className="mock-row-meta">10:42</span>
                <span className="mock-row-pill" style={{color:'var(--accent)', background:'color-mix(in oklab, var(--accent) 14%, transparent)'}}>{isEn ? "Approved" : "Aprobado"}</span>
              </div>
              <div className="mock-row">
                <span className="mock-row-status pending"></span>
                <span className="mock-row-name">{isEn ? "Asset purchase · IT" : "Compra activos · TI"}</span>
                <span className="mock-row-meta">09:58</span>
                <span className="mock-row-pill" style={{color:'var(--warn)', background:'color-mix(in oklab, var(--warn) 14%, transparent)'}}>{isEn ? "Pending" : "Pendiente"}</span>
              </div>
              <div className="mock-row">
                <span className="mock-row-status new"></span>
                <span className="mock-row-name">{isEn ? "SAP support ticket" : "Ticket soporte SAP"}</span>
                <span className="mock-row-meta">09:21</span>
                <span className="mock-row-pill" style={{color:'var(--brand)', background:'color-mix(in oklab, var(--brand) 14%, transparent)'}}>{isEn ? "New" : "Nuevo"}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}
window.Hero = Hero;

// === Marquee (tagline strip) ===
function Marquee() {
  const isEn = window.location.pathname.startsWith("/en");
  const items = [
    ...(isEn
      ? ["Web development", "Automation", "Custom applications", "ERP integrations", "Dashboards", "Technical support", "Databases", "IT consulting", "Web development", "Automation", "Custom applications", "ERP integrations", "Dashboards", "Technical support"]
      : ["Desarrollo web", "Automatización", "Aplicaciones a la medida", "Integraciones ERP", "Dashboards", "Soporte técnico", "Bases de datos", "Consultoría IT", "Desarrollo web", "Automatización", "Aplicaciones a la medida", "Integraciones ERP", "Dashboards", "Soporte técnico"])
  ];
  return (
    <div className="marquee-wrap">
      <div className="marquee">
        {items.map((t, i) => <span key={i}>{t}</span>)}
      </div>
    </div>
  );
}
window.Marquee = Marquee;

// === Problem section ===
function Problem() {
  const isEn = window.location.pathname.startsWith("/en");
  return (
    <section className="problem">
      <div className="section">
        <div className="problem-grid">
          <div>
            <span className="eyebrow"><span className="dot"></span>{isEn ? "The problem" : "El problema"}</span>
            <h2 style={{ marginTop: 20 }}>
              {isEn ? "Manual processes, disconnected systems, and scattered data slow down growth." : "Procesos manuales, sistemas desconectados y datos dispersos atrasan el crecimiento."}
            </h2>
            <p style={{ marginTop: 20, fontSize: 16 }}>
              {isEn ? "When information lives in email, spreadsheets, and disconnected systems, approvals get delayed, reporting takes too long, and teams repeat tasks that should be automated." : "Cuando la información vive en correos, Excel y sistemas separados, las aprobaciones se atrasan, los reportes toman demasiado tiempo y el equipo termina repitiendo tareas que podrían estar automatizadas."}
            </p>
            <p style={{ marginTop: 12, fontSize: 16 }}>
              {isEn ? "At GuerrerosCR, we turn those processes into simple, structured, and efficient digital solutions." : "En GuerrerosCR transformamos esos procesos en soluciones digitales simples, ordenadas y eficientes."}
            </p>
          </div>
          <div className="compare">
            <div className="compare-col before">
              <span className="compare-col-label">{isEn ? "Before" : "Antes"}</span>
              <ul>
                <li>{isEn ? "Email-based approvals" : "Aprobaciones por correo"}</li>
                <li>{isEn ? "Shared Excel with no control" : "Excel compartido sin control"}</li>
                <li>{isEn ? "Manually copied reports" : "Reportes copiados a mano"}</li>
                <li>{isEn ? "Disconnected systems" : "Sistemas que no se hablan"}</li>
                <li>{isEn ? "No traceability or history" : "Sin trazabilidad ni historial"}</li>
              </ul>
            </div>
            <div className="compare-arrow">→</div>
            <div className="compare-col after">
              <span className="compare-col-label">{isEn ? "After" : "Después"}</span>
              <ul>
                <li>{isEn ? "Digital workflow with notifications" : "Flujo digital con notificaciones"}</li>
                <li>{isEn ? "Role-based forms with permissions" : "Formulario con roles y permisos"}</li>
                <li>{isEn ? "Real-time dashboards" : "Dashboards en tiempo real"}</li>
                <li>{isEn ? "ERP / SQL integration" : "Integración con ERP / SQL"}</li>
                <li>{isEn ? "Full audit history" : "Historial y auditoría completa"}</li>
              </ul>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}
window.Problem = Problem;
