// diag-steps.jsx — Pantallas del flujo: Intro, EjeStep, MetasStep, DatosStep.

const CheckIcon = () => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3.4"
       strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
);

function EjeFloaters({ ejeKey }) {
  const inner = window.DIAG_EJE_ICONS[ejeKey] || '';
  const spots = [
    { top: '4%',  left: '6%',  size: 30, dur: '7s',  delay: '0s',   op: 0.10 },
    { top: '20%', left: '90%', size: 22, dur: '9s',  delay: '-2s',  op: 0.08 },
    { top: '64%', left: '3%',  size: 26, dur: '8s',  delay: '-4s',  op: 0.07 },
    { top: '82%', left: '84%', size: 34, dur: '10s', delay: '-1s',  op: 0.09 },
    { top: '46%', left: '50%', size: 18, dur: '11s', delay: '-3s',  op: 0.05 },
  ];
  return (
    <div className="eje-floaters" aria-hidden="true">
      {spots.map((s, i) => (
        <span key={i} className="eje-floater"
              style={{ top: s.top, left: s.left, width: s.size, height: s.size,
                       opacity: s.op, animationDuration: s.dur, animationDelay: s.delay }}>
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"
               strokeLinecap="round" strokeLinejoin="round"
               dangerouslySetInnerHTML={{ __html: inner }} />
        </span>
      ))}
    </div>
  );
}

function ejeBgSrc(key) {
  const map = {
    enfoque: window.NL_ENFOQUE_BG || 'assets/enfoque-bg-web.jpg',
    integracion: window.NL_INTEGRACION_BG || 'assets/integracion-bg-web.jpg',
  };
  return map[key] || '';
}

/* ------------------------------------------------------------------ INTRO */
function Intro({ onStart }) {
  return (
    <section className="intro diag-fade">
      <div className="intro-copy">
        <div className="intro-eyebrow"><span className="dot" /> Diagnóstico · The Next Level 360</div>
        <h1 className="intro-title">
          ¿En qué nivel<br/>estás <em>hoy
            <svg className="brush" viewBox="0 0 300 24" preserveAspectRatio="none" aria-hidden="true">
              <path d="M6 15 C 90 5, 210 5, 294 12" stroke="#E4042C" strokeWidth="7" strokeLinecap="round" fill="none"/>
            </svg>
          </em>?
        </h1>
        <p className="intro-sub">
          Un diagnóstico honesto de los <strong>8 ejes</strong> de The Next Level 360.
          Responde <strong>40 afirmaciones</strong>, define a dónde quieres llegar y recibe
          tu mapa de partida con el <strong>curso recomendado</strong> para tu siguiente nivel.
        </p>
        <div className="intro-meta">
          <div className="mi"><div className="mi-num">8</div><div className="mi-label">Ejes</div></div>
          <div className="mi"><div className="mi-num">40</div><div className="mi-label">Afirmaciones</div></div>
          <div className="mi"><div className="mi-num">±6</div><div className="mi-label">Minutos</div></div>
        </div>
        <div>
          <button className="diag-btn" onClick={onStart}>
            Comenzar diagnóstico <span className="arrow">→</span>
          </button>
        </div>
      </div>
      <div className="intro-avatar" aria-hidden="true">
        <div className="intro-avatar-glow" />
        <div className="intro-avatar-ring intro-avatar-ring--1" />
        <div className="intro-avatar-ring intro-avatar-ring--2" />
        <img className="intro-avatar-img" src={window.NL_AVATAR_THUMB || 'assets/coach-arturo-shrug.png'} alt="" />
        <div className="intro-avatar-badge intro-avatar-badge--face">
          <span className="iab-dot" /> ¡Vamos a tu siguiente nivel!
        </div>
      </div>
    </section>
  );
}

