// Fenix IA Solutions — landing components
// Components export to window at the bottom for cross-file scope.

const { useState, useEffect, useRef } = React;

// ─────────────────────────────────────────────────────────────────────────────
// NAV
// ─────────────────────────────────────────────────────────────────────────────
function Nav({ accent }) {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 20);
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  return (
    <header className={`nav ${scrolled ? 'nav--scrolled' : ''}`}>
      <div className="nav__inner">
        <a href="#top" className="nav__brand">
          <img src="assets/fenix-logo.jpeg" alt="Fenix IA Solutions" className="nav__logo" />
          <div className="nav__wordmark">
            <span className="nav__name">FENIX<span style={{color: accent}}>·</span>IA</span>
            <span className="nav__sub">SOLUTIONS</span>
          </div>
        </a>
        <nav className="nav__links">
          <a href="#servicios">Servicios</a>
          <a href="#proceso">Proceso</a>
          <a href="#contacto">Contacto</a>
        </nav>
        <a href="#contacto" className="nav__cta" style={{borderColor: accent, color: accent}}>
          Hablemos
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
            <path d="M5 12h14M13 5l7 7-7 7"/>
          </svg>
        </a>
      </div>
    </header>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// HERO — Variant A: Editorial / static with subtle ember
// ─────────────────────────────────────────────────────────────────────────────
function HeroEditorial({ accent }) {
  return (
    <section className="hero hero--editorial">
      <div className="hero__grid-bg" />
      <div className="hero__inner">
        <div className="hero__eyebrow">
          <span className="hero__dot" style={{background: accent}} />
          <span>Fenix IA Solutions S.L.</span>
          <span className="hero__sep">·</span>
          <span>Elche · España</span>
        </div>

        <h1 className="hero__title">
          Tecnología<br/>
          <span className="hero__accent" style={{color: accent}}>impulsada por IA</span>,<br/>
          para PYMEs que no se quedan atrás.
        </h1>

        <p className="hero__lede">
          Diseñamos, construimos y mantenemos las herramientas digitales que tu empresa necesita —
          con inteligencia artificial integrada donde aporta valor real, no donde queda bonito.
        </p>

        <div className="hero__cta-row">
          <a href="#contacto" className="btn btn--primary" style={{background: accent}}>
            Cuéntanos tu proyecto
          </a>
          <a href="#servicios" className="btn btn--ghost">
            Ver servicios
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="M12 5v14M5 12l7 7 7-7"/>
            </svg>
          </a>
        </div>

        <div className="hero__meta">
          <div className="hero__meta-item">
            <span className="hero__meta-num" style={{color: accent}}>+40</span>
            <span className="hero__meta-label">proyectos<br/>entregados</span>
          </div>
          <div className="hero__meta-divider" />
          <div className="hero__meta-item">
            <span className="hero__meta-num" style={{color: accent}}>8</span>
            <span className="hero__meta-label">años haciendo<br/>software en España</span>
          </div>
          <div className="hero__meta-divider" />
          <div className="hero__meta-item">
            <span className="hero__meta-num" style={{color: accent}}>100%</span>
            <span className="hero__meta-label">equipo propio,<br/>sin subcontrata</span>
          </div>
        </div>
      </div>

      <div className="hero__visual">
        <div className="hero__shield-glow" style={{background: `radial-gradient(circle, ${accent}33 0%, transparent 60%)`}} />
        <img src="assets/fenix-logo.jpeg" alt="" className="hero__shield" />
        <div className="hero__rings">
          <div className="hero__ring hero__ring--1" />
          <div className="hero__ring hero__ring--2" />
          <div className="hero__ring hero__ring--3" />
        </div>
      </div>
    </section>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// HERO — Variant B: Terminal / code-oriented
// ─────────────────────────────────────────────────────────────────────────────
function HeroTerminal({ accent }) {
  const [typed, setTyped] = useState('');
  const fullText = 'fenix deploy --client="tu-empresa" --ai=integrated';

  useEffect(() => {
    let i = 0;
    const id = setInterval(() => {
      i++;
      setTyped(fullText.slice(0, i));
      if (i >= fullText.length) clearInterval(id);
    }, 45);
    return () => clearInterval(id);
  }, []);

  return (
    <section className="hero hero--terminal">
      <div className="hero__grid-bg" />
      <div className="hero__inner hero__inner--terminal">
        <div className="hero__eyebrow">
          <span className="hero__dot" style={{background: accent}} />
          <span>Desarrollo de software · IA aplicada</span>
        </div>

        <h1 className="hero__title hero__title--terminal">
          De la idea al código<br/>
          que mueve tu negocio.
        </h1>

        <p className="hero__lede">
          Equipo técnico español especializado en integrar IA, automatizar procesos
          y construir herramientas digitales para PYMEs que necesitan más que una plantilla.
        </p>

        <div className="terminal">
          <div className="terminal__bar">
            <span className="terminal__dot terminal__dot--r" />
            <span className="terminal__dot terminal__dot--y" />
            <span className="terminal__dot terminal__dot--g" />
            <span className="terminal__title">~/fenix-ia · zsh</span>
          </div>
          <div className="terminal__body">
            <div className="terminal__line"><span className="terminal__prompt" style={{color: accent}}>fenix@solutions</span> <span className="terminal__sep">~</span> <span className="terminal__cmd">{typed}<span className="terminal__caret" style={{background: accent}} /></span></div>
            <div className="terminal__line terminal__line--out">→ analizando requisitos...</div>
            <div className="terminal__line terminal__line--out">→ diseñando arquitectura...</div>
            <div className="terminal__line terminal__line--out">→ <span style={{color: accent}}>integrando modelos de IA</span></div>
            <div className="terminal__line terminal__line--out">→ <span style={{color: '#7ee787'}}>✓ proyecto listo en 6–12 semanas</span></div>
          </div>
        </div>

        <div className="hero__cta-row">
          <a href="#contacto" className="btn btn--primary" style={{background: accent}}>
            Iniciar proyecto
          </a>
          <a href="#servicios" className="btn btn--ghost">Ver qué hacemos</a>
        </div>
      </div>
    </section>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// MARQUEE — continuous, seamless loop measured in px
// ─────────────────────────────────────────────────────────────────────────────
function Marquee({ accent, items, pxPerSecond = 70 }) {
  const copyRef = useRef(null);
  const [copies, setCopies] = useState(2);
  const [copyWidth, setCopyWidth] = useState(0);

  useEffect(() => {
    function measure() {
      if (!copyRef.current) return;
      const w = copyRef.current.getBoundingClientRect().width;
      if (!w) return;
      setCopyWidth(w);
      const viewport = window.innerWidth;
      const needed = Math.max(2, Math.ceil(viewport / w) + 1);
      setCopies(needed);
    }
    measure();
    window.addEventListener('resize', measure);
    return () => window.removeEventListener('resize', measure);
  }, [items.join('|')]);

  const duration = copyWidth > 0 ? copyWidth / pxPerSecond : 30;

  const renderCopy = (key, ref) => (
    <div key={key} ref={ref} className="marquee__copy">
      {items.flatMap((label, idx) => [
        <span key={`s-${idx}`} style={{color: accent}} aria-hidden="true">✦</span>,
        <span key={`l-${idx}`}>{label}</span>,
      ])}
    </div>
  );

  return (
    <div className="hero__marquee">
      <div
        className="hero__marquee-track"
        style={{
          animationDuration: `${duration}s`,
          ['--marquee-shift']: `-${copyWidth}px`,
        }}
      >
        {Array.from({length: copies}).map((_, i) =>
          renderCopy(i, i === 0 ? copyRef : undefined)
        )}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// HERO — Variant C: Bold / typographic
// ─────────────────────────────────────────────────────────────────────────────
function HeroBold({ accent }) {
  return (
    <section className="hero hero--bold">
      <div className="hero__bold-bg">
        <div className="hero__ember" style={{background: `radial-gradient(ellipse at 70% 40%, ${accent}55 0%, transparent 50%)`}} />
      </div>
      <div className="hero__inner hero__inner--bold">
        <div className="hero__eyebrow">
          <span className="hero__dot" style={{background: accent}} />
          <span>FENIX IA SOLUTIONS</span>
        </div>

        <h1 className="hero__title hero__title--bold">
          <span className="hero__line">Renacemos</span>
          <span className="hero__line">tu software</span>
          <span className="hero__line hero__line--accent" style={{color: accent}}>con IA.</span>
        </h1>

        <div className="hero__bold-row">
          <p className="hero__lede hero__lede--bold" style={{textAlign:'justify'}}>
            Llevamos a las PYMEs españolas a la siguiente fase digital.
            Integración de IA, automatización inteligente y modelos aplicados a
            problemas reales — facturación, atención al cliente, operaciones, datos.
          </p>
          <div className="hero__bold-cta">
            <a href="#contacto" className="btn btn--primary btn--xl" style={{background: accent}}>
              Empieza tu proyecto →
            </a>
            <span className="hero__bold-note">Primera consulta gratuita · respuesta en 24h</span>
          </div>
        </div>

        <Marquee accent={accent} items={['Integración IA','Automatización','Chatbots inteligentes','Análisis de datos','APIs y backend']} pxPerSecond={70} />
      </div>
    </section>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// SERVICIOS
// ─────────────────────────────────────────────────────────────────────────────
const SERVICES = [
  {
    num: '01',
    title: 'IA aplicada a tu negocio',
    desc: 'Integramos modelos de IA donde aportan valor: clasificación de documentos, asistentes internos, análisis predictivo, generación automática.',
    bullets: ['LLMs (GPT, Claude, Llama)', 'RAG con tus documentos'],
    icon: 'spark'
  },
  {
    num: '02',
    title: 'Automatización de procesos',
    desc: 'Conectamos tus herramientas y eliminamos el trabajo manual repetitivo. ERP, CRM, facturación, atención al cliente.',
    bullets: ['Integraciones API', 'Conectores ERP y CRM'],
    icon: 'flow'
  },
  {
    num: '03',
    title: 'Mantenimiento de software',
    desc: 'Mantenemos tu software vivo: corregimos errores, lo ponemos al día con las nuevas versiones y lo evolucionamos según tu negocio.',
    bullets: ['Mantenimiento correctivo', 'Mantenimiento evolutivo', 'Actualizaciones de dependencias', 'Refactorización y optimización'],
    icon: 'shield'
  },
  {
    num: '04',
    title: 'Consultoría de procesos',
    desc: 'Analizamos tus procesos actuales, detectamos los cuellos de botella y diseñamos el plan para automatizarlos. Te decimos qué vale la pena cambiar y qué no.',
    bullets: ['Mapeo de procesos', 'Análisis de cuellos de botella', 'Plan de digitalización', 'Acompañamiento al equipo'],
    icon: 'compass'
  }
];

function ServiceIcon({ name, accent }) {
  const props = { width: 28, height: 28, viewBox: '0 0 24 24', fill: 'none', stroke: accent, strokeWidth: 1.6, strokeLinecap: 'round', strokeLinejoin: 'round' };
  switch (name) {
    case 'code': return <svg {...props}><path d="M8 6L2 12l6 6M16 6l6 6-6 6"/><path d="M14 4l-4 16" opacity="0.5"/></svg>;
    case 'spark': return <svg {...props}><path d="M12 3v3M12 18v3M3 12h3M18 12h3M5.6 5.6l2.1 2.1M16.3 16.3l2.1 2.1M5.6 18.4l2.1-2.1M16.3 7.7l2.1-2.1"/><circle cx="12" cy="12" r="3"/></svg>;
    case 'flow': return <svg {...props}><circle cx="5" cy="6" r="2"/><circle cx="19" cy="6" r="2"/><circle cx="5" cy="18" r="2"/><circle cx="19" cy="18" r="2"/><path d="M7 6h10M7 18h10M5 8v8M19 8v8" opacity="0.6"/></svg>;
    case 'mobile': return <svg {...props}><rect x="6" y="2" width="12" height="20" rx="2"/><path d="M11 18h2"/></svg>;
    case 'shield': return <svg {...props}><path d="M12 2l8 4v6c0 5-3.5 9-8 10-4.5-1-8-5-8-10V6l8-4z"/><path d="M9 12l2 2 4-4" opacity="0.7"/></svg>;
    case 'compass': return <svg {...props}><circle cx="12" cy="12" r="9"/><path d="M16 8l-2 6-6 2 2-6 6-2z"/></svg>;
    default: return null;
  }
}

function Servicios({ accent }) {
  return (
    <section id="servicios" className="services">
      <div className="services__head">
        <div className="section__eyebrow">
          <span className="section__bar" style={{background: accent}} />
          <span>02 · Servicios</span>
        </div>
        <h2 className="section__title">
          Construimos lo que tu empresa
          <br/>
          <span style={{color: accent}}>realmente necesita.</span>
        </h2>
        <p className="section__lede">
          No hacemos plantillas. Cada proyecto empieza con escuchar, entender el problema
          y diseñar la solución más simple que funcione — y después la construimos en serio.
        </p>
      </div>

      <div className="services__grid">
        {SERVICES.map((s) => (
          <article key={s.num} className="service-card">
            <div className="service-card__top">
              <span className="service-card__num">{s.num}</span>
              <ServiceIcon name={s.icon} accent={accent} />
            </div>
            <h3 className="service-card__title">{s.title}</h3>
            <p className="service-card__desc">{s.desc}</p>
            <ul className="service-card__bullets">
              {s.bullets.map((b) => (
                <li key={b}>
                  <span className="service-card__bullet-dot" style={{background: accent}} />
                  {b}
                </li>
              ))}
            </ul>
          </article>
        ))}
      </div>
    </section>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// PROCESO (small, supporting section)
// ─────────────────────────────────────────────────────────────────────────────
const STEPS = [
  { n: '01', t: 'Descubrimiento', d: 'Una primera reunión sin compromiso. Entendemos tu negocio, tus problemas y qué te ha llevado hasta aquí.' },
  { n: '02', t: 'Propuesta', d: 'En 5–7 días te enviamos una propuesta detallada con alcance, tiempos y precio cerrado. Sin sorpresas.' },
  { n: '03', t: 'Construcción', d: 'Sprints de 1–2 semanas con demos en vivo. Ves el producto crecer y das feedback continuo.' },
  { n: '04', t: 'Entrega y soporte', d: 'Despliegue, formación a tu equipo y mantenimiento continuo. Seguimos cerca cuando nos necesitas.' },
];

function Proceso({ accent }) {
  return (
    <section id="proceso" className="process">
      <div className="process__head">
        <div className="section__eyebrow">
          <span className="section__bar" style={{background: accent}} />
          <span>03 · Cómo trabajamos</span>
        </div>
        <h2 className="section__title">Un proceso claro, sin humo.</h2>
      </div>
      <div className="process__steps">
        {STEPS.map((s, i) => (
          <div key={s.n} className="process__step">
            <div className="process__num" style={{color: accent}}>{s.n}</div>
            <div className="process__line" style={{background: i === STEPS.length - 1 ? 'transparent' : 'rgba(255,255,255,0.08)'}} />
            <div className="process__body">
              <h3 className="process__t">{s.t}</h3>
              <p className="process__d">{s.d}</p>
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// CONTACTO
// ─────────────────────────────────────────────────────────────────────────────
const LEADS_PROXY_URL = 'https://fenix-leads-proxy.proveedores-702.workers.dev';

function Contacto({ accent }) {
  const [form, setForm] = useState({ nombre: '', empresa: '', email: '', telefono: '', tipo: 'web', mensaje: '' });
  const [privacy, setPrivacy] = useState(true);
  const [submitted, setSubmitted] = useState(false);
  const [sending, setSending] = useState(false);
  const [submitError, setSubmitError] = useState('');
  const [errors, setErrors] = useState({});

  const validate = () => {
    const e = {};
    if (!form.nombre.trim()) e.nombre = 'Necesitamos tu nombre';
    if (!form.email.trim()) e.email = 'Necesitamos un email';
    else if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(form.email)) e.email = 'Email no válido';
    if (!form.mensaje.trim() || form.mensaje.trim().length < 10) e.mensaje = 'Cuéntanos un poco más (10+ caracteres)';
    if (!privacy) e.privacy = 'Debes aceptar la política de privacidad';
    return e;
  };

  const tipoLabel = (id) => {
    const map = { web: 'Aplicación web', ia: 'Integración IA', auto: 'Automatización', consultoria: 'Consultoría', otro: 'Otro' };
    return map[id] || id;
  };

  const submit = async (ev) => {
    ev.preventDefault();
    setSubmitError('');
    const e = validate();
    setErrors(e);
    if (Object.keys(e).length > 0) return;

    setSending(true);
    try {
      const productLabel = tipoLabel(form.tipo);
      const noteLines = [
        `Tipo: ${productLabel}`,
        form.telefono ? `Teléfono: ${form.telefono}` : null,
        '',
        form.mensaje,
      ].filter(Boolean).join('\n');

      const resp = await fetch(LEADS_PROXY_URL, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: form.nombre.trim(),
          email: form.email.trim(),
          company: form.empresa.trim(),
          phone: form.telefono.trim(),
          product: `Fenixia · ${productLabel}`,
          source: 'fenixia.tech',
          message: noteLines,
          privacy_accepted: true,
          privacy_accepted_at: new Date().toISOString(),
        }),
      });
      if (!resp.ok) throw new Error('HTTP ' + resp.status);
      setSubmitted(true);
    } catch (err) {
      setSubmitError('No pudimos enviar el formulario. Escríbenos a contacto@fenixia.tech.');
    } finally {
      setSending(false);
    }
  };

  const update = (k) => (ev) => {
    setForm((f) => ({ ...f, [k]: ev.target.value }));
    if (errors[k]) setErrors((er) => ({ ...er, [k]: undefined }));
  };

  const tipos = [
    { id: 'web', label: 'Aplicación web' },
    { id: 'ia', label: 'Integración IA' },
    { id: 'auto', label: 'Automatización' },
    { id: 'consultoria', label: 'Consultoría' },
    { id: 'otro', label: 'Otro' },
  ];

  return (
    <section id="contacto" className="contact">
      <div className="contact__inner">
        <div className="contact__left">
          <div className="section__eyebrow">
            <span className="section__bar" style={{background: accent}} />
            <span>04 · Contacto</span>
          </div>
          <h2 className="section__title">
            Cuéntanos qué quieres<br/>
            <span style={{color: accent}}>construir.</span>
          </h2>
          <p className="section__lede">
            Respondemos en menos de 24 horas laborables. La primera reunión es siempre gratuita
            y sin compromiso — incluso si decides que no somos el equipo adecuado para tu proyecto.
          </p>

          <div className="contact__channels">
            <a href="mailto:contacto@fenixia.tech" className="contact__channel">
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke={accent} strokeWidth="1.6">
                <rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3 7l9 6 9-6"/>
              </svg>
              <div>
                <div className="contact__channel-label">Email directo</div>
                <div className="contact__channel-value">contacto@fenixia.tech</div>
              </div>
            </a>
            <a href="tel:+34 966 101 029" className="contact__channel">
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke={accent} strokeWidth="1.6">
                <path d="M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07 19.5 19.5 0 01-6-6 19.79 19.79 0 01-3.07-8.67A2 2 0 014.11 2h3a2 2 0 012 1.72c.13.96.37 1.9.72 2.81a2 2 0 01-.45 2.11L8.09 9.91a16 16 0 006 6l1.27-1.27a2 2 0 012.11-.45c.91.35 1.85.59 2.81.72A2 2 0 0122 16.92z"/>
              </svg>
              <div>
                <div className="contact__channel-label">Teléfono</div>
                <div className="contact__channel-value">+34 966 101 029</div>
              </div>
            </a>
            <div className="contact__channel">
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke={accent} strokeWidth="1.6">
                <path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0118 0z"/><circle cx="12" cy="10" r="3"/>
              </svg>
              <div>
                <div className="contact__channel-label">Oficina</div>
                <div className="contact__channel-value">C/ La Paz, 83 · Elche</div>
              </div>
            </div>
          </div>
        </div>

        <div className="contact__right">
          {submitted ? (
            <div className="contact__success">
              <div className="contact__success-icon" style={{background: `${accent}22`, color: accent}}>
                <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                  <path d="M5 13l4 4L19 7"/>
                </svg>
              </div>
              <h3>Mensaje recibido</h3>
              <p>Gracias <strong>{form.nombre}</strong>. Te responderemos a <strong>{form.email}</strong> en menos de 24 horas laborables.</p>
              <button className="btn btn--ghost" onClick={() => { setSubmitted(false); setSubmitError(''); setForm({ nombre: '', empresa: '', email: '', telefono: '', tipo: 'web', mensaje: '' }); setPrivacy(true); }}>
                Enviar otro mensaje
              </button>
            </div>
          ) : (
            <form className="contact__form" onSubmit={submit} noValidate>
              <div className="field-row">
                <Field label="Nombre" error={errors.nombre}>
                  <input type="text" value={form.nombre} onChange={update('nombre')} placeholder="María García" />
                </Field>
                <Field label="Empresa" optional>
                  <input type="text" value={form.empresa} onChange={update('empresa')} placeholder="Tu empresa, S.L." />
                </Field>
              </div>

              <div className="field-row">
                <Field label="Email" error={errors.email}>
                  <input type="email" value={form.email} onChange={update('email')} placeholder="maria@empresa.com" />
                </Field>
                <Field label="Teléfono" optional>
                  <input type="tel" value={form.telefono} onChange={update('telefono')} placeholder="+34 600 000 000" />
                </Field>
              </div>

              <Field label="¿Qué tipo de proyecto?">
                <div className="chip-group">
                  {tipos.map((t) => (
                    <button
                      type="button"
                      key={t.id}
                      className={`chip ${form.tipo === t.id ? 'chip--on' : ''}`}
                      style={form.tipo === t.id ? { borderColor: accent, color: accent, background: `${accent}14` } : {}}
                      onClick={() => setForm((f) => ({ ...f, tipo: t.id }))}
                    >
                      {t.label}
                    </button>
                  ))}
                </div>
              </Field>

              <Field label="Cuéntanos brevemente" error={errors.mensaje}>
                <textarea value={form.mensaje} onChange={update('mensaje')} rows={5} placeholder="Estamos pensando en construir... el problema actual es... necesitamos algo que..."/>
              </Field>

              <div className="contact__submit-row">
                <label className="contact__check">
                  <input type="checkbox" checked={privacy} onChange={(e) => { setPrivacy(e.target.checked); if (errors.privacy) setErrors((er) => ({ ...er, privacy: undefined })); }} />
                  <span>He leído y acepto la <a href="/privacidad/" target="_blank" rel="noopener">política de privacidad</a></span>
                </label>
                <button type="submit" className="btn btn--primary" style={{background: accent, opacity: sending ? 0.7 : 1}} disabled={sending}>
                  {sending ? 'Enviando…' : 'Enviar mensaje'}
                  {!sending && (
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                      <path d="M5 12h14M13 5l7 7-7 7"/>
                    </svg>
                  )}
                </button>
              </div>
              {errors.privacy && <div className="field__error" style={{marginTop: 8}}>{errors.privacy}</div>}
              {submitError && <div className="field__error" style={{marginTop: 8}}>{submitError}</div>}
            </form>
          )}
        </div>
      </div>
    </section>
  );
}

function Field({ label, optional, error, children }) {
  return (
    <label className={`field ${error ? 'field--error' : ''}`}>
      <span className="field__label">
        {label}
        {optional && <span className="field__optional"> · opcional</span>}
        {error && <span className="field__error">{error}</span>}
      </span>
      {children}
    </label>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// FOOTER
// ─────────────────────────────────────────────────────────────────────────────
function Footer({ accent }) {
  return (
    <footer className="footer">
      <div className="footer__big">
        <div className="footer__big-text">
          ¿Listo para que tu software<br/>
          <span style={{color: accent}}>renazca?</span>
        </div>
        <a href="#contacto" className="btn btn--primary btn--xl" style={{background: accent}}>
          Hablemos →
        </a>
      </div>

      <div className="footer__cols">
        <div className="footer__col footer__col--brand">
          <div className="footer__brand">
            <img src="assets/fenix-logo.jpeg" alt="" className="footer__logo" />
            <div>
              <div className="footer__name">FENIX<span style={{color: accent}}>·</span>IA SOLUTIONS</div>
              <div className="footer__tagline">IA aplicada · automatización · desde Elche</div>
            </div>
          </div>
          <p className="footer__about" style={{textAlign:'justify'}}>
            Fenix IA Solutions S.L. es una empresa española especializada en
            integrar IA, automatizar procesos y construir herramientas digitales
            para PYMEs.
          </p>
        </div>

        <div className="footer__col">
          <h4>Servicios</h4>
          <ul>
            <li><a href="#servicios">Integración IA</a></li>
            <li><a href="#servicios">Automatización</a></li>
            <li><a href="#servicios">Mantenimiento</a></li>
            <li><a href="#servicios">Consultoría de procesos</a></li>
          </ul>
        </div>

        <div className="footer__col">
          <h4>Empresa</h4>
          <ul>
            <li><a href="#proceso">Proceso</a></li>
            <li><a href="#contacto">Contacto</a></li>
            <li></li>
            <li></li>
          </ul>
        </div>

        <div className="footer__col">
          <h4>Contacto</h4>
          <ul className="footer__contact">
            <li>contacto@fenixia.tech</li>
            <li>+34 966 101 029</li>
            <li>C/ La Paz, 83<br/>03320 Elche, Alicante</li>
          </ul>
          <div className="footer__social">
            <a href="https://www.linkedin.com/company/109810068/admin/dashboard/" target="_blank" rel="noopener" aria-label="LinkedIn">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M19 3a2 2 0 012 2v14a2 2 0 01-2 2H5a2 2 0 01-2-2V5a2 2 0 012-2h14zM8.34 17.34V9.67H5.83v7.67h2.51zM7.08 8.58a1.46 1.46 0 100-2.91 1.46 1.46 0 000 2.91zm10.93 8.76v-4.41c0-2.18-1.16-3.19-2.71-3.19-1.25 0-1.81.69-2.12 1.17V9.67H10.67c.03.71 0 7.67 0 7.67h2.51v-4.28c0-.23.02-.45.08-.61.18-.45.59-.92 1.28-.92.9 0 1.26.69 1.26 1.69v4.12h2.5z"/></svg>
            </a>
            <a href="#" aria-label="GitHub" style={{display:'none'}}>
              <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2a10 10 0 00-3.16 19.49c.5.09.68-.22.68-.48v-1.7c-2.78.6-3.37-1.34-3.37-1.34-.45-1.16-1.11-1.47-1.11-1.47-.91-.62.07-.6.07-.6 1 .07 1.53 1.03 1.53 1.03.89 1.53 2.34 1.09 2.91.83.09-.65.35-1.09.63-1.34-2.22-.25-4.56-1.11-4.56-4.94 0-1.09.39-1.98 1.03-2.68-.1-.25-.45-1.27.1-2.65 0 0 .84-.27 2.75 1.02a9.55 9.55 0 015 0c1.91-1.29 2.75-1.02 2.75-1.02.55 1.38.2 2.4.1 2.65.64.7 1.03 1.59 1.03 2.68 0 3.84-2.34 4.69-4.57 4.94.36.31.68.92.68 1.85v2.74c0 .27.18.58.69.48A10 10 0 0012 2z"/></svg>
            </a>
            <a href="#" aria-label="X" style={{display:'none'}}>
              <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231 5.45-6.231zm-1.161 17.52h1.833L7.084 4.126H5.117L17.083 19.77z"/></svg>
            </a>
          </div>
        </div>
      </div>

      <div className="footer__base">
        <div className="footer__legal">
          <span>© 2026 Fenix IA Solutions S.L.<span className="footer__cif"> · CIF B22739668</span></span>
          <span>·</span>
          <a href="/aviso-legal/">Aviso legal</a>
          <a href="/privacidad/">Privacidad</a>
          <a href="/cookies/">Cookies</a>
        </div>
        <div className="footer__made">
          Hecho con <span style={{color: accent}}>♦</span> en Elche
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, {
  Nav, HeroEditorial, HeroTerminal, HeroBold,
  Servicios, Proceso, Contacto, Footer
});
