// ───────────────────────── App shell ─────────────────────────
const { useState, useRef } = React;

const STEPS = [
  { n: 1, label: 'Contenido',       title: 'Selecciona el contenido',       icon: 'book' },
  { n: 2, label: 'Currículo',       title: 'Vincula el currículo oficial',  icon: 'target' },
  { n: 3, label: 'Configuración',   title: 'Configura la generación',       icon: 'settings' },
  { n: 4, label: 'Revisión',        title: 'Revisa y edita las preguntas',  icon: 'clipboard' },
  { n: 5, label: 'Entrega',         title: 'Vista previa y entrega',        icon: 'send' },
];

function ChromeHeader({ lang, setLang }) {
  const [open, setOpen] = useState(false);
  return (
    <header className="sticky top-0 z-40 bg-white border-b border-line">
      <div className="h-[58px] px-4 flex items-center gap-4">
        {/* edebé icon */}
        <img src="assets/edebeon-icon.svg" alt="EdebéOn+" title="EdebéOn+" className="w-6 h-6 shrink-0" />
        <div className="self-stretch w-px bg-line shrink-0" />
        {/* book */}
        <div className="flex items-center gap-2.5 min-w-0">
          <div className="w-7 h-[38px] rounded-[5px] overflow-hidden ring-1 ring-black/10 shrink-0" style={{ background: `url(${CONTEXT.cover}) center/cover` }} />
          <span className="text-[15px] font-semibold text-ink truncate max-w-[120px] sm:max-w-[180px]">Biología y Geología 1</span>
        </div>
        <div className="self-stretch w-px bg-line shrink-0" />
        {/* tool */}
        <div className="flex items-center gap-2.5 min-w-0">
          <div className="w-8 h-8 rounded-lg bg-primary-50 text-primary flex items-center justify-center shrink-0">
            <Icon name="sparkle" size={18} />
          </div>
          <span className="text-[15px] font-semibold text-ink truncate hidden sm:block">Generador de actividades con IA</span>
        </div>
        <div className="flex-1" />
        {/* selector de idioma de la plataforma */}
        <div className="relative shrink-0">
          <button onClick={() => setOpen(o => !o)}
            className="inline-flex items-center gap-2 h-9 pl-3.5 pr-3 rounded-[10px] border border-line bg-white text-[14px] font-semibold text-ink hover:border-primary-300 transition-colors">
            {lang}
            <Icon name="chevron-down" size={17} className={cx('text-faint transition-transform', open && 'rotate-180')} />
          </button>
          {open && (
            <>
              <div className="fixed inset-0 z-10" onClick={() => setOpen(false)} />
              <div className="absolute right-0 top-11 z-20 w-[190px] bg-white rounded-[10px] border border-line shadow-pop py-1.5 anim-fade-in">
                {LANGUAGES.map(l => (
                  <button key={l} onClick={() => { setLang(l); setOpen(false); }}
                    className={cx('w-full flex items-center justify-between gap-3 px-3.5 py-2 text-sm transition-colors hover:bg-canvas',
                      l === lang ? 'text-primary-800 font-semibold' : 'text-ink')}>
                    {l}
                    {l === lang && <Icon name="check" size={16} strokeWidth={2.6} className="text-primary-800" />}
                  </button>
                ))}
              </div>
            </>
          )}
        </div>
      </div>
    </header>
  );
}

function ContextStrip() { return null; }