/* --------------------------------------------------------------- EJE STEP */
function EjeStep({ eje, idx, total, answers, onAnswer, onPrev, onNext, hintMissing }) {
  const vals = answers[eje.key] || [];
  const done = vals.filter(v => typeof v === 'number').length;
  const allDone = done === eje.q.length;

  return (
    <section className={`diag-fade eje-step ${eje.bg ? 'has-bg' : ''}`} key={eje.key}>
      {eje.bg && (
        <div className="eje-bg" aria-hidden="true">
          <img src={ejeBgSrc(eje.bg)} alt="" />
          <div className="eje-bg-veil" />
          <span className="eje-hud eje-hud--1" />
          <span className="eje-hud eje-hud--2" />
          <span className="eje-hud eje-hud--3" />
        </div>
      )}
      <EjeFloaters ejeKey={eje.key} />
      <div className="eje-head">
        <div className="eje-ghostnum" aria-hidden="true">{eje.n}</div>
        <div className="eje-kicker">
          <span className="eje-kicker-ic" aria-hidden="true">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7"
                 strokeLinecap="round" strokeLinejoin="round"
                 dangerouslySetInnerHTML={{ __html: window.DIAG_EJE_ICONS[eje.key] || '' }} />
          </span>
          Eje {eje.n} de 08
        </div>
        <h2 className="eje-name">{eje.name}</h2>
        <p className="eje-tagline">{eje.tagline}</p>
        <p className="eje-desc"><strong>{eje.desc}</strong></p>
        <div className="eje-instruct">
          Indica qué tanto estás de acuerdo con cada afirmación.
        </div>
      </div>

      <div className="q-list">
        {eje.q.map((text, qi) => {
          const sel = vals[qi];
          const pending = hintMissing && typeof sel !== 'number';
          return (
            <div key={qi}
                 className={`q-card ${typeof sel === 'number' ? 'answered' : ''} ${pending ? 'pending-hint' : ''}`}>
              <div className="q-top">
                <span className="q-idx">{eje.n}.{qi + 1}</span>
                <p className="q-text">{text}</p>
              </div>
              <div className="likert">
                <div className="likert-row" role="radiogroup" aria-label={text}>
                  {window.DIAG_SCALE.map(opt => {
                    const active = sel === opt.v;
                    return (
                      <button type="button" key={opt.v}
                              className={`likert-opt ${active ? 'sel' : ''}`}
                              role="radio" aria-checked={active}
                              title={opt.label}
                              onClick={() => onAnswer(eje.key, qi, opt.v)}>
                        <span className="bead"><CheckIcon /></span>
                        <span className="lk-short">{opt.short}</span>
                      </button>
                    );
                  })}
                </div>
                <div className="likert-ends">
                  <span>En desacuerdo</span>
                  <span>De acuerdo</span>
                </div>
              </div>
            </div>
          );
        })}
      </div>

      <div className="diag-nav">
        <button className="diag-btn ghost sm" onClick={onPrev}>← Atrás</button>
        <div className="right">
          <span className="count"><b>{done}</b> / {eje.q.length}</span>
          <button className="diag-btn sm" onClick={onNext}>
            {idx === total - 1 ? 'Definir mis metas' : 'Siguiente eje'} <span className="arrow">→</span>
          </button>
        </div>
      </div>
    </section>
  );
}

/* ----------------------------------------------------------------- METAS */
function MetaSlider({ score, value, onChange }) {
  const curPct = (score.current / 5) * 100;
  const tgtPct = (value / 5) * 100;
  return (
    <div className="meta-row">
      <div className="meta-row-head">
        <span className="meta-n">{score.n}</span>
        <span className="meta-name">{score.name}</span>
        <span className="meta-cur">
          <span className="pip" /> Hoy estás en <b>{score.current.toFixed(1)}</b>
        </span>
      </div>
      <div className="meta-slider">
        <div className="ms-track">
          <div className="ms-cur-fill" style={{ width: curPct + '%' }} />
          <div className="ms-tgt-fill" style={{ width: tgtPct + '%' }} />
          <div className="ms-cur-mark" style={{ left: curPct + '%' }} title="Tu nivel actual" />
          <div className="ms-thumb" style={{ left: tgtPct + '%' }}><b>{value}</b></div>
          <input className="ms-input" type="range" min="1" max="5" step="1" value={value}
                 aria-label={`Meta para ${score.name}`}
                 onChange={e => onChange(score.key, Number(e.target.value))} />
        </div>
        <div className="ms-scale">
          <span>1 · Punto de partida</span><span>2</span><span>3</span><span>4</span><span>5 · Imparable</span>
        </div>
      </div>
    </div>
  );
}

