/* global React, Wordmark, Icon, WA_URL, PHONE, PHONE_FMT */
const { useState: useStateNav, useEffect: useEffectNav } = React;

/* ===========================================================
   Navigation
   =========================================================== */
function Nav({ onOpenCalendar, onHome = true, active }) {
  const [open, setOpen] = useStateNav(false);
  const [scrolled, setScrolled] = useStateNav(false);

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

  const HOME = 'index.html';
  const base = onHome ? '' : HOME;
  const links = [
    { href: base + '#soluciones', label: 'Soluciones', id: 'soluciones' },
    { href: 'SLF Energia - Sector Publico.html', label: 'Sector Público', id: 'sector-publico' },
    { href: base + '#calculadora', label: 'Calculadora', id: 'calculadora' },
    { href: base + '#casos', label: 'Casos', id: 'casos' },
    { href: 'SLF Energia - Nosotros.html', label: 'Nosotros', id: 'nosotros' },
    { href: base + '#recursos', label: 'Recursos', id: 'recursos' },
    { href: 'SLF Energia - Contacto.html', label: 'Contacto', id: 'contacto' },
  ];

  return (
    <header className="nav" style={scrolled ? { boxShadow: '0 1px 0 rgba(11,37,69,.04), 0 8px 24px -16px rgba(11,37,69,.16)' } : {}}>
      <div className="container nav-inner">
        <a href={onHome ? '#top' : HOME} aria-label="Inicio">
          <Wordmark variant="full" tone="dark" size={20} />
        </a>
        <nav className="nav-links" aria-label="Principal">
          {links.map((l) => (
            <a key={l.href} href={l.href} className={`nav-link ${active === l.id ? 'is-active' : ''}`}>{l.label}</a>
          ))}
        </nav>
        <div className="flex items-center gap-3">
          <a className="btn btn-ghost btn-sm" href={WA_URL} target="_blank" rel="noopener" style={{ display: 'none' }}>
            <Icon.Whatsapp size={16} />
            <span className="hide-sm">WhatsApp</span>
          </a>
          <button className="btn btn-primary btn-sm" onClick={onOpenCalendar} style={{ display: 'inline-flex' }}>
            <span style={{ display: 'inline-block' }}>Agendar diagnóstico</span>
          </button>
          <button
            aria-label="Menú"
            onClick={() => setOpen(!open)}
            style={{
              display: 'none', border: '1px solid var(--line)', borderRadius: 8,
              padding: 8, background: 'transparent', color: 'var(--ink)'
            }}
            className="nav-menu-btn"
          >
            <Icon.Menu />
          </button>
        </div>
      </div>
      {open && (
        <div style={{ borderTop: '1px solid var(--line)', background: '#fff' }}>
          <div className="container" style={{ padding: '12px 24px 16px' }}>
            {links.map((l) => (
              <a key={l.href} href={l.href} className="nav-link" style={{ display: 'block', padding: '12px 0' }} onClick={() => setOpen(false)}>
                {l.label}
              </a>
            ))}
          </div>
        </div>
      )}
      <style>{`
        @media (max-width: 960px) {
          .nav-menu-btn { display: inline-flex !important; }
        }
        @media (max-width: 640px) {
          .nav .btn-primary span { display: none !important; }
          .nav .btn-primary::after { content: 'Agendar'; }
        }
      `}</style>
    </header>
  );
}

/* ===========================================================
   Sticky CTA (appears after hero on desktop)
   =========================================================== */