// Top-of-content progress indicator
function WizardProgress({ step, generated, go }) {
  const cur = STEPS[step - 1];
  const total = STEPS.length;
  return (
    <div className="sticky top-[58px] z-30 bg-white/90 backdrop-blur border-b border-line">
      <div className="max-w-[1040px] mx-auto px-4 lg:px-8 py-3.5">
        {/* Desktop: full stepper */}
        <div className="hidden md:flex items-center gap-1">
          {STEPS.map((s, i) => {
            const done = s.n < step;
            const active = s.n === step;
            const locked = s.n >= 4 && !generated;
            const reachable = done && !locked;
            return (
              <React.Fragment key={s.n}>
                <button onClick={() => reachable && go(s.n)} disabled={!reachable && !active}
                  title={reachable ? 'Volver a este paso · tus datos se conservan' : undefined}
                  className={cx('group inline-flex items-center gap-2 pl-1.5 pr-3 py-1 rounded-full text-[13px] font-semibold transition-colors',
                    active ? 'bg-primary text-white' : done ? 'text-primary-800 hover:bg-primary-50 cursor-pointer' : 'text-muted cursor-default',
                    locked && 'opacity-50')}>
                  <span className={cx('w-[22px] h-[22px] rounded-full flex items-center justify-center text-[11px] font-bold border-2 transition-colors',
                    active ? 'bg-white/15 border-white/50 text-white' : done ? 'bg-primary border-primary text-white' : 'border-[#d4d4dc] text-faint')}>
                    {done ? <Icon name="check" size={12} strokeWidth={3.2} /> : s.n}
                  </span>
                  {s.label}
                </button>
                {i < total - 1 && <Icon name="chevron-right" size={16} className="text-faint shrink-0" />}
              </React.Fragment>
            );
          })}
        </div>

        {/* Mobile: compact dots */}
        <div className="md:hidden flex items-center gap-1.5">
          {STEPS.map(s => (
            <span key={s.n} className={cx('h-1.5 rounded-full flex-1 transition-colors', s.n <= step ? 'bg-primary' : 'bg-line')} />
          ))}
        </div>
      </div>
    </div>
  );
}

// Step legend — sits ABOVE the content (not in the fixed sub-header)
function StepLegend({ step }) {
  const cur = STEPS[step - 1];
  const total = STEPS.length;
  return (
    <div className="mb-5">
      <span className="text-[12px] font-bold uppercase tracking-wide text-primary-800">Paso {step} de {total}</span>
      <h2 className="text-[22px] font-bold text-ink tracking-tight leading-tight mt-1">{cur.title}</h2>
    </div>
  );
}

function GeneratingOverlay() {
  const [phase, setPhase] = useState(0);
  const phases = ['Analizando las páginas seleccionadas…', 'Cruzando con los criterios de evaluación…', 'Redactando las preguntas…'];
  React.useEffect(() => {
    const t1 = setTimeout(() => setPhase(1), 650);
    const t2 = setTimeout(() => setPhase(2), 1300);
    return () => { clearTimeout(t1); clearTimeout(t2); };
  }, []);
  return (
    <div className="fixed inset-0 z-50 bg-white/95 backdrop-blur flex items-center justify-center anim-fade-in">
      <div className="text-center px-8">
        <div className="relative w-20 h-20 mx-auto mb-6">
          <span className="absolute inset-0 rounded-full border-4 border-primary-100" />
          <span className="absolute inset-0 rounded-full border-4 border-transparent border-t-primary" style={{ animation: 'spin 0.9s linear infinite' }} />
          <span className="absolute inset-0 flex items-center justify-center text-primary"><Icon name="sparkle" size={28} /></span>
        </div>
        <h2 className="text-[22px] font-bold text-ink">Generando tu actividad</h2>
        <p className="text-[15px] text-muted mt-2 transition-all">{phases[phase]}</p>
        <div className="flex items-center justify-center gap-1.5 mt-5">
          {phases.map((_, i) => (
            <span key={i} className={cx('h-1.5 rounded-full transition-all duration-300', i <= phase ? 'w-8 bg-primary' : 'w-3 bg-line')} />
          ))}
        </div>
      </div>
    </div>
  );
}