function MetasStep({ scores, targets, onChange, onPrev, onNext }) {
  return (
    <section className="diag-fade">
      <div className="eje-head">
        <div className="eje-kicker"><span className="kdot" /> Paso final · Tu siguiente nivel</div>
        <h2 className="eje-name">¿Cuál es tu<br/><em style={{color:'var(--d-red)'}}>siguiente nivel</em>?</h2>
        <p className="eje-tagline metas-intro">
          Esta es la otra mitad del mapa. Mueve cada control hasta el nivel al que quieres llegar
          en los próximos meses. La marca clara muestra dónde estás hoy.
        </p>
      </div>
      <div className="meta-list">
        {scores.map(s => (
          <MetaSlider key={s.key} score={s} value={targets[s.key] ?? Math.min(5, Math.max(Math.round(s.current) + 1, 4))}
                      onChange={onChange} />
        ))}
      </div>
      <div className="diag-nav">
        <button className="diag-btn ghost sm" onClick={onPrev}>← Atrás</button>
        <div className="right">
          <button className="diag-btn sm" onClick={onNext}>Ver mi siguiente nivel <span className="arrow">→</span></button>
        </div>
      </div>
    </section>
  );
}

/* ----------------------------------------------------------------- DATOS */
function DatosStep({ data, set, onPrev, onSubmit }) {
  const [touched, setTouched] = React.useState(false);
  const emailOk = /^\S+@\S+\.\S+$/.test(data.email);
  const phoneOk = data.telefono.replace(/\D/g, '').length >= 8;
  const nameOk = data.nombre.trim().length > 1;
  const errs = {
    nombre: touched && !nameOk,
    email: touched && !emailOk,
    telefono: touched && !phoneOk,
  };
  const go = () => {
    setTouched(true);
    if (nameOk && emailOk && phoneOk) onSubmit();
    else {
      const el = document.querySelector('.dfield.err input');
      if (el) el.focus();
    }
  };
  return (
    <section className="diag-fade">
      <div className="eje-head">
        <div className="eje-kicker"><span className="kdot" /> Casi listo</div>
        <h2 className="eje-name">¿A dónde te<br/>enviamos tu <em style={{color:'var(--d-red)'}}>diagnóstico</em>?</h2>
        <p className="eje-tagline">
          Recibirás tu mapa de los 8 ejes y tu curso recomendado por WhatsApp y correo.
        </p>
      </div>
      <div className="datos-grid">
        <div className={`dfield ${errs.nombre ? 'err' : ''}`}>
          <label htmlFor="diagNombre">Nombre completo <span className="req">*</span></label>
          <input id="diagNombre" value={data.nombre} placeholder="¿Cómo te llamas?"
                 onChange={e => set('nombre', e.target.value)} />
          <span className="msg">{errs.nombre ? 'Escribe tu nombre' : ''}</span>
        </div>
        <div className={`dfield ${errs.telefono ? 'err' : ''}`}>
          <label htmlFor="diagTelefono">WhatsApp <span className="req">*</span></label>
          <input id="diagTelefono" value={data.telefono} placeholder="+52 55 0000 0000" type="tel"
                 onChange={e => set('telefono', e.target.value)} />
          <span className="msg">{errs.telefono ? 'Incluye lada + número' : ''}</span>
        </div>
        <div className={`dfield span2 ${errs.email ? 'err' : ''}`}>
          <label htmlFor="diagEmail">Correo electrónico <span className="req">*</span></label>
          <input id="diagEmail" value={data.email} placeholder="tu@correo.com" type="email"
                 onChange={e => set('email', e.target.value)} />
          <span className="msg">{errs.email ? 'Correo inválido' : ''}</span>
        </div>
      </div>
      <div className="datos-note"><span className="pin" /> Tus datos son confidenciales · solo se usan para enviarte tu resultado.</div>
      <div className="diag-nav">
        <button className="diag-btn ghost sm" onClick={onPrev}>← Atrás</button>
        <div className="right">
          <button className="diag-btn sm" onClick={go}>Generar mi diagnóstico <span className="arrow">→</span></button>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Intro, EjeStep, MetasStep, DatosStep });
