/* global React, PROGRAMS, eur, Icon, Button, Card, Badge, LevelChip, Eyebrow, EPMark, Logo */
const { useState: useStateFA } = React;

/* ---------------------------------------------------------------
   FORMSPREE ENDPOINT  ·  edita esta línea cuando tengas el form ID.
   Pasos:
     1) Crea cuenta en https://formspree.io
     2) Nuevo formulario → copia el endpoint (https://formspree.io/f/XXXXXXXX)
     3) Reemplaza el valor de FORMSPREE_ENDPOINT abajo
     4) En el dashboard, activa "Notification emails" → secretaria@escueladeprotones.com
--------------------------------------------------------------- */
const FORMSPREE_ENDPOINT = 'https://formspree.io/f/maqkbool';

/* ========================================
   Format / Methodology
   ======================================== */
function MethodologySection() {
  return (
    <section id="metodologia" style={{padding:'120px 0', background:'var(--bg)'}}>
      <div className="container">
        <div style={{display:'grid', gridTemplateColumns:'1fr 1.2fr', gap:80, alignItems:'center'}}>
          <div>
            <Eyebrow>// Metodología</Eyebrow>
            <h2 style={{margin:'0 0 24px', fontSize:48, lineHeight:1.05, letterSpacing:'-0.02em'}}>
              Formato intensivo.<br/>Casos reales. Aforo controlado.
            </h2>
            <p className="lead" style={{margin:'0 0 32px', maxWidth:520}}>
              Cada edición se imparte en tres días consecutivos, con cuatro horas diarias en directo. Sin grabaciones públicas, sin asistentes pasivos: clases enfocadas, ejercicios sobre datasheets reales y debate técnico.
            </p>

            <div style={{display:'flex', flexDirection:'column', gap:12, maxWidth:520}}>
              {[
                ['Teoría aplicada', 'Cada concepto se aterriza en un caso real auditado, no en ejemplos académicos.'],
                ['Datasheets de fabricante', 'Aprendes a leer los documentos que llegan a tu mesa, no versiones simplificadas.'],
                ['Material descargable', 'Plantillas de cálculo, hojas de selección y checklist normativos para llevarte al puesto.'],
                ['Certificado firmado', 'Documento acreditativo emitido por Lean Hydrogen al completar cada programa.'],
              ].map(([t,b]) => (
                <div key={t} style={{
                  display:'flex', gap:14, padding:'14px 0',
                  borderTop:'1px solid var(--border)',
                }}>
                  <div style={{
                    width:24, height:24, borderRadius:6,
                    background:'var(--lh-navy)', color:'#fff', flexShrink:0,
                    display:'flex',alignItems:'center',justifyContent:'center',
                  }}>
                    <Icon name="check" size={14} stroke={2.4}/>
                  </div>
                  <div>
                    <div style={{fontSize:15, fontWeight:600, marginBottom:2}}>{t}</div>
                    <div style={{fontSize:14, color:'var(--fg-muted)', lineHeight:1.5}}>{b}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* Schedule card */}
          <div style={{
            background:'var(--lh-navy)', color:'#fff', borderRadius:16,
            padding:'40px 40px 32px', position:'relative', overflow:'hidden',
          }}>
            <div style={{
              position:'absolute', inset:0,
              backgroundImage:'linear-gradient(rgba(255,255,255,.04) 1px,transparent 1px),linear-gradient(90deg,rgba(255,255,255,.04) 1px,transparent 1px)',
              backgroundSize:'40px 40px',
            }}/>
            <div style={{position:'relative'}}>
              <div style={{
                fontFamily:'var(--font-mono)', fontSize:11, letterSpacing:'.14em',
                color:'var(--lh-cyan)', textTransform:'uppercase', marginBottom:12,
              }}>Horario tipo de edición</div>
              <h3 style={{margin:'0 0 8px', fontSize:28, color:'#fff', letterSpacing:'-0.01em'}}>
                12 horas de formación en directo
              </h3>
              <div style={{
                margin:'0 0 28px', fontSize:14, color:'rgba(255,255,255,.7)',
                display:'flex', alignItems:'center', gap:8, flexWrap:'wrap',
              }}>
                <span className="tnum" style={{
                  fontFamily:'var(--font-mono)', color:'var(--lh-cyan)', fontWeight:600,
                  letterSpacing:'.04em',
                }}>16:00 — 20:00</span>
                <span style={{opacity:.5}}>·</span>
                <span>Hora peninsular (CET/CEST)</span>
              </div>

              {[
                { day:'Día 01', date:'Mar', label:'Fundamentos y marco general' },
                { day:'Día 02', date:'Mié', label:'Análisis técnico aplicado' },
                { day:'Día 03', date:'Jue', label:'Casos reales y entrega de material' },
              ].map((d, i)=>(
                <div key={d.day} style={{
                  display:'grid', gridTemplateColumns:'auto 1fr auto', alignItems:'center', gap:20,
                  padding:'18px 0', borderTop: i===0?'1px solid rgba(255,255,255,.14)':0,
                  borderBottom:'1px solid rgba(255,255,255,.14)',
                }}>
                  <div style={{
                    width:44, height:44, borderRadius:10,
                    background:'rgba(255,255,255,.06)', border:'1px solid rgba(255,255,255,.16)',
                    display:'flex',flexDirection:'column',alignItems:'center',justifyContent:'center',
                  }}>
                    <span style={{fontFamily:'var(--font-mono)', fontSize:9, color:'rgba(255,255,255,.55)', letterSpacing:'.1em', textTransform:'uppercase'}}>{d.date}</span>
                    <span style={{fontFamily:'var(--font-display)', fontSize:16, fontWeight:700, lineHeight:1}}>{String(i+1).padStart(2,'0')}</span>
                  </div>
                  <div>
                    <div style={{
                      fontFamily:'var(--font-mono)', fontSize:11, letterSpacing:'.14em',
                      color:'rgba(255,255,255,.55)', textTransform:'uppercase', marginBottom:4,
                    }}>{d.day}</div>
                    <div style={{fontSize:15, color:'#fff', fontWeight:500}}>{d.label}</div>
                  </div>
                  <div className="tnum" style={{
                    fontFamily:'var(--font-mono)', fontSize:13, color:'var(--lh-cyan)',
                    letterSpacing:'.02em', textAlign:'right',
                  }}>16:00 — 20:00</div>
                </div>
              ))}

              <div style={{
                display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:24,
                marginTop:28, paddingTop:24,
                borderTop:'1px solid rgba(255,255,255,.14)',
              }}>
                {[
                  ['Total', '12 h'],
                  ['Aforo', '30 alumnos'],
                  ['Idioma', 'Español'],
                ].map(([k,v])=>(
                  <div key={k}>
                    <div style={{
                      fontFamily:'var(--font-mono)', fontSize:10, letterSpacing:'.14em',
                      color:'rgba(255,255,255,.5)', textTransform:'uppercase', marginBottom:4,
                    }}>{k}</div>
                    <div style={{fontSize:18, fontWeight:600}}>{v}</div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ========================================
   Calendar / cohorts
   ======================================== */
function CalendarSection() {
  // Launch strategy: each programme runs ONE live edition during the Oct–Dec 2026
  // window, then continues as on-demand async editions from 2027 onwards.
  const cohorts = [
    { id:'p1', month:'Oct', year:2026, dates:'13 — 15 oct', spots: 12, total: 30 },
    { id:'p2', month:'Oct', year:2026, dates:'27 — 29 oct', spots:  8, total: 30 },
    { id:'p3', month:'Nov', year:2026, dates:'10 — 12 nov', spots: 14, total: 30 },
    { id:'p4', month:'Nov', year:2026, dates:'24 — 26 nov', spots: 18, total: 30 },
    { id:'p5', month:'Dic', year:2026, dates:' 1 —  3 dic', spots: 22, total: 30 },
    { id:'p6', month:'Dic', year:2026, dates:'15 — 17 dic', spots: 26, total: 30 },
  ];

  return (
    <section id="calendario" style={{padding:'96px 0', background:'var(--bg-subtle)'}}>
      <div className="container">
        <div style={{
          display:'flex', justifyContent:'space-between', alignItems:'flex-end',
          gap:32, marginBottom:40, flexWrap:'wrap',
        }}>
          <div style={{maxWidth:680}}>
            <Eyebrow>// Lanzamiento · Q4 2026</Eyebrow>
            <h2 style={{margin:'0 0 12px', fontSize:40, lineHeight:1.05, letterSpacing:'-0.02em'}}>
              Ediciones en vivo de lanzamiento.
            </h2>
            <p className="lead" style={{margin:0}}>
              Cada programa abre con <strong>una única edición en directo</strong> entre octubre y diciembre de 2026, con plaza limitada y acceso al claustro. A partir de 2027 quedará disponible en formato asíncrono, a tu ritmo.
            </p>
          </div>
          <div style={{
            display:'flex',alignItems:'center',gap:10,
            padding:'10px 14px', background:'#fff', borderRadius:10,
            border:'1px solid var(--border)',
            fontSize:13, color:'var(--fg-muted)',
          }}>
            <span style={{width:6,height:6,borderRadius:3,background:'var(--success)'}}/>
            Preinscripción ya disponible
          </div>
        </div>

        <div style={{
          background:'#fff', border:'1px solid var(--border)', borderRadius:14,
          overflow:'hidden',
        }}>
          {cohorts.map((c, i)=>{
            const p = PROGRAMS.find(x => x.id === c.id);
            const lc = p.level === 'i' ? 'var(--lh-cyan)'
                    : p.level === 'a' ? 'var(--lh-blue)' : '#9A9F00';
            const remaining = c.total - c.spots;
            const pct = (c.spots / c.total) * 100;
            const isFull = remaining <= 0;
            return (
              <div key={c.id} style={{
                display:'grid',
                gridTemplateColumns:'88px 80px 1fr 110px 140px 200px 120px 140px',
                alignItems:'center', gap:20, padding:'20px 24px',
                borderTop: i===0 ? 0 : '1px solid var(--border)',
              }}>
                <div style={{
                  width:64, height:64, borderRadius:12,
                  background:'var(--bg-subtle)', border:'1px solid var(--border)',
                  display:'flex',flexDirection:'column',alignItems:'center',justifyContent:'center',
                }}>
                  <span style={{
                    fontFamily:'var(--font-mono)', fontSize:10, color:'var(--fg-subtle)',
                    letterSpacing:'.12em', textTransform:'uppercase',
                  }}>{c.month}</span>
                  <span style={{fontFamily:'var(--font-display)', fontSize:22, fontWeight:700, color:'var(--fg)', lineHeight:1, marginTop:2}}>
                    {c.year}
                  </span>
                </div>
                <div style={{
                  fontFamily:'var(--font-mono)', fontSize:12, color:'var(--fg-subtle)',
                }}>{p.code}</div>
                <div>
                  <div style={{fontSize:16, fontWeight:600, marginBottom:2}}>{p.title}</div>
                  <div style={{fontSize:13, color:'var(--fg-muted)'}}>{p.subtitle}</div>
                </div>
                <div>
                  <span style={{
                    display:'inline-flex', alignItems:'center', gap:6,
                    fontFamily:'var(--font-mono)', fontSize:10, letterSpacing:'.12em',
                    textTransform:'uppercase', fontWeight:700,
                    padding:'4px 8px', borderRadius:4,
                    background:'rgba(0,181,226,.14)', color:'var(--lh-cyan)',
                    border:'1px solid rgba(0,181,226,.3)',
                  }}>
                    <span style={{width:6, height:6, borderRadius:3, background:'var(--lh-cyan)', boxShadow:'0 0 0 3px rgba(0,181,226,.22)'}}/>
                    En vivo
                  </span>
                </div>
                <div>
                  <LevelChip level={p.level} size={22} withLabel/>
                </div>
                <div>
                  <div style={{fontSize:13, color:'var(--fg-muted)', marginBottom:6, display:'flex', justifyContent:'space-between'}}>
                    <span>{isFull ? 'Completo' : `${remaining} plazas libres`}</span>
                    <span className="tnum" style={{fontFamily:'var(--font-mono)', fontSize:12}}>{c.spots}/{c.total}</span>
                  </div>
                  <div style={{
                    height:4, background:'var(--bg-muted)', borderRadius:2, overflow:'hidden',
                  }}>
                    <div style={{
                      width:`${pct}%`, height:'100%',
                      background: isFull ? 'var(--danger)' : pct > 80 ? 'var(--warning)' : lc,
                    }}/>
                  </div>
                </div>
                <div className="tnum" style={{fontSize:13, color:'var(--fg)', fontWeight:600, fontFamily:'var(--font-mono)'}}>
                  {c.dates}
                </div>
                <div style={{display:'flex', justifyContent:'flex-end'}}>
                  <Button
                    variant={isFull ? 'secondary' : 'primary'}
                    size="sm"
                    iconAfter={isFull ? null : 'arrow'}
                    disabled={isFull}
                    href={isFull ? null : '#inscripcion'}>
                    {isFull ? 'Lista de espera' : 'Preinscribir'}
                  </Button>
                </div>
              </div>
            );
          })}
        </div>

        {/* Async follow-on band */}
        <div style={{
          marginTop:16, padding:'18px 24px', borderRadius:12,
          background:'#fff', border:'1px dashed var(--border-strong)',
          display:'flex', alignItems:'center', gap:16, flexWrap:'wrap',
        }}>
          <div style={{
            width:42, height:42, borderRadius:10, flexShrink:0,
            background:'var(--bg-subtle)', border:'1px solid var(--border)',
            display:'flex', alignItems:'center', justifyContent:'center',
            color:'var(--lh-navy)',
          }}>
            <Icon name="clock" size={18}/>
          </div>
          <div style={{flex:1, minWidth:240}}>
            <div style={{fontSize:14, fontWeight:700, color:'var(--fg)'}}>
              Desde 2027 — ediciones asíncronas <span style={{color:'var(--fg-muted)', fontWeight:500}}>· a tu ritmo</span>
            </div>
            <div style={{fontSize:13, color:'var(--fg-muted)', marginTop:2}}>
              Tras la edición en vivo de cada programa, el contenido queda disponible en formato asíncrono con tutorías programadas. Mismo precio, mismo certificado firmado por Lean Hydrogen.
            </div>
          </div>
          <Button variant="tertiary" iconAfter="arrow" href="#inscripcion">Avísame cuando abra</Button>
        </div>

        {/* In-company / ad-hoc training band */}
        <div style={{
          marginTop:12, padding:'22px 28px', borderRadius:14,
          background:'var(--lh-navy)', color:'#fff', position:'relative', overflow:'hidden',
          display:'grid', gridTemplateColumns:'auto 1fr auto', alignItems:'center', gap:24,
        }}>
          {/* faint blueprint */}
          <div aria-hidden style={{
            position:'absolute', inset:0,
            backgroundImage:'linear-gradient(rgba(255,255,255,.05) 1px,transparent 1px),linear-gradient(90deg,rgba(255,255,255,.05) 1px,transparent 1px)',
            backgroundSize:'32px 32px',
            maskImage:'radial-gradient(ellipse at 90% 50%, #000 30%, transparent 75%)',
          }}/>
          <div style={{
            position:'relative',
            width:48, height:48, borderRadius:10, flexShrink:0,
            background:'rgba(0,181,226,.15)', border:'1px solid rgba(0,181,226,.35)',
            color:'var(--lh-cyan)',
            display:'flex', alignItems:'center', justifyContent:'center',
          }}>
            <Icon name="factory" size={22}/>
          </div>
          <div style={{position:'relative', minWidth:0}}>
            <div style={{
              fontFamily:'var(--font-mono)', fontSize:11, letterSpacing:'.14em',
              color:'var(--lh-cyan)', textTransform:'uppercase', marginBottom:6,
            }}>// Formación in-company</div>
            <div style={{fontSize:18, fontWeight:700, color:'#fff', letterSpacing:'-0.01em', marginBottom:4}}>
              Diseñamos programas a medida para tu empresa.
            </div>
            <div style={{fontSize:13, color:'rgba(255,255,255,.7)', lineHeight:1.55, maxWidth:680}}>
              Combinamos módulos del catálogo o construimos un itinerario ad-hoc sobre tus casos reales — electrolizadores, SAF, amoníaco, metanol. En vuestras oficinas, online o híbrido. Bonificable FUNDAE.
            </div>
          </div>
          <div style={{position:'relative', display:'flex', flexDirection:'column', gap:8, alignItems:'stretch'}}>
            <Button variant="cyan" size="sm" iconAfter="arrow" href="mailto:secretaria@escueladeprotones.com?subject=Formaci%C3%B3n%20in-company">
              Solicitar propuesta
            </Button>
            <a href="mailto:secretaria@escueladeprotones.com" style={{
              fontFamily:'var(--font-mono)', fontSize:11, color:'rgba(255,255,255,.65)',
              textDecoration:'none', textAlign:'center',
            }}>secretaria@escueladeprotones.com</a>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ========================================
   Apply / contact
   ======================================== */
function ApplySection() {
  const [submitted, setSubmitted] = useStateFA(false);
  const [sending, setSending]     = useStateFA(false);
  const [error, setError]         = useStateFA(null);
  const [form, setForm] = useStateFA({
    name:'', email:'', company:'', role:'',
    program:'', message:'', track:'reservar',
    privacy: false,
  });

  const update = (k) => (e) => setForm(prev => ({...prev, [k]: e.target.value}));
  const trackLabel = {reservar:'Preinscripción', corporativo:'Reserva corporativa', info:'Más información'};

  async function handleSubmit(e) {
    e.preventDefault();
    setError(null);

    // Fail loudly if the endpoint hasn't been wired yet.
    if (FORMSPREE_ENDPOINT.indexOf('YOUR_FORM_ID') !== -1) {
      setError('Form endpoint no configurado. Edita FORMSPREE_ENDPOINT en sections-end.jsx.');
      return;
    }

    setSending(true);
    const programLabel = form.program === 'multiple'
      ? 'Varios — necesita asesoramiento'
      : (PROGRAMS.find(p => p.id === form.program) || {});
    const programText = typeof programLabel === 'string'
      ? programLabel
      : (programLabel.code ? programLabel.code + ' · ' + programLabel.title : form.program);

    try {
      const res = await fetch(FORMSPREE_ENDPOINT, {
        method: 'POST',
        headers: { 'Accept': 'application/json' },
        body: new URLSearchParams({
          'Nombre':       form.name,
          'Email':        form.email,
          'Empresa':      form.company,
          'Cargo':        form.role,
          'Programa':     programText,
          'Mensaje':      form.message,
          'Tipo':         trackLabel[form.track] || form.track,
          '_subject':     'Escuela de Protones — ' + (trackLabel[form.track] || 'Solicitud') + ' (' + form.name + ')',
          '_replyto':     form.email,
        }),
      });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        throw new Error(
          (data.errors && data.errors.map(e => e.message).join(', ')) ||
          'No hemos podido enviar tu solicitud. Inténtalo de nuevo en unos minutos o escríbenos a secretaria@escueladeprotones.com.'
        );
      }
      setSubmitted(true);
    } catch (err) {
      setError(err.message || 'Error de red. Inténtalo de nuevo.');
    } finally {
      setSending(false);
    }
  }

  return (
    <section id="inscripcion" style={{
      padding:'120px 0', background:'var(--lh-navy)', color:'#fff',
      position:'relative', overflow:'hidden',
    }}>
      <div style={{
        position:'absolute', inset:0,
        backgroundImage:'linear-gradient(rgba(255,255,255,.04) 1px,transparent 1px),linear-gradient(90deg,rgba(255,255,255,.04) 1px,transparent 1px)',
        backgroundSize:'48px 48px',
        maskImage:'radial-gradient(ellipse at 30% 50%, #000 30%, transparent 75%)',
      }}/>

      <div className="container" style={{
        position:'relative', display:'grid', gridTemplateColumns:'1fr 1fr', gap:80,
      }}>
        <div>
          <div style={{
            fontFamily:'var(--font-mono)', fontSize:12, letterSpacing:'.14em',
            color:'var(--lh-cyan)', textTransform:'uppercase', marginBottom:14,
          }}>// Preinscripción abierta</div>
          <h2 style={{margin:'0 0 24px', fontSize:52, lineHeight:1.02, letterSpacing:'-0.025em', color:'#fff'}}>
            Reserva tu plaza para la edición en vivo de Q4 2026.
          </h2>
          <p style={{fontSize:18, lineHeight:1.55, color:'rgba(255,255,255,.78)', margin:'0 0 36px', maxWidth:460}}>
            Cuéntanos qué programa te interesa. El equipo te confirma disponibilidad, condiciones y fechas en menos de 48 horas hábiles.
          </p>

          <div style={{
            display:'flex', flexDirection:'column', gap:18,
            padding:'24px 28px', borderRadius:14,
            background:'rgba(255,255,255,.04)', border:'1px solid rgba(255,255,255,.1)',
            maxWidth:460,
          }}>
            {[
              { icon:'mail', label:'Correo de admisiones', value:'secretaria@escueladeprotones.com' },
              { icon:'calendar', label:'Lanzamiento', value:'Octubre 2026 — preinscripción ya abierta' },
              { icon:'users', label:'Reservas corporativas', value:'A partir de 3 plazas — condiciones especiales' },
              { icon:'euro',  label:'Bonificable FUNDAE',   value:'Empresas: 100 % gestionable como formación bonificada. Tramitamos la solicitud.' },
            ].map(it=>(
              <div key={it.label} style={{display:'flex', gap:14, alignItems:'flex-start'}}>
                <div style={{
                  width:34, height:34, borderRadius:8,
                  background:'rgba(0,181,226,.14)', color:'var(--lh-cyan)',
                  border:'1px solid rgba(0,181,226,.3)',
                  display:'flex',alignItems:'center',justifyContent:'center', flexShrink:0,
                }}>
                  <Icon name={it.icon} size={15}/>
                </div>
                <div>
                  <div style={{
                    fontFamily:'var(--font-mono)', fontSize:10, letterSpacing:'.14em',
                    color:'rgba(255,255,255,.55)', textTransform:'uppercase', marginBottom:2,
                  }}>{it.label}</div>
                  <div style={{fontSize:14, color:'#fff'}}>{it.value}</div>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Form */}
        <div style={{
          background:'#fff', color:'var(--fg)', borderRadius:16,
          padding:36, boxShadow:'0 24px 64px rgba(0,0,0,.18)',
        }}>
          {submitted ? (
            <div style={{textAlign:'center', padding:'48px 0'}}>
              <div style={{
                width:64, height:64, borderRadius:'50%',
                background:'var(--success-bg)', color:'var(--success)',
                display:'inline-flex', alignItems:'center', justifyContent:'center',
                marginBottom:20,
              }}>
                <Icon name="check" size={28} stroke={2.4}/>
              </div>
              <h3 style={{margin:'0 0 8px'}}>Solicitud recibida</h3>
              <p style={{color:'var(--fg-muted)', maxWidth:340, margin:'0 auto'}}>
                Te contactaremos en menos de 48 horas hábiles para confirmar la plaza.
              </p>
              <Button variant="tertiary" onClick={()=>setSubmitted(false)} style={{marginTop:16}}>
                Enviar otra solicitud
              </Button>
            </div>
          ) : (
            <form onSubmit={handleSubmit} noValidate>
              <div style={{
                display:'inline-flex', background:'var(--bg-subtle)', borderRadius:10,
                padding:4, border:'1px solid var(--border)', gap:2, marginBottom:24,
              }}>
                {[
                  ['reservar','Preinscripción'],
                  ['corporativo','Reserva corporativa'],
                  ['info','Más información'],
                ].map(([k,label])=>(
                  <button key={k} type="button" onClick={()=>setForm(f=>({...f, track:k}))} style={{
                    background: form.track===k ? '#fff' : 'transparent',
                    border:0, padding:'7px 12px', borderRadius:7, cursor:'pointer',
                    fontFamily:'inherit', fontSize:12, fontWeight:600,
                    color: form.track===k ? 'var(--fg)' : 'var(--fg-muted)',
                    boxShadow: form.track===k ? 'var(--shadow-xs)' : 'none',
                  }}>{label}</button>
                ))}
              </div>

              <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:16}}>
                <FormField label="Nombre completo" name="name" value={form.name} onChange={update('name')} required/>
                <FormField label="Correo profesional" name="email" type="email" value={form.email} onChange={update('email')} required/>
                <FormField label="Empresa" name="company" value={form.company} onChange={update('company')}/>
                <FormField label="Cargo" name="role" value={form.role} onChange={update('role')}/>
                <div style={{gridColumn:'span 2'}}>
                  <FormSelect label="Programa de interés" name="program" value={form.program} onChange={update('program')} required>
                    <option value="">Selecciona un programa…</option>
                    {PROGRAMS.map(p=>(
                      <option key={p.id} value={p.id}>{p.code} · {p.title}</option>
                    ))}
                    <option value="multiple">Varios — necesito asesoramiento</option>
                  </FormSelect>
                </div>
                <div style={{gridColumn:'span 2'}}>
                  <FormField as="textarea" name="message" label="Cuéntanos sobre tu proyecto" placeholder="Necesidad formativa, equipo, calendario tentativo…" value={form.message} onChange={update('message')} rows={3}/>
                </div>
              </div>

              <label style={{
                marginTop:16, display:'flex', alignItems:'flex-start', gap:10,
                fontSize:12, color:'var(--fg-muted)', cursor:'pointer', lineHeight:1.5,
              }}>
                <input
                  type="checkbox"
                  checked={form.privacy}
                  onChange={(e)=>setForm(f=>({...f, privacy:e.target.checked}))}
                  required
                  style={{
                    marginTop:2, accentColor:'var(--lh-navy)',
                    width:14, height:14, flexShrink:0, cursor:'pointer',
                  }}/>
                <span>
                  Acepto la <a href="politica-privacidad.html" target="_blank" rel="noopener" style={{color:'var(--lh-blue)', fontWeight:600}}>política de privacidad</a> y el tratamiento de mis datos para gestionar esta solicitud.
                </span>
              </label>

              {error && (
                <div role="alert" style={{
                  marginTop:16, padding:'12px 14px', borderRadius:8,
                  background:'var(--danger-bg)', border:'1px solid rgba(192,57,43,.25)',
                  color:'var(--danger)', fontSize:13, lineHeight:1.5,
                  display:'flex', gap:10, alignItems:'flex-start',
                }}>
                  <Icon name="x" size={14} stroke={2.4}/>
                  <span>{error}</span>
                </div>
              )}

              <div style={{display:'flex', gap:12, marginTop:24}}>
                <Button type="submit" variant="primary" size="lg" iconAfter={sending ? null : 'arrow'} full disabled={sending}>
                  {sending ? 'Enviando…' : 'Enviar solicitud'}
                </Button>
              </div>
            </form>
          )}
        </div>
      </div>
    </section>
  );
}

function FormField({ label, as = 'input', type='text', required, placeholder, rows, value, onChange, name }) {
  const [focus, setFocus] = useStateFA(false);
  const sharedStyle = {
    width:'100%', boxSizing:'border-box',
    padding:'12px 14px',
    fontFamily:'inherit', fontSize:14, color:'var(--fg)',
    background:'#fff',
    border:`1px solid ${focus ? 'var(--accent)' : 'var(--border)'}`,
    boxShadow: focus ? 'var(--shadow-focus)' : 'none',
    borderRadius:8, outline:'none',
    transition:'all 160ms cubic-bezier(.2,.8,.2,1)',
    resize: as === 'textarea' ? 'vertical' : 'none',
  };
  return (
    <label style={{display:'block'}}>
      <div style={{
        fontSize:12, fontWeight:600, color:'var(--fg-muted)',
        marginBottom:6, letterSpacing:'.02em',
      }}>{label}{required && <span style={{color:'var(--danger)'}}> *</span>}</div>
      {as === 'textarea' ? (
        <textarea name={name} value={value} onChange={onChange} required={required} placeholder={placeholder} rows={rows||3}
          onFocus={()=>setFocus(true)} onBlur={()=>setFocus(false)} style={sharedStyle}/>
      ) : (
        <input name={name} type={type} value={value} onChange={onChange} required={required} placeholder={placeholder}
          onFocus={()=>setFocus(true)} onBlur={()=>setFocus(false)} style={sharedStyle}/>
      )}
    </label>
  );
}

function FormSelect({ label, required, value, onChange, children, name }) {
  const [focus, setFocus] = useStateFA(false);
  return (
    <label style={{display:'block'}}>
      <div style={{
        fontSize:12, fontWeight:600, color:'var(--fg-muted)',
        marginBottom:6, letterSpacing:'.02em',
      }}>{label}{required && <span style={{color:'var(--danger)'}}> *</span>}</div>
      <div style={{position:'relative'}}>
        <select name={name} value={value} onChange={onChange} required={required}
          onFocus={()=>setFocus(true)} onBlur={()=>setFocus(false)}
          style={{
            width:'100%', boxSizing:'border-box',
            padding:'12px 36px 12px 14px', appearance:'none',
            fontFamily:'inherit', fontSize:14, color: value ? 'var(--fg)' : 'var(--fg-subtle)',
            background:'#fff',
            border:`1px solid ${focus ? 'var(--accent)' : 'var(--border)'}`,
            boxShadow: focus ? 'var(--shadow-focus)' : 'none',
            borderRadius:8, outline:'none',
            transition:'all 160ms cubic-bezier(.2,.8,.2,1)',
          }}>
          {children}
        </select>
        <div style={{
          position:'absolute', right:12, top:'50%', transform:'translateY(-50%)',
          pointerEvents:'none', color:'var(--fg-muted)',
        }}>
          <Icon name="chevron" size={16}/>
        </div>
      </div>
    </label>
  );
}

/* ========================================
   Footer
   ======================================== */
function Footer() {
  return (
    <footer style={{
      background:'#0F1722', color:'rgba(255,255,255,.65)',
      padding:'64px 0 32px',
    }}>
      <div className="container">
        <div style={{
          display:'grid', gridTemplateColumns:'2fr 1fr 1fr 1fr', gap:48, marginBottom:48,
        }}>
          <div>
            <EPMark height={28} color="#fff" accent="var(--lh-cyan)" variant="white"/>
            <p style={{
              marginTop:20, fontSize:14, lineHeight:1.6,
              color:'rgba(255,255,255,.55)', maxWidth:340,
            }}>
              La academia virtual de Lean Hydrogen. Formación técnica especializada en hidrógeno renovable, desde la planta real.
            </p>

            <a href="https://escueladeprotones.com" target="_blank" rel="noopener" style={{
              display:'inline-flex', alignItems:'center', gap:8, marginTop:18,
              fontFamily:'var(--font-mono)', fontSize:12, letterSpacing:'.02em',
              color:'var(--lh-cyan)', textDecoration:'none',
            }}>
              <span aria-hidden style={{width:5, height:5, borderRadius:3, background:'var(--lh-cyan)', boxShadow:'0 0 0 3px rgba(0,181,226,.18)'}}/>
              escueladeprotones.com
            </a>
            <div style={{
              marginTop:24, display:'flex', alignItems:'center', gap:14,
              padding:'12px 16px', borderRadius:10,
              background:'rgba(255,255,255,.04)', border:'1px solid rgba(255,255,255,.08)',
              maxWidth:340,
            }}>
              <span style={{
                fontFamily:'var(--font-mono)', fontSize:10, letterSpacing:'.14em',
                color:'rgba(255,255,255,.5)', textTransform:'uppercase',
              }}>by</span>
              <Logo variant="white" height={20}/>
            </div>
          </div>

          {[
            ['Programas', [
              ['Introducción al H₂ renovable', '#p1'],
              ['Pre-diseño de instalaciones', '#p2'],
              ['Financiación de proyectos', '#p3'],
              ['Seguridad industrial para plantas de H₂', '#p4'],
              ['Diseño de electrolizadores', '#p5'],
              ['Operación y mantenimiento', '#p6'],
            ]],
            ['Recursos', [
              ['Calendario 2026', '#calendario'],
              ['Metodología', '#metodologia'],
              ['Niveles formativos', '#niveles'],
              ['Dossier (PDF)', '#detalle'],
            ]],
            ['Lean Hydrogen', [
              ['Ingeniería', 'https://leanhydrogen.com'],
              ['Consultoría', 'https://leanhydrogen.com'],
              ['I+D', 'https://leanhydrogen.com'],
              ['Contacto', '#inscripcion'],
            ]],
          ].map(([title, links])=>(
            <div key={title}>
              <div style={{
                fontFamily:'var(--font-mono)', fontSize:11, letterSpacing:'.14em',
                color:'rgba(255,255,255,.5)', textTransform:'uppercase', marginBottom:18,
              }}>{title}</div>
              <ul style={{listStyle:'none', padding:0, margin:0, display:'flex', flexDirection:'column', gap:10}}>
                {links.map(([label, href])=>(
                  <li key={label}>
                    <a href={href} style={{
                      color:'rgba(255,255,255,.75)', textDecoration:'none', fontSize:14,
                    }}
                    onMouseEnter={e=>e.currentTarget.style.color='#fff'}
                    onMouseLeave={e=>e.currentTarget.style.color='rgba(255,255,255,.75)'}
                    >{label}</a>
                  </li>
                ))}
              </ul>
            </div>
          ))}
        </div>

        <div style={{
          paddingTop:24, borderTop:'1px solid rgba(255,255,255,.08)',
          display:'flex', justifyContent:'space-between', alignItems:'center', gap:24, flexWrap:'wrap',
          fontSize:13, color:'rgba(255,255,255,.45)',
        }}>
          <div style={{display:'flex',gap:24,flexWrap:'wrap'}}>
            <span>© 2026 The Lean Hydrogen Company S.L.U.</span>
            <a href="aviso-legal.html" style={{color:'inherit'}}>Aviso legal</a>
            <a href="politica-privacidad.html" style={{color:'inherit'}}>Privacidad</a>
            <a href="politica-cookies.html" style={{color:'inherit'}}>Cookies</a>
            <a href="#" onClick={(e)=>{e.preventDefault(); window.dispatchEvent(new Event('open-cookie-prefs'));}} style={{color:'inherit'}}>Gestionar cookies</a>
          </div>
          <div style={{display:'flex', gap:14, alignItems:'center'}}>
            <a href="https://www.linkedin.com/company/lean-hydrogen" target="_blank" rel="noopener" style={{color:'rgba(255,255,255,.55)'}} aria-label="LinkedIn"><Icon name="linkedin" size={18}/></a>
            <a href="mailto:secretaria@escueladeprotones.com" style={{color:'rgba(255,255,255,.55)'}} aria-label="Email"><Icon name="mail" size={18}/></a>
          </div>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { MethodologySection, CalendarSection, ApplySection, Footer });