function App() {
  const [view, setView] = useState('home'); // home | wizard | generating | preview | export
  const [step, setStep] = useState(1);
  const [generated, setGenerated] = useState(false);
  const [integrated, setIntegrated] = useState(false);
  const [exportFormat, setExportFormat] = useState(null); // 'PDF' | 'ODT' | 'EDEBEON'
  const [integrationCopy, setIntegrationCopy] = useState(null);
  const [successOpen, setSuccessOpen] = useState(false);
  const [docTitle, setDocTitle] = useState('');
  const scrollRef = useRef(null);

  // wizard data
  const [type, setType] = useState('flipbook');
  const [pageSel, setPageSel] = useState({ u4: [68, 69, 70, 71, 72, 73] });
  const [blockSel, setBlockSel] = useState({ u4: [0, 2, 3] });
  const [linked, setLinked] = useState(['c3.1', 'c3.2']);
  const [config, setConfig] = useState({ typeCounts: { simple: 3, multiple: 3, fill: 1, essay: 1 }, difficulty: 'Medio' });
  const [questions, setQuestions] = useState([]);
  const [delivery, setDelivery] = useState({ center: CONTEXT.school, materia: CONTEXT.book, curso: CONTEXT.level, logo: null, logoName: '', group: '1º ESO A', solutions: true });
  const [lang, setLang] = useState(CONTEXT.language);

  const scrollTop = () => { if (scrollRef.current) scrollRef.current.scrollTop = 0; };
  const goStep = (n) => { setStep(n); scrollTop(); };

  // selection counts
  const sel1 = type === 'flipbook'
    ? Object.values(pageSel).reduce((a, x) => a + x.length, 0)
    : Object.values(blockSel).reduce((a, x) => a + x.length, 0);
  const total3 = Object.values(config.typeCounts).reduce((a, b) => a + b, 0);
  const nTypes3 = Object.keys(config.typeCounts).length;
  const validatedCount = questions.filter(q => q.validated).length;
  const canNext = step === 1 ? sel1 > 0 : step === 3 ? total3 > 0 : step === 4 ? validatedCount > 0 : true;

  const defaultTitle = () => `Actividad — ${CONTEXT.book}`;

  const startWizard = () => { setView('wizard'); setStep(1); setIntegrated(false); setExportFormat(null); setIntegrationCopy(null); scrollTop(); };

  // Reinicio completo para crear otra actividad
  const resetAll = () => {
    setSuccessOpen(false);
    setView('home');
    setGenerated(false);
    setIntegrated(false);
    setExportFormat(null);
    setIntegrationCopy(null);
    setStep(1);
    scrollTop();
  };

  // Histórico · Editar → abre la revisión (paso 4)
  const editHistory = (item) => {
    setQuestions(makeGeneratedQuestions());
    setDocTitle(item.title);
    setGenerated(true);
    setIntegrated(false);
    setView('wizard');
    setStep(4);
    scrollTop();
  };

  // Histórico · Visualizar → abre el paso final (vista previa + entrega)
  const previewHistory = (item) => {
    setQuestions(makeGeneratedQuestions().map(q => ({ ...q, validated: true })));
    setDocTitle(item.title);
    setGenerated(true);
    setIntegrated(false);
    setView('wizard');
    setStep(5);
    scrollTop();
  };

  const next = () => {
    if (step === 3) {
      setView('generating');
      setTimeout(() => {
        if (!generated) setQuestions(makeGeneratedQuestions());
        setGenerated(true);
        setStep(4);
        setView('wizard');
        scrollTop();
      }, 1850);
    } else if (step === 5) {
      setDocTitle(t => t || defaultTitle());
    } else {
      goStep(step + 1);
    }
  };
  const prev = () => {
    if (step === 1) { setView('home'); scrollTop(); }
    else goStep(step - 1);
  };

  const summary = {
    title: docTitle || defaultTitle(),
    count: questions.length,
    types: [...new Set(questions.map(q => q.type))].length,
    criteria: linked.length,
    group: delivery.group,
  };

  const nextLabel = step === 3 ? 'Generar con IA' : 'Siguiente';

  return (
    <div ref={scrollRef} className="h-screen overflow-y-auto bg-canvas">
      <ChromeHeader lang={lang} setLang={setLang} />
      {view !== 'export' && <ContextStrip />}

      {view === 'generating' && <GeneratingOverlay />}

      {view === 'home' && <HomeScreen onStart={startWizard} onView={previewHistory} onEdit={editHistory} />}

      {(view === 'wizard' || view === 'generating') && (
        <>
          <WizardProgress step={step} generated={generated} go={goStep} />
          <div className="max-w-[1040px] mx-auto px-4 lg:px-8 pt-6 pb-28">
            <main className="min-w-0 anim-fade-up" key={step}>
              <StepLegend step={step} />
              {step === 1 && <ContentStep type={type} setType={setType} pageSel={pageSel} setPageSel={setPageSel} blockSel={blockSel} setBlockSel={setBlockSel} />}
              {step === 2 && <CurriculumStep linked={linked} setLinked={setLinked} />}
              {step === 3 && <ConfigStep config={config} setConfig={setConfig} />}
              {step === 4 && <QuestionsStep questions={questions} setQuestions={setQuestions} config={config} />}
              {step === 5 && <DeliveryStep delivery={delivery} setDelivery={setDelivery}
                title={docTitle || defaultTitle()} setTitle={setDocTitle} config={config} questions={questions} setQuestions={setQuestions} linked={linked}
                exportFormat={exportFormat} setExportFormat={setExportFormat}
                integrationCopy={integrationCopy} setIntegrationCopy={setIntegrationCopy}
                onEditQuestions={() => { setStep(4); scrollTop(); }} />}
            </main>
          </div>
        </>
      )}

      {/* Sticky action bar */}
      {view === 'wizard' && (
        <div className="fixed bottom-0 inset-x-0 z-30 bg-white/90 backdrop-blur border-t border-line">
          <div className="max-w-[1040px] mx-auto px-4 lg:px-8 h-[68px] flex items-center justify-between gap-4">
            <Button variant="ghost" icon="arrow-left" onClick={prev}>
              {step === 1 ? 'Volver al inicio' : 'Anterior'}
            </Button>
            <div className="flex items-center gap-3">
              <span className="hidden sm:block text-[13px] text-muted">
                {step === 1 && `${sel1} ${type === 'flipbook' ? 'páginas' : 'bloques'} seleccionados`}
                {step === 2 && `${linked.length} criterios vinculados`}
                {step === 3 && `${total3} preguntas · ${nTypes3} ${nTypes3 === 1 ? 'tipo' : 'tipos'}`}
                {step === 4 && (validatedCount > 0 ? `${validatedCount} de ${questions.length} validadas` : 'Valida al menos una pregunta para continuar')}
                {step === 5 && (exportFormat === 'EDEBEON' && !integrationCopy ? 'Selecciona la copia donde integrar' : exportFormat ? '' : 'Selecciona un formato de exportación')}
              </span>
              {step === 5
                ? <Button variant="primary" icon={exportFormat ? EXPORT_ICON[exportFormat] : undefined} onClick={() => setSuccessOpen(true)} disabled={!exportFormat || (exportFormat === 'EDEBEON' && !integrationCopy)}>
                    {exportFormat ? EXPORT_LABEL[exportFormat] : 'Selecciona un formato'}
                  </Button>
                : step === 3
                ? <Button variant="primary" icon="sparkle" onClick={next} disabled={!canNext}>{nextLabel}</Button>
                : <Button variant="primary" iconRight="arrow-right" onClick={next} disabled={!canNext}>{nextLabel}</Button>}
            </div>
          </div>
        </div>
      )}

      {successOpen && (
        <SuccessModal format={exportFormat} solutions={delivery.solutions} group={delivery.group}
          copyName={(TEACHER_COPIES.find(c => c.id === integrationCopy) || {}).name}
          onClose={() => setSuccessOpen(false)} onNew={resetAll} />
      )}
    </div>
  );
}

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