function StickyCTA({ onOpenCalendar }) {
  const [show, setShow] = useStateNav(false);
  useEffectNav(() => {
    const onScroll = () => setShow(window.scrollY > 900);
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return (
    <div className={`sticky-cta ${show ? 'is-visible' : ''}`} aria-hidden={!show}>
      <div className="container flex items-center justify-between" style={{ gap: 16 }}>
        <div className="flex items-center gap-3" style={{ fontSize: 14 }}>
          <span className="pulse-dot" style={{ background: '#FFB800' }} />
          <span style={{ color: 'rgba(255,255,255,.85)' }}>¿Listo para evaluar tu operación?</span>
          <span style={{ color: 'rgba(255,255,255,.5)' }} className="mono">— diagnóstico técnico sin costo</span>
        </div>
        <div className="flex items-center gap-2">
          <a className="btn btn-onblue btn-sm" href={WA_URL} target="_blank" rel="noopener">
            <Icon.Whatsapp size={14} /> WhatsApp
          </a>
          <button className="btn btn-primary btn-sm" onClick={onOpenCalendar}>Agendar diagnóstico</button>
        </div>
      </div>
    </div>
  );
}

/* ===========================================================
   Hero
   =========================================================== */
function Hero({ onOpenCalendar }) {
  return (
    <section id="top" style={{ position: 'relative', overflow: 'hidden', background: '#0B2545', color: '#fff' }}>
      <div className="hero-bg" aria-hidden="true" />
      <div className="hero-photo" aria-hidden="true" />
      {/* readability overlay */}
      <div aria-hidden="true" style={{
        position: 'absolute', inset: 0,
        background: 'linear-gradient(180deg, rgba(11,37,69,.55) 0%, rgba(6,19,40,.85) 100%)'
      }}/>
      {/* monospace placeholder tag — top-right */}
      <div style={{
        position: 'absolute', top: 76, right: 24, zIndex: 2,
        fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '.04em',
        color: 'rgba(255,255,255,.45)', textTransform: 'uppercase',
        border: '1px solid rgba(255,255,255,.15)', borderRadius: 4,
        padding: '4px 8px', background: 'rgba(255,255,255,.04)',
        backdropFilter: 'blur(4px)'
      }}>
        [ PLACEHOLDER · foto aérea planta solar industrial — overlay azul ]
      </div>

      <div className="container" style={{ position: 'relative', zIndex: 2, padding: '120px 24px 96px' }}>
        <div style={{ maxWidth: 920 }}>
          <div className="flex items-center gap-3 mb-6 reveal is-in" style={{ flexWrap: 'wrap' }}>
            <span className="badge badge-onblue">
              <span className="pulse-dot" /> Operando en Chile desde 2014
            </span>
            <span className="badge badge-onblue mono">B2B · INDUSTRIAL · O&amp;M</span>
          </div>

          <h1 className="h-display" style={{ color: '#fff' }}>
            Plantas solares industriales para empresas <span style={{ color: '#FFB800' }}>que no pueden parar.</span>
          </h1>

          <p className="lead mt-6" style={{ color: 'rgba(255,255,255,.78)', maxWidth: 720 }}>
            Diseño, ingeniería, instalación y O&amp;M de proyectos fotovoltaicos en Chile.
            Operamos en minería, retail, manufactura y agroindustria — desde Arica a Puerto Montt.
          </p>

          <div className="flex items-center gap-3 mt-8 flex-wrap">
            <button className="btn btn-primary btn-lg" onClick={onOpenCalendar}>
              <Icon.Calendar /> Agendar diagnóstico técnico
            </button>
            <a className="btn btn-onblue btn-lg" href={WA_URL} target="_blank" rel="noopener">
              <Icon.Whatsapp /> Hablar con un ingeniero
            </a>
          </div>

          <div className="flex items-center gap-4 mt-8" style={{ flexWrap: 'wrap', color: 'rgba(255,255,255,.55)', fontSize: 13 }}>
            <span className="flex items-center gap-2"><Icon.Check /> Sin compromiso</span>
            <span style={{ opacity: .4 }}>·</span>
            <span className="flex items-center gap-2"><Icon.Check /> Respuesta en 24h hábiles</span>
            <span style={{ opacity: .4 }}>·</span>
            <span className="flex items-center gap-2"><Icon.Check /> Visita a sitio incluida</span>
          </div>
        </div>

        {/* Floating stats card */}
        <div className="hero-stats" style={{
          marginTop: 80,
          background: 'rgba(255,255,255,.04)',
          border: '1px solid rgba(255,255,255,.12)',
          borderRadius: 14,
          backdropFilter: 'blur(8px)',
          padding: '32px 24px',
          display: 'grid',
          gridTemplateColumns: 'repeat(4, 1fr)',
          gap: 16,
        }}>
          {[
            { num: 12.4, suffix: ' MWp', label: 'Capacidad instalada' },
            { num: 47, suffix: '', label: 'Proyectos entregados' },
            { num: 12, suffix: ' años', label: 'Operando en Chile' },
            { num: 99.4, suffix: '%', label: 'Disponibilidad O&M', decimals: 1 },
          ].map((s, i) => (
            <div key={i} style={{ textAlign: 'left' }}>
              <div className="stat-num on-blue">
                <CountUp to={s.num} suffix={s.suffix} decimals={s.decimals || 0} />
              </div>
              <div className="stat-label on-blue">{s.label}</div>
            </div>
          ))}
        </div>
      </div>

      <style>{`
        @media (max-width: 720px) {
          .hero-stats { grid-template-columns: repeat(2, 1fr) !important; padding: 20px 16px !important; }
          .hero-stats .stat-num { font-size: 28px !important; }
        }
      `}</style>
    </section>
  );
}

/* ===========================================================
   Credibility bar
   =========================================================== */
function Credibility() {
  const certs = [
    'SEC',
    'ChileCompra · Proveedor del Estado',
    'ISO 9001',
    'ISO 14001',
    'ACESOL',
    'TE4 · Recepción',
  ];
  const clients = ['Minera del Norte', 'Retail Andino', 'Frutícola Maule', 'Logística Pacífico', 'Manufactura Sur', 'Vitivinícola Valle'];

  return (
    <section className="section-sm bg-off" style={{ borderTop: '1px solid var(--line)', borderBottom: '1px solid var(--line)' }}>
      <div className="container">
        <div className="flex items-center justify-between" style={{ gap: 24, flexWrap: 'wrap', marginBottom: 32 }}>
          <p className="eyebrow" style={{ margin: 0 }}>Trabajamos con</p>
          <div className="flex items-center gap-4 mono" style={{ fontSize: 12, color: 'var(--slate)' }}>
            <span className="flex items-center gap-2">
              <span style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--green)' }} />
              4 proyectos en construcción
            </span>
            <span style={{ opacity: .4 }}>·</span>
            <span>17 en ingeniería</span>
          </div>
        </div>

        <div className="logo-strip">
          {clients.map((c) => <span key={c} className="logo">{c}</span>)}
        </div>

        <hr className="hr mt-12 mb-8" />

        <div className="flex items-center justify-between" style={{ gap: 24, flexWrap: 'wrap' }}>
          <div className="flex items-center gap-4 flex-wrap">
            <p className="eyebrow" style={{ margin: 0 }}>Certificaciones y registros</p>
            {certs.map((c) => (
              <span key={c} className="tech-tag">
                <Icon.Shield /> {c}
              </span>
            ))}
          </div>
          <a href="#sector-publico" className="flex items-center gap-2" style={{ fontSize: 14, color: 'var(--pv-blue)', fontWeight: 500 }}>
            Ver dossier de licitaciones <Icon.ArrowSmall />
          </a>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Nav, StickyCTA, Hero, Credibility });
