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

/* ========================================
   "Why" — problem statement
   ======================================== */
function WhySection() {
  return (
    <section id="por-que" style={{padding:'120px 0 96px', background:'var(--bg)'}}>
      <div className="container" style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:96, alignItems:'start'}}>
        <div>
          <Eyebrow>// Por qué nace Escuela de Protones</Eyebrow>
          <h2 style={{margin:'0 0 24px', fontSize:48, lineHeight:1.05, letterSpacing:'-0.02em'}}>
            El sector crece a velocidad de electrolizador. <span style={{color:'var(--fg-muted)'}}>La formación, no tanto.</span>
          </h2>
          <p style={{fontSize:18, lineHeight:1.6, color:'var(--fg-muted)', maxWidth:520, marginBottom:24}}>
            El hidrógeno renovable se acelera, pero existe una carencia crítica: formación técnica rigurosa basada en experiencia real de campo, no en presentaciones de proveedor.
          </p>
          <p style={{fontSize:18, lineHeight:1.6, color:'var(--fg-muted)', maxWidth:520, marginBottom:32}}>
            Los profesionales necesitan comprender no solo la teoría, sino la viabilidad técnica y económica de proyectos reales — desde el diseño conceptual hasta la operación diaria de la planta.
          </p>
          <Button variant="tertiary" iconAfter="arrow" href="#programas">Ver los seis programas</Button>
        </div>
        <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:16}}>
          {[
            {
              eyebrow:'01 · Diseño',
              title:'Ingeniería de detalle',
              body:'Datasheets reales, dimensionado conceptual y selección tecnológica defendible.',
              icon: 'factory',
            },
            {
              eyebrow:'02 · Comisionado',
              title:'Puesta en marcha',
              body:'Lecciones aprendidas en plantas auditadas: lo que falla, y por qué.',
              icon: 'bolt',
            },
            {
              eyebrow:'03 · Económico',
              title:'LCOH y sensibilidades',
              body:'El coste nivelado como brújula: qué palancas mueven la viabilidad.',
              icon: 'chart',
            },
            {
              eyebrow:'04 · Operación',
              title:'Día a día de planta',
              body:'Curvas de polarización, mantenimiento predictivo, respuesta a desviaciones.',
              icon: 'wrench',
            },
          ].map((c)=>(
            <Card key={c.title} padding={20} hover style={{height:'100%'}}>
              <div style={{
                width:36,height:36,borderRadius:8,
                background:'var(--bg-muted)',
                display:'flex',alignItems:'center',justifyContent:'center',
                color:'var(--lh-navy)', marginBottom:14,
              }}>
                <Icon name={c.icon} size={18}/>
              </div>
              <div style={{
                fontFamily:'var(--font-mono)', fontSize:11, letterSpacing:'.12em',
                color:'var(--fg-muted)', textTransform:'uppercase', marginBottom:8,
              }}>{c.eyebrow}</div>
              <div style={{fontSize:16, fontWeight:600, color:'var(--fg)', marginBottom:6}}>{c.title}</div>
              <div style={{fontSize:14, color:'var(--fg-muted)', lineHeight:1.5}}>{c.body}</div>
            </Card>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ========================================
   Levels framework
   ======================================== */
function LevelsSection() {
  return (
    <section id="niveles" style={{padding:'96px 0', background:'var(--bg-subtle)'}}>
      <div className="container">
        <div style={{maxWidth:760, marginBottom:56}}>
          <Eyebrow>// Estructura de niveles formativos</Eyebrow>
          <h2 style={{margin:'0 0 20px', fontSize:44, lineHeight:1.05, letterSpacing:'-0.02em'}}>
            Tres niveles, una progresión escalonada.
          </h2>
          <p className="lead" style={{margin:0}}>
            De los fundamentos del ecosistema hasta el diseño y la operación de electrolizadores en planta. Cada nivel se identifica con un código tipográfico — <span style={{fontFamily:'var(--font-mono)', fontStyle:'italic'}}>(i)</span>, <span style={{fontFamily:'var(--font-mono)', fontStyle:'italic'}}>(a)</span>, <span style={{fontFamily:'var(--font-mono)', fontStyle:'italic'}}>(e)</span> — presente en todo el catálogo.
          </p>
        </div>

        <div style={{display:'grid', gridTemplateColumns:'repeat(3, 1fr)', gap:20}}>
          {LEVELS.map((l, idx)=>(
            <div key={l.code} style={{
              background:'#fff', border:'1px solid var(--border)', borderRadius:16,
              padding:'32px 28px', position:'relative', overflow:'hidden',
              minHeight: 360,
              display:'flex', flexDirection:'column',
            }}>
              {/* Accent rule */}
              <div style={{
                position:'absolute', left:0, top:0, bottom:0, width:4,
                background: l.color,
              }}/>
              {/* Level number large in BG */}
              <div style={{
                position:'absolute', right:24, top:18,
                fontFamily:'var(--font-display)', fontSize:120,
                fontStyle:'italic', fontWeight:300,
                color: l.bgTint, lineHeight:1, letterSpacing:'-0.04em',
                pointerEvents:'none',
              }}>
                {l.code}
              </div>

              <div style={{display:'flex', alignItems:'center', gap:12, marginBottom:20, position:'relative'}}>
                <LevelChip level={l.code} size={32}/>
                <div style={{
                  fontFamily:'var(--font-mono)', fontSize:11, letterSpacing:'.14em',
                  textTransform:'uppercase', color:'var(--fg-muted)',
                }}>nivel · 0{idx+1}</div>
              </div>

              <h3 style={{margin:'0 0 6px', fontSize:24, position:'relative'}}>{l.name}</h3>
              <div style={{
                fontSize:13, color: l.color, fontWeight:600, marginBottom:18,
                fontStyle:'italic', position:'relative',
              }}>{l.tag}</div>

              <p style={{margin:'0 0 24px', fontSize:15, color:'var(--fg-muted)', lineHeight:1.55, position:'relative'}}>
                {l.description}
              </p>

              <div style={{marginTop:'auto', position:'relative'}}>
                <div style={{
                  fontSize:11, letterSpacing:'.12em', textTransform:'uppercase',
                  fontFamily:'var(--font-mono)', color:'var(--fg-subtle)', marginBottom:8,
                }}>Para quién</div>
                <div style={{fontSize:13, color:'var(--fg)', lineHeight:1.5}}>{l.forWhom}</div>
              </div>

              <div style={{
                marginTop:24, paddingTop:20,
                borderTop:'1px solid var(--border)',
                display:'flex', justifyContent:'space-between', alignItems:'center',
                position:'relative',
              }}>
                <div style={{fontSize:13, color:'var(--fg-muted)'}}>
                  {PROGRAMS.filter(p=>p.level===l.code).length} programa{PROGRAMS.filter(p=>p.level===l.code).length>1?'s':''}
                </div>
                <a href={`#programas`} style={{
                  fontSize:13, fontWeight:600, color:l.color,
                  display:'inline-flex', alignItems:'center', gap:4,
                }}>
                  Ver programas <Icon name="arrow" size={12}/>
                </a>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ========================================
   Program catalog
   ======================================== */
function ProgramsSection({ cardStyle = 'level-bar', layout = 'grid' }) {
  const [filter, setFilter] = useStateLP('all');

  const filtered = filter === 'all' ? PROGRAMS : PROGRAMS.filter(p => p.level === filter);

  return (
    <section id="programas" style={{padding:'120px 0', background:'var(--bg)'}}>
      <div className="container">
        <div style={{
          display:'flex', justifyContent:'space-between', alignItems:'flex-end',
          gap:48, marginBottom:48, flexWrap:'wrap',
        }}>
          <div style={{maxWidth:680}}>
            <Eyebrow>// Catálogo de programas</Eyebrow>
            <h2 style={{margin:'0 0 16px', fontSize:48, lineHeight:1.04, letterSpacing:'-0.02em'}}>
              Seis programas. Toda la cadena de valor del H₂ verde.
            </h2>
            <p className="lead" style={{margin:0}}>
              Cada programa se imparte en formato intensivo de <strong>3 días consecutivos × 4 h/día — de 16:00 a 20:00 h</strong>, con un máximo de 30 alumnos por edición. Teoría aplicada y casos reales auditados.
            </p>
          </div>

          {/* Filter pills */}
          <div style={{
            display:'inline-flex', background:'var(--bg-subtle)', borderRadius:10,
            padding:4, border:'1px solid var(--border)', gap:2,
          }}>
            {[
              ['all','Todos', null],
              ['i','Intro', 'i'],
              ['a','Avanzado', 'a'],
              ['e','Experto', 'e'],
            ].map(([k,label,lvl])=>(
              <button key={k} onClick={()=>setFilter(k)} style={{
                background: filter===k ? '#fff' : 'transparent',
                border:0, padding:'8px 14px', borderRadius:8, cursor:'pointer',
                fontFamily:'inherit', fontSize:13, fontWeight:600,
                color: filter===k ? 'var(--fg)' : 'var(--fg-muted)',
                boxShadow: filter===k ? 'var(--shadow-xs)' : 'none',
                display:'inline-flex', alignItems:'center', gap:8,
                transition:'all 200ms cubic-bezier(.2,.8,.2,1)',
              }}>
                {lvl && <span style={{
                  fontFamily:'var(--font-mono)', fontStyle:'italic',
                  fontSize:12, color: filter===k ? 'var(--lh-blue)' : 'var(--fg-subtle)',
                }}>({lvl})</span>}
                {label}
              </button>
            ))}
          </div>
        </div>

        {layout === 'grid' ? (
          <div style={{display:'grid', gridTemplateColumns:'repeat(3, 1fr)', gap:24}}>
            {filtered.map(p => <ProgramCard key={p.id} p={p} variant={cardStyle}/>)}
          </div>
        ) : (
          <div style={{display:'flex', flexDirection:'column', gap:12}}>
            {filtered.map(p => <ProgramRow key={p.id} p={p}/>)}
          </div>
        )}
      </div>
    </section>
  );
}

/* Program card — grid view */
function ProgramCard({ p, variant = 'level-bar' }) {
  const [hover, setHover] = useStateLP(false);
  const levelColor =
    p.level === 'i' ? 'var(--lh-cyan)' :
    p.level === 'a' ? 'var(--lh-blue)' : '#9A9F00';

  return (
    <a href={`#${p.id}`} id={p.id}
       onMouseEnter={()=>setHover(true)} onMouseLeave={()=>setHover(false)}
       style={{
         display:'block', textDecoration:'none', color:'inherit',
         background:'#fff', border:'1px solid var(--border)', borderRadius:16,
         padding:0, overflow:'hidden', position:'relative',
         boxShadow: hover
           ? '0 12px 32px rgba(0,26,112,.08), 0 4px 12px rgba(0,26,112,.05)'
           : '0 1px 2px rgba(0,26,112,.04)',
         transform: hover ? 'translateY(-2px)' : 'none',
         transition:'all 200ms cubic-bezier(.2,.8,.2,1)',
       }}>
      {variant === 'level-bar' && (
        <div style={{height:4, background: levelColor}}/>
      )}
      <div style={{padding:'28px 26px 24px'}}>
        <div style={{
          display:'flex', justifyContent:'space-between', alignItems:'flex-start',
          marginBottom:20,
        }}>
          <div style={{
            width:44, height:44, borderRadius:10, background:'var(--bg-muted)',
            display:'flex', alignItems:'center', justifyContent:'center',
            color: 'var(--lh-navy)',
          }}>
            <Icon name={p.icon} size={22}/>
          </div>
          <div style={{display:'flex', flexDirection:'column', alignItems:'flex-end', gap:6}}>
            <LevelChip level={p.level} size={26}/>
            <div style={{
              fontFamily:'var(--font-mono)', fontSize:11, letterSpacing:'.08em',
              color:'var(--fg-subtle)',
            }}>{p.code}</div>
          </div>
        </div>

        <h3 style={{margin:'0 0 4px', fontSize:20, lineHeight:1.2}}>{p.title}</h3>
        <div style={{
          fontSize:13, color:'var(--fg-muted)', marginBottom:18, fontStyle:'italic',
        }}>{p.subtitle}</div>

        <p style={{
          fontSize:14, color:'var(--fg-muted)', margin:'0 0 24px', lineHeight:1.55,
          minHeight: 84,
        }}>{p.summary}</p>

        <div style={{
          display:'grid', gridTemplateColumns:'1fr 1fr', gap:0,
          borderTop:'1px solid var(--border)', paddingTop:18, marginTop:'auto',
        }}>
          <div>
            <div style={{
              fontSize:10, letterSpacing:'.14em', textTransform:'uppercase',
              fontFamily:'var(--font-mono)', color:'var(--fg-subtle)', marginBottom:4,
            }}>Precio</div>
            <div className="tnum" style={{fontSize:18, fontWeight:700, color:'var(--fg)', letterSpacing:'-0.01em'}}>
              {eur(p.price)}
            </div>
          </div>
          <div>
            <div style={{
              fontSize:10, letterSpacing:'.14em', textTransform:'uppercase',
              fontFamily:'var(--font-mono)', color:'var(--fg-subtle)', marginBottom:4,
            }}>Formato</div>
            <div style={{fontSize:14, fontWeight:600, color:'var(--fg)', display:'flex', alignItems:'center', gap:6}}>
              <Icon name="clock" size={13}/> {p.duration}
            </div>
          </div>
        </div>

        <div style={{
          marginTop:16, display:'flex', justifyContent:'space-between', alignItems:'center',
        }}>
          <div style={{fontSize:12, color:'var(--fg-subtle)', display:'inline-flex', alignItems:'center', gap:6}}>
            <Icon name="users" size={13}/> Máx. {p.capacity} alumnos
          </div>
          <div style={{
            fontSize:13, fontWeight:600, color: levelColor,
            display:'inline-flex', alignItems:'center', gap:4,
          }}>
            Ver programa <Icon name="arrow" size={12}/>
          </div>
        </div>
      </div>
    </a>
  );
}

/* Program row — list view */
function ProgramRow({ p }) {
  const [hover, setHover] = useStateLP(false);
  const levelColor =
    p.level === 'i' ? 'var(--lh-cyan)' :
    p.level === 'a' ? 'var(--lh-blue)' : '#9A9F00';
  return (
    <a href={`#${p.id}`} id={p.id}
       onMouseEnter={()=>setHover(true)} onMouseLeave={()=>setHover(false)}
       style={{
         display:'grid',
         gridTemplateColumns:'56px 80px 1fr 200px 120px 140px 40px',
         alignItems:'center', gap:20,
         padding:'18px 24px',
         background: hover ? 'var(--bg-subtle)' : '#fff',
         border:'1px solid var(--border)', borderRadius:12,
         textDecoration:'none', color:'inherit',
         transition:'all 160ms cubic-bezier(.2,.8,.2,1)',
       }}>
      <div style={{
        width:44, height:44, borderRadius:10, background:'var(--bg-muted)',
        display:'flex', alignItems:'center', justifyContent:'center', color:'var(--lh-navy)',
      }}>
        <Icon name={p.icon} size={20}/>
      </div>
      <div style={{
        fontFamily:'var(--font-mono)', fontSize:12, color:'var(--fg-subtle)', letterSpacing:'.06em',
      }}>{p.code}</div>
      <div>
        <div style={{fontWeight:600, fontSize:16, marginBottom:2}}>{p.title}</div>
        <div style={{fontSize:13, color:'var(--fg-muted)'}}>{p.subtitle}</div>
      </div>
      <div>
        <LevelChip level={p.level} size={22} withLabel/>
      </div>
      <div style={{fontSize:13, color:'var(--fg-muted)', display:'flex', alignItems:'center', gap:6}}>
        <Icon name="clock" size={13}/> {p.duration}
      </div>
      <div className="tnum" style={{fontSize:16, fontWeight:700, color:'var(--fg)'}}>{eur(p.price)}</div>
      <div style={{color: levelColor}}>
        <Icon name="arrowDown" size={18} stroke={2}/>
      </div>
    </a>
  );
}

Object.assign(window, { WhySection, LevelsSection, ProgramsSection });
