// diag-app.jsx — Orquesta el flujo del diagnóstico + persistencia en localStorage.

const STORAGE = 'nl360_diagnostico_v1';
const EJES = window.DIAG_EJES;

function loadState() {
  try {
    const raw = localStorage.getItem(STORAGE);
    if (raw) return JSON.parse(raw);
  } catch (e) {}
  return null;
}

function defaultTarget(cur) {
  return Math.max(3, Math.min(5, Math.round(cur) + 1));
}

function App() {
  const saved = loadState();
  const [step, setStep] = React.useState(saved?.step ?? 0); // 0 intro · 1-8 ejes · 9 metas · 10 datos · 11 results
  const [answers, setAnswers] = React.useState(saved?.answers ?? {});
  const [targets, setTargets] = React.useState(saved?.targets ?? {});
  const [data, setData] = React.useState(saved?.data ?? { nombre: '', email: '', telefono: '' });
  const [hint, setHint] = React.useState(false);
  const [menuOpen, setMenuOpen] = React.useState(false);
  let resultsRec = null, resultsGrowth = null;

  // persist
  React.useEffect(() => {
    try { localStorage.setItem(STORAGE, JSON.stringify({ step, answers, targets, data })); } catch (e) {}
  }, [step, answers, targets, data]);

  // scroll top on step change
  React.useEffect(() => { window.scrollTo({ top: 0, behavior: 'smooth' }); }, [step]);

  const setField = (k, v) => setData(d => ({ ...d, [k]: v }));
  const answer = (ejeKey, qi, val) => {
    setAnswers(a => {
      const arr = (a[ejeKey] || []).slice();
      arr[qi] = val;
      return { ...a, [ejeKey]: arr };
    });
  };
  const setTarget = (k, v) => setTargets(t => ({ ...t, [k]: v }));

  const scores = window.diagBuildScores(answers, targets);

  // ---- navigation ----
  const ejeComplete = (ej) => {
    const arr = answers[ej.key] || [];
    return arr.filter(v => typeof v === 'number').length === ej.q.length;
  };

  const goNextFromEje = (idx) => {
    const ej = EJES[idx];
    if (!ejeComplete(ej)) {
      setHint(true);
      // shake unanswered
      requestAnimationFrame(() => {
        const el = document.querySelector('.q-card.pending-hint');
        if (el) el.scrollIntoView({ behavior: 'smooth', block: 'center' });
      });
      return;
    }
    setHint(false);
    setStep(s => s + 1);
  };

  const enterMetas = () => {
    // initialize any unset targets to a sensible default above current
    setTargets(t => {
      const next = { ...t };
      scores.forEach(s => { if (next[s.key] == null) next[s.key] = defaultTarget(s.current); });
      return next;
    });
  };

  const restart = () => {
    if (!confirm('¿Borrar tus respuestas y empezar de nuevo?')) return;
    try { localStorage.removeItem(STORAGE); } catch (e) {}
    setStep(0); setAnswers({}); setTargets({}); setData({ nombre: '', email: '', telefono: '' }); setHint(false);
  };

  // progress for top bar
  const answeredTotal = EJES.reduce((acc, e) => acc + (answers[e.key] || []).filter(v => typeof v === 'number').length, 0);
  let progress = 0, stepLabel = '';
  if (step === 0) { progress = 0; stepLabel = 'Inicio'; }
  else if (step >= 1 && step <= 8) { progress = (answeredTotal / 40) * 0.8; stepLabel = `Eje ${EJES[step-1].n} / 08`; }
  else if (step === 9) { progress = 0.86; stepLabel = 'Metas'; }
  else if (step === 10) { progress = 0.94; stepLabel = 'Tus datos'; }
  else { progress = 1; stepLabel = 'Resultados'; }

  // ---- render current screen ----
  let screen;
  if (step === 0) {
    screen = <window.Intro onStart={() => setStep(1)} />;
  } else if (step >= 1 && step <= 8) {
    const idx = step - 1;
    screen = (
      <window.EjeStep
        eje={EJES[idx]} idx={idx} total={8} answers={answers} hintMissing={hint}
        onAnswer={answer}
        onPrev={() => { setHint(false); setStep(s => s - 1); }}
        onNext={() => goNextFromEje(idx)} />
    );
  } else if (step === 9) {
    screen = (
      <window.MetasStep
        scores={scores} targets={targets} onChange={setTarget}
        onPrev={() => setStep(8)}
        onNext={() => setStep(10)} />
    );
  } else if (step === 10) {
    screen = (
      <window.DatosStep
        data={data} set={setField}
        onPrev={() => setStep(9)}
        onSubmit={() => setStep(11)} />
    );
  } else {
    const rec = window.diagRecommend(scores);
    const growth = window.diagBuildGrowth(scores, rec.program, rec.estWeeks);
    resultsRec = rec; resultsGrowth = growth;
    screen = <window.Results data={data} scores={scores} rec={rec} growth={growth} onRestart={restart} />;
  }

  // initialize metas targets when arriving at step 9
  React.useEffect(() => { if (step === 9) enterMetas(); /* eslint-disable-next-line */ }, [step]);

  return (
    <div className="diag">
      <div className="diag-grain" aria-hidden="true" />
      <header className="nav">
        <a href="index.html" className="nav__brand" title="The Next Level 360">
          The Next Level 360
        </a>
        <nav className="nav__links">
          <a href="index.html#metodo">El Método</a>
          <a href="index.html#arturo" className="nav__coach"><span className="nav__coach-dot" />Coach Arturo Ceballos</a>
          <a href="index.html#servicios">Servicios</a>
          <a href="index.html#programas">Programas</a>
          <a href="index.html#comunidad">Comunidad</a>
          <a href="Tienda.html">Tienda</a>
          <a href="index.html#oficinas">Oficinas</a>
        </nav>
        <a href="index.html#contacto" className="nav__cta">Contáctanos →</a>
        <button
          className="nav__burger"
          type="button"
          aria-label="Abrir menú"
          aria-expanded={menuOpen}
          onClick={() => setMenuOpen(o => !o)}>
          <span />
        </button>
      </header>

      <div className="diag-progress" role="progressbar" aria-valuenow={Math.round(progress*100)} aria-valuemin={0} aria-valuemax={100} aria-label="Avance del diagnóstico">
        <span className="diag-progress__label">▶ Avance del diagnóstico</span>
        <div className="diag-progress__track">
          <div className="diag-progress__fill" style={{ width: `${progress*100}%` }} />
        </div>
        <span className="diag-progress__pct">{Math.round(progress*100)}%</span>
      </div>

      <nav className={`mobile-menu${menuOpen ? ' is-on' : ''}`} aria-label="Menú móvil">
        <button className="mobile-menu__close" type="button" aria-label="Cerrar menú" onClick={() => setMenuOpen(false)}>
          <svg viewBox="0 0 24 24" fill="none" strokeWidth="2" strokeLinecap="round"><path d="M18 6 6 18M6 6l12 12" /></svg>
        </button>
        <a href="index.html" onClick={() => setMenuOpen(false)}>Inicio</a>
        <a href="index.html#metodo" onClick={() => setMenuOpen(false)}>El Método</a>
        <a href="index.html#arturo" className="mobile-menu__coach" onClick={() => setMenuOpen(false)}><span className="mm-dot" />Coach Arturo Ceballos</a>
        <a href="index.html#servicios" onClick={() => setMenuOpen(false)}>Servicios</a>
        <a href="index.html#programas" onClick={() => setMenuOpen(false)}>Programas</a>
        <a href="index.html#comunidad" onClick={() => setMenuOpen(false)}>Comunidad</a>
        <a href="Conferencias.html" onClick={() => setMenuOpen(false)}>Conferencias</a>
        <a href="Tienda.html" onClick={() => setMenuOpen(false)}>Tienda</a>
        <a href="index.html#oficinas" onClick={() => setMenuOpen(false)}>Oficinas</a>
        <a href="index.html#contacto" className="mobile-menu__cta" onClick={() => setMenuOpen(false)}>Contáctanos →</a>
      </nav>

      <style>{`
        @media (max-width: 880px) {
          body.menu-open .mobile-menu { opacity: 1; pointer-events: auto; }
          .mobile-menu a { animation: mmIn 420ms var(--ease-out) forwards; opacity: 0; transform: translateY(16px); }
          .mobile-menu a:nth-child(2) { animation-delay: 60ms; }
          .mobile-menu a:nth-child(3) { animation-delay: 110ms; }
          .mobile-menu a:nth-child(4) { animation-delay: 160ms; }
          .mobile-menu a:nth-child(5) { animation-delay: 210ms; }
          .mobile-menu a:nth-child(6) { animation-delay: 260ms; }
          .mobile-menu a:nth-child(7) { animation-delay: 310ms; }
          .mobile-menu a:nth-child(8) { animation-delay: 360ms; }
          .mobile-menu a:nth-child(9) { animation-delay: 410ms; }
          .mobile-menu a:nth-child(10) { animation-delay: 460ms; }
          .mobile-menu a:nth-child(11) { animation-delay: 510ms; }
          @keyframes mmIn { to { opacity: 1; transform: translateY(0); } }
          .mobile-menu__cta {
            margin-top: auto; background: var(--d-red); color: #fff !important; justify-content: center;
            border-radius: 16px !important; border: none !important; font-size: clamp(18px,5vw,22px) !important;
            font-weight: 700 !important; padding: 20px !important;
          }
        }
        @media (prefers-reduced-motion: reduce) {
          .mobile-menu a { animation: none; opacity: 1; transform: none; }
        }
      `}</style>

      <main className="diag-stage">
        {screen}
      </main>

      <footer className="diag-footer">
        <span>THE NEXT LEVEL 360 · <b>Diagnóstico de los 8 Ejes</b></span>
        <span>By Coach Arturo Ceballos</span>
      </footer>

      {step === 11 && resultsRec && (
        <window.PdfSheet data={data} scores={scores} rec={resultsRec} growth={resultsGrowth} />
      )}
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('app')).render(<App />);
