/* global React, window */
const { useState } = React;

// Step 0: Welcome
function Step0_Welcome() {
  const { schoolName, account } = useApp();
  const firstName = (account && account.user && account.user.firstName) || "";
  const greeting = firstName ? `Olá, ${firstName}!` : `Olá, ${schoolName}!`;
  return (
    <div>
      <div style={{ display: "flex", gap: 48, alignItems: "center", marginTop: 20 }}>
        <div style={{ flexShrink: 0, position: "relative" }}>
          <div style={{
            position: "absolute", inset: "-20px -10px", borderRadius: "50%",
            background: "radial-gradient(circle, rgba(199,222,64,0.25), transparent 70%)",
            zIndex: 0,
          }}/>
          <div style={{ position: "relative", zIndex: 1 }}>
            <LexFullBody size={300} />
          </div>
        </div>
        <div style={{ flex: 1 }}>
          <div style={{
            fontSize: 13, fontWeight: 700, letterSpacing: 1.3,
            textTransform: "uppercase", color: "var(--teal)", marginBottom: 12,
          }}>{greeting}</div>
          <h1 style={{
            fontSize: 46, fontWeight: 800, lineHeight: 1.08,
            color: "var(--text)", letterSpacing: -0.8, marginBottom: 20,
          }}>
            Oi, eu sou o <span style={{color:"var(--teal)"}}>Lex</span>.<br/>
            Vou te ajudar a montar a <span style={{color:"var(--blue)"}}>lista de volta às aulas</span> do próximo ano letivo.
          </h1>
          <p style={{
            fontSize: 18, color: "var(--text-mute)", lineHeight: 1.6, maxWidth: 640, marginBottom: 10,
          }}>
            Em poucos passos eu cruzo o histórico da escola, os níveis <Scolex/> dos alunos,
            os temas que você quer trabalhar, e monto uma recomendação personalizada
            por série, com estoque, preço e link pronto pra compartilhar com as famílias.
          </p>
          <div style={{ display: "flex", gap: 20, marginTop: 32, flexWrap: "wrap" }}>
            {[
              { n: "5 etapas", l: "do começo ao fim" },
              { n: "15 passos", l: "guiados" },
              { n: "1 link", l: "final pra escola" },
            ].map((s,i) => (
              <div key={i} style={{
                background: "#fff", border: "1px solid var(--border)",
                borderRadius: 14, padding: "14px 20px",
                boxShadow: "var(--shadow-sm)",
              }}>
                <div style={{ fontSize: 22, fontWeight: 800, color: "var(--teal-dark)" }}>{s.n}</div>
                <div style={{ fontSize: 12.5, color: "var(--text-mute)", marginTop: 2 }}>{s.l}</div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Editoras parceiras */}
      <div style={{
        marginTop: 48,
      }}>
        <div style={{
          fontSize: 11, fontWeight: 700, letterSpacing: 1.5,
          textTransform: "uppercase", color: "var(--text-mute)",
          textAlign: "center", marginBottom: 14,
        }}>Editoras parceiras da Scolados</div>
        <div style={{
          background: "#fff",
          border: "1px solid var(--border)",
          borderRadius: 20,
          padding: "28px 32px",
          boxShadow: "var(--shadow-sm)",
          display: "flex", justifyContent: "space-around", alignItems: "center",
          gap: 24, flexWrap: "wrap",
        }}>
          {[
            { n:"Companhia das Letras",   logo:"assets/editoras/companhia.png",          h: 56 },
            { n:"Penguin",                logo:"assets/editoras/penguin.png",            h: 64 },
            { n:"Scholastic",             logo:"assets/editoras/scholastic.png",         h: 32 },
            { n:"Pallas",                 logo:"assets/editoras/pallas.png",             h: 64 },
            { n:"Bloomsbury",             logo:"assets/editoras/bloomsbury.png",         h: 40 },
            { n:"Pallas Mini",            logo:"assets/editoras/pallasmini.png",         h: 52 },
            { n:"Global Editora",         logo:"assets/editoras/global.png",             h: 34 },
            { n:"Grupo Editorial Record", logo:"assets/editoras/record.png",             h: 56 },
            { n:"Moderna Literatura",     logo:"assets/editoras/moderna-literatura.png", h: 56 },
            { n:"HarperCollins",          logo:"assets/editoras/harpercollins.png",      h: 48 },
            { n:"Piraporiando",           logo:"assets/editoras/piraporiando.png",       h: 56 },
            { n:"Savvas",                 logo:"assets/editoras/savvas.png",             h: 44 },
            { n:"Pearson",                logo:"assets/editoras/pearson.png",            h: 40 },
            { n:"Girassol",               logo:"assets/editoras/girassol.png",           h: 34 },
            { n:"Editora Globo",          logo:"assets/editoras/globo.png",              h: 32 },
            { n:"FTD Educação",           logo:"assets/editoras/ftd.png",                h: 48 },
          ].map(p => (
            <img key={p.n} src={p.logo} alt={p.n} title={p.n}
              style={{ height: p.h, objectFit: "contain" }} />
          ))}
        </div>
      </div>
    </div>
  );
}
// Step 1: Calendário & séries — escolhe organização (bimestres/trimestres) e edita a lista de séries.
const SEGMENTS_DEF = [
  { id: "infantil", label: "Educação Infantil", c: "#e79cc5", series: ["Maternal","Pré I","Pré II"] },
  { id: "fund1",    label: "Fundamental I",     c: "#c7de40", series: ["1º ano","2º ano","3º ano","4º ano","5º ano"] },
  { id: "fund2",    label: "Fundamental II",    c: "#2f97a1", series: ["6º ano","7º ano","8º ano","9º ano"] },
  { id: "em",       label: "Ensino Médio",      c: "#2c4ffc", series: ["1º EM","2º EM","3º EM"] },
];
const DEFAULT_SERIES = SEGMENTS_DEF.filter(s => s.id !== "infantil").flatMap(s => s.series);
const SEGMENT_ORDER = ["infantil", "fund1", "fund2", "em", "outros"];

// Reconstrói `series` respeitando a ordem visual dos segmentos (infantil →
// fund1 → fund2 → em → outros — a mesma ordem que a tela mostra agrupada,
// ver `grouped`/`segOrder` no render abaixo), preservando a ordem relativa
// dentro de cada segmento. Sem isso, "+ série" e reatribuir o segmento de
// uma série ao editar só mexiam no array (append no fim / troca in-place)
// sem nunca mover a série pra posição certa — a Seção 1 continuava
// mostrando tudo agrupado corretamente (ela reagrupa na hora de renderizar,
// não depende da ordem do array), mas toda outra tela que usa
// data.seriesNames direto (Recomendações, Didáticos, Papelaria, Revisão...)
// mostrava a ordem "crua" do array, divergindo do que a escola via na
// Seção 1 — bug reportado depois da mudança pra usar séries reais em vez
// da lista fixa de 12 (31/08/2026).
function reorderBySegment(list, resolveSegmentFn) {
  const bySeg = {};
  list.forEach((name) => {
    const segId = resolveSegmentFn(name).id;
    if (!bySeg[segId]) bySeg[segId] = [];
    bySeg[segId].push(name);
  });
  return SEGMENT_ORDER.flatMap((id) => bySeg[id] || []);
}
const SEGMENT_OF = (name) => {
  if (/EM\b/i.test(name)) return SEGMENTS_DEF.find(s => s.id === "em");
  if (/maternal|pré|pre\b|jardim|infantil/i.test(name)) return SEGMENTS_DEF.find(s => s.id === "infantil");
  const m = name.match(/^(\d+)/);
  const n = m ? +m[1] : 0;
  if (n >= 1 && n <= 5) return SEGMENTS_DEF.find(s => s.id === "fund1");
  if (n >= 6 && n <= 9) return SEGMENTS_DEF.find(s => s.id === "fund2");
  // Escolas bilíngues nomeiam por "10th/11th/12th grade" (ou numeração contínua tipo Portugal) — ainda é Ensino Médio
  if (n >= 10 && n <= 12) return SEGMENTS_DEF.find(s => s.id === "em");
  return { id: "outros", label: "Outros", c: "#9aa0a6", series: [] };
};

function Step1_Calendar() {
  const { data, setData } = useApp();
  const calendar = data.calendar || "bimestres";
  const series = data.seriesNames || DEFAULT_SERIES;
  // Segments enabled by default: tudo exceto Infantil (mantém comportamento atual)
  const enabledSegs = data.enabledSegments || ["fund1","fund2","em"];
  // Segmento escolhido manualmente por nome de série, sobrescreve a heurística por nome (SEGMENT_OF)
  const segmentOverrides = data.seriesSegmentOverrides || {};
  const resolveSegmentUsing = (name, overridesMap) => {
    const ov = overridesMap[name];
    if (ov) return SEGMENTS_DEF.find(s => s.id === ov) || { id: "outros", label: "Outros", c: "#9aa0a6", series: [] };
    return SEGMENT_OF(name);
  };
  const resolveSegment = (name) => resolveSegmentUsing(name, segmentOverrides);
  // Nome do segmento renomeado pela escola (ex: "Fundamental I" -> "Anos Iniciais")
  const segmentLabels = data.segmentLabels || {};
  const labelFor = (segId, fallback) => segmentLabels[segId] || fallback;
  const setCalendar = (v) => setData(d => ({ ...d, calendar: v }));
  const setSeries = (next) => setData(d => ({ ...d, seriesNames: next }));

  const [editingIdx, setEditingIdx] = useState(-1);
  const [draft, setDraft] = useState("");
  const [draftSegment, setDraftSegment] = useState(null);
  const [newName, setNewName] = useState("");
  // null = segue a sugestão automática (SEGMENT_OF) enquanto a escola não escolher outro segmento no <select>
  const [newSegId, setNewSegId] = useState(null);
  const [editingSegId, setEditingSegId] = useState(null);
  const [segDraft, setSegDraft] = useState("");

  const startSegEdit = (segId, currentLabel) => { setEditingSegId(segId); setSegDraft(currentLabel); };
  const cancelSegEdit = () => { setEditingSegId(null); setSegDraft(""); };
  const commitSegEdit = () => {
    const v = segDraft.trim();
    if (v && editingSegId) {
      setData(d => ({ ...d, segmentLabels: { ...(d.segmentLabels || {}), [editingSegId]: v } }));
    }
    setEditingSegId(null); setSegDraft("");
  };

  // Insere `name` já classificado no segmento `segId` escolhido explicitamente
  // pela escola — grava override antes de reordenar, então a heurística
  // (SEGMENT_OF) nunca decide por conta própria onde a série cai, e ela não
  // se move dali em renders futuros (resolveSegment consulta o override primeiro).
  const insertSeriesInSegment = (name, segId) => {
    const nextOverrides = { ...segmentOverrides, [name]: segId };
    setSeries(reorderBySegment([...series, name], (n) => resolveSegmentUsing(n, nextOverrides)));
    setData(d => ({ ...d, seriesSegmentOverrides: nextOverrides }));
  };

  // Adicionar série já direto dentro de um segmento específico (evita cair em "Outros")
  const [addingSegId, setAddingSegId] = useState(null);
  const [addDraft, setAddDraft] = useState("");
  const startAddInSeg = (segId) => { setAddingSegId(segId); setAddDraft(""); };
  const cancelAddInSeg = () => { setAddingSegId(null); setAddDraft(""); };
  const commitAddInSeg = () => {
    const v = addDraft.trim();
    if (v) insertSeriesInSegment(v, addingSegId);
    setAddingSegId(null); setAddDraft("");
  };

  const startEdit = (i) => { setEditingIdx(i); setDraft(series[i]); setDraftSegment(resolveSegment(series[i]).id); };
  const cancelEdit = () => { setEditingIdx(-1); setDraft(""); setDraftSegment(null); };
  const commitEdit = () => {
    const v = draft.trim();
    if (v && editingIdx >= 0) {
      const oldName = series[editingIdx];
      // grava o segmento escolhido explicitamente pro novo nome, sobrescrevendo a heurística
      const nextOverrides = { ...segmentOverrides };
      if (oldName !== v) delete nextOverrides[oldName];
      nextOverrides[v] = draftSegment;
      const renamed = [...series];
      renamed[editingIdx] = v;
      // Reordena: se o segmento mudou (via <select> de segmento no editor),
      // a série precisa se mover pro bloco certo, não só trocar de nome na
      // mesma posição — senão a ordem "de verdade" (data.seriesNames, usada
      // por Recomendações/Didáticos/etc) fica fora de sincronia com o
      // agrupamento visual desta tela.
      setSeries(reorderBySegment(renamed, (name) => resolveSegmentUsing(name, nextOverrides)));
      setData(d => ({ ...d, seriesSegmentOverrides: nextOverrides }));
    }
    setEditingIdx(-1); setDraft(""); setDraftSegment(null);
  };
  const removeAt = (i) => {
    const name = series[i];
    setSeries(series.filter((_, j) => j !== i));
    setData(d => {
      const ov = { ...(d.seriesSegmentOverrides || {}) };
      delete ov[name];
      return { ...d, seriesSegmentOverrides: ov };
    });
  };
  const addSeries = () => {
    const v = newName.trim();
    if (!v) return;
    insertSeriesInSegment(v, newSegId || resolveSegment(v).id);
    setNewName(""); setNewSegId(null);
  };
  const resetDefaults = () => {
    const segs = enabledSegs;
    const next = SEGMENTS_DEF.filter(s => segs.includes(s.id)).flatMap(s => s.series);
    setSeries(next);
    setData(d => ({ ...d, seriesSegmentOverrides: {}, segmentLabels: {} }));
  };

  // Toggle de segmento: adiciona/remove TODAS as séries daquele segmento
  const toggleSegment = (segId) => {
    const seg = SEGMENTS_DEF.find(s => s.id === segId);
    if (!seg) return;
    const isOn = enabledSegs.includes(segId);
    if (isOn) {
      // desliga, remove séries do segmento (compara pelo segmento efetivo: override ou heurística)
      const filtered = series.filter(s => resolveSegment(s)?.id !== segId);
      setData(d => ({ ...d, enabledSegments: enabledSegs.filter(x => x !== segId), seriesNames: filtered }));
    } else {
      // liga, adiciona séries faltantes do segmento, na ordem certa
      const existing = new Set(series);
      const toAdd = seg.series.filter(s => !existing.has(s));
      // inserir respeitando ordem dos segmentos (infantil → fund1 → fund2 → em)
      const orderedAll = [];
      const newEnabled = [...enabledSegs, segId];
      SEGMENTS_DEF.forEach(s => {
        if (newEnabled.includes(s.id)) {
          // séries existentes desse segmento + faltantes (se for o que tá sendo adicionado)
          const existingOfSeg = series.filter(x => resolveSegment(x)?.id === s.id);
          if (s.id === segId) orderedAll.push(...existingOfSeg, ...toAdd);
          else orderedAll.push(...existingOfSeg);
        }
      });
      // séries "outros" (custom) preservadas no final
      const outros = series.filter(s => resolveSegment(s)?.id === "outros");
      setData(d => ({ ...d, enabledSegments: newEnabled, seriesNames: [...orderedAll, ...outros] }));
    }
  };

  // Group por segmento pra exibição
  const grouped = {};
  series.forEach((s, i) => {
    const seg = resolveSegment(s);
    if (!grouped[seg.id]) grouped[seg.id] = { ...seg, label: labelFor(seg.id, seg.label), items: [] };
    grouped[seg.id].items.push({ name: s, idx: i });
  });
  const segOrder = ["infantil","fund1","fund2","em","outros"];

  return (
    <div>
      <Heading
        eyebrow="Preparação · Passo 1"
        title="Como sua escola se organiza?"
        subtitle="Preciso saber o calendário pedagógico e as séries da escola pra distribuir os livros e materiais corretamente." />
      <LexBubble pose="study">
        Em alguns colégios são 4 bimestres, em outros 3 trimestres. E cada escola atende segmentos diferentes, "Maternal", "Pré II", "1ª série EM"... Você ajusta aqui ✏️
      </LexBubble>

      {/* Calendário */}
      <div style={{ marginTop: 32 }}>
        <div style={{ fontSize: 13, fontWeight: 700, color: "var(--teal-dark)", textTransform: "uppercase", letterSpacing: 1, marginBottom: 10 }}>
          Calendário pedagógico
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
          <OptionCard selected={calendar === "bimestres"} onClick={() => setCalendar("bimestres")}>
            <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
              <div style={{
                display: "grid", gridTemplateColumns: "1fr 1fr", gridTemplateRows: "1fr 1fr",
                gap: 4, width: 56, height: 56, flexShrink: 0,
              }}>
                {[1,2,3,4].map(n => (
                  <div key={n} style={{
                    background: calendar === "bimestres" ? "var(--teal)" : "#dde8e9",
                    color: "#fff", borderRadius: 6,
                    display: "flex", alignItems: "center", justifyContent: "center",
                    fontSize: 12, fontWeight: 800,
                  }}>{n}</div>
                ))}
              </div>
              <div>
                <div style={{ fontSize: 16, fontWeight: 700, color: "var(--text)" }}>4 bimestres</div>
                <div style={{ fontSize: 13, color: "var(--text-mute)", marginTop: 2 }}>Avaliações a cada ~2 meses</div>
              </div>
            </div>
          </OptionCard>
          <OptionCard selected={calendar === "trimestres"} onClick={() => setCalendar("trimestres")}>
            <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
              <div style={{
                display: "grid", gridTemplateColumns: "1fr 1fr 1fr",
                gap: 4, width: 84, height: 28, flexShrink: 0,
              }}>
                {[1,2,3].map(n => (
                  <div key={n} style={{
                    background: calendar === "trimestres" ? "var(--teal)" : "#dde8e9",
                    color: "#fff", borderRadius: 6,
                    display: "flex", alignItems: "center", justifyContent: "center",
                    fontSize: 12, fontWeight: 800,
                  }}>{n}</div>
                ))}
              </div>
              <div>
                <div style={{ fontSize: 16, fontWeight: 700, color: "var(--text)" }}>3 trimestres</div>
                <div style={{ fontSize: 13, color: "var(--text-mute)", marginTop: 2 }}>Avaliações a cada ~3 meses</div>
              </div>
            </div>
          </OptionCard>
        </div>
      </div>

      {/* Segmentos atendidos */}
      <div style={{ marginTop: 36 }}>
        <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 10 }}>
          <div style={{ fontSize: 13, fontWeight: 700, color: "var(--teal-dark)", textTransform: "uppercase", letterSpacing: 1 }}>
            Segmentos que a escola atende
          </div>
          <span style={{ fontSize: 12.5, color: "var(--text-mute)" }}>
            Desligue os segmentos que sua escola não atende
          </span>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 10 }}>
          {SEGMENTS_DEF.map(seg => {
            const on = enabledSegs.includes(seg.id);
            return (
              <button key={seg.id} onClick={() => toggleSegment(seg.id)} style={{
                background: on ? "#fff" : "var(--bg-soft)",
                border: `2px solid ${on ? seg.c : "var(--border)"}`,
                borderRadius: 14, padding: "14px 14px",
                cursor: "pointer", textAlign: "left",
                opacity: on ? 1 : 0.55,
                transition: "all .15s",
                position: "relative",
              }}>
                <div style={{
                  position: "absolute", top: 10, right: 10,
                  width: 22, height: 22, borderRadius: 6,
                  background: on ? seg.c : "transparent",
                  border: `1.5px solid ${on ? seg.c : "var(--border)"}`,
                  color: "#fff", fontSize: 12, fontWeight: 800,
                  display: "flex", alignItems: "center", justifyContent: "center",
                }}>{on ? "✓" : ""}</div>
                <div style={{ fontSize: 11, fontWeight: 700, color: seg.c, textTransform: "uppercase", letterSpacing: 0.6, marginBottom: 6 }}>
                  {seg.id === "infantil" ? "Pre-school" : seg.id === "fund1" ? "Anos iniciais" : seg.id === "fund2" ? "Anos finais" : "Médio"}
                </div>
                <div style={{ fontSize: 14.5, fontWeight: 700, color: "var(--text)", lineHeight: 1.2 }}>
                  {labelFor(seg.id, seg.label)}
                </div>
                <div style={{ fontSize: 11.5, color: "var(--text-mute)", marginTop: 4 }}>
                  {seg.series.length} série{seg.series.length !== 1 ? "s" : ""}
                </div>
              </button>
            );
          })}
        </div>
      </div>

      {/* Séries */}
      <div style={{ marginTop: 32 }}>
        <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 10 }}>
          <div style={{ fontSize: 13, fontWeight: 700, color: "var(--teal-dark)", textTransform: "uppercase", letterSpacing: 1 }}>
            Séries da escola
          </div>
          <div style={{ display: "flex", gap: 14, alignItems: "center" }}>
            <span style={{ fontSize: 13, color: "var(--text-mute)" }}>
              <strong style={{ color: "var(--text)" }}>{series.length}</strong> séries no total
            </span>
            <button onClick={resetDefaults} style={{
              background: "transparent", border: "none",
              color: "var(--blue)", fontSize: 12.5, fontWeight: 600,
              cursor: "pointer", padding: 0,
            }}>↺ restaurar padrão</button>
          </div>
        </div>

        <div style={{
          background: "#fff", border: "1px solid var(--border)", borderRadius: 18,
          padding: 22, boxShadow: "var(--shadow-sm)",
        }}>
          {segOrder.filter(k => grouped[k]).map(k => {
            const g = grouped[k];
            return (
              <div key={k} style={{ marginBottom: 18 }}>
                <div style={{
                  fontSize: 11, fontWeight: 700, color: g.c,
                  textTransform: "uppercase", letterSpacing: 0.8, marginBottom: 8,
                  display: "flex", alignItems: "center", gap: 8,
                }}>
                  <span style={{ width: 8, height: 8, borderRadius: 2, background: g.c, flexShrink: 0 }}/>
                  {editingSegId === k ? (
                    <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
                      <input autoFocus
                        value={segDraft}
                        onChange={e => setSegDraft(e.target.value)}
                        onKeyDown={e => {
                          if (e.key === "Enter") commitSegEdit();
                          if (e.key === "Escape") cancelSegEdit();
                        }}
                        style={{
                          padding: "4px 8px", borderRadius: 6,
                          border: `1px solid ${g.c}`, fontSize: 11, fontWeight: 700,
                          textTransform: "uppercase", letterSpacing: 0.8,
                          outline: "none", background: "#fff", color: "var(--text)",
                          minWidth: 100, fontFamily: "inherit",
                        }}/>
                      <button onClick={commitSegEdit} title="Salvar" style={{
                        width: 20, height: 20, borderRadius: "50%",
                        background: "var(--teal)", color: "#fff",
                        fontSize: 11, lineHeight: 1, cursor: "pointer", border: "none",
                        display: "inline-flex", alignItems: "center", justifyContent: "center",
                      }}>✓</button>
                      <button onClick={cancelSegEdit} title="Cancelar" style={{
                        width: 18, height: 18, borderRadius: "50%",
                        background: "var(--bg-light)", color: "var(--text-mute)",
                        fontSize: 10, lineHeight: 1, cursor: "pointer", border: "none",
                        display: "inline-flex", alignItems: "center", justifyContent: "center",
                      }}>✕</button>
                    </span>
                  ) : (
                    <span style={{ display: "inline-flex", alignItems: "center", gap: 4 }}>
                      {g.label}
                      <button onClick={() => startSegEdit(k, g.label)} title="Renomear segmento" style={{
                        width: 18, height: 18, borderRadius: "50%",
                        background: "transparent", color: "var(--text-mute)",
                        fontSize: 10, lineHeight: 1, cursor: "pointer", border: "none",
                        display: "inline-flex", alignItems: "center", justifyContent: "center",
                        textTransform: "none", letterSpacing: "normal",
                      }}>✏️</button>
                    </span>
                  )}
                  <span style={{ color: "var(--text-mute)", fontWeight: 500 }}>· {g.items.length}</span>
                </div>
                <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
                  {g.items.map(({ name, idx }) => (
                    editingIdx === idx ? (
                      <span key={idx} style={{
                        display: "inline-flex", alignItems: "center", gap: 6,
                        padding: 6, borderRadius: 999,
                        border: `2px solid ${g.c}`, background: "#fff",
                      }}>
                        <input autoFocus
                          value={draft}
                          onChange={e => setDraft(e.target.value)}
                          onKeyDown={e => {
                            if (e.key === "Enter") commitEdit();
                            if (e.key === "Escape") cancelEdit();
                          }}
                          style={{
                            padding: "6px 10px", borderRadius: 999,
                            border: "1px solid var(--border)", fontSize: 13.5, fontWeight: 600,
                            outline: "none", background: "var(--bg-soft)", color: "var(--text)",
                            minWidth: 90, fontFamily: "inherit",
                          }}/>
                        <select
                          value={draftSegment || "outros"}
                          onChange={e => setDraftSegment(e.target.value)}
                          title="Segmento"
                          style={{
                            padding: "6px 8px", borderRadius: 999,
                            border: "1px solid var(--border)", fontSize: 12.5, fontWeight: 600,
                            outline: "none", background: "var(--bg-soft)", color: "var(--text)",
                            fontFamily: "inherit", cursor: "pointer",
                          }}>
                          {SEGMENTS_DEF.map(s => <option key={s.id} value={s.id}>{labelFor(s.id, s.label)}</option>)}
                          <option value="outros">{labelFor("outros", "Outros")}</option>
                        </select>
                        <button onClick={commitEdit} title="Salvar" style={{
                          width: 24, height: 24, borderRadius: "50%",
                          background: "var(--teal)", color: "#fff",
                          fontSize: 12, lineHeight: 1, cursor: "pointer", border: "none",
                          display: "inline-flex", alignItems: "center", justifyContent: "center",
                        }}>✓</button>
                        <button onClick={cancelEdit} title="Cancelar" style={{
                          width: 22, height: 22, borderRadius: "50%",
                          background: "var(--bg-light)", color: "var(--text-mute)",
                          fontSize: 12, lineHeight: 1, cursor: "pointer", border: "none",
                          display: "inline-flex", alignItems: "center", justifyContent: "center",
                        }}>✕</button>
                      </span>
                    ) : (
                      <span key={idx} style={{
                        display: "inline-flex", alignItems: "center", gap: 6,
                        padding: "7px 8px 7px 14px", borderRadius: 999,
                        background: "#fff", border: `1.5px solid ${g.c}40`,
                        fontSize: 13.5, fontWeight: 600, color: "var(--text)",
                      }}>
                        <span onClick={() => startEdit(idx)} style={{ cursor: "text" }}>{name}</span>
                        <button onClick={() => startEdit(idx)} title="Renomear" style={{
                          width: 24, height: 24, borderRadius: "50%",
                          background: "transparent", color: "var(--text-mute)",
                          fontSize: 12, lineHeight: 1, cursor: "pointer", border: "none",
                          display: "inline-flex", alignItems: "center", justifyContent: "center",
                        }}>✏️</button>
                        <button onClick={() => removeAt(idx)} title="Remover" style={{
                          width: 22, height: 22, borderRadius: "50%",
                          background: "var(--bg-light)", color: "var(--text-mute)",
                          fontSize: 13, lineHeight: 1, cursor: "pointer", border: "none",
                          display: "inline-flex", alignItems: "center", justifyContent: "center",
                          fontWeight: 700,
                        }}>×</button>
                      </span>
                    )
                  ))}
                  {addingSegId === k ? (
                    <span style={{
                      display: "inline-flex", alignItems: "center", gap: 6,
                      padding: 6, borderRadius: 999,
                      border: `2px dashed ${g.c}`, background: "#fff",
                    }}>
                      <input autoFocus
                        value={addDraft}
                        onChange={e => setAddDraft(e.target.value)}
                        placeholder="Nome da série"
                        onKeyDown={e => {
                          if (e.key === "Enter") commitAddInSeg();
                          if (e.key === "Escape") cancelAddInSeg();
                        }}
                        style={{
                          padding: "6px 10px", borderRadius: 999,
                          border: "1px solid var(--border)", fontSize: 13.5, fontWeight: 600,
                          outline: "none", background: "var(--bg-soft)", color: "var(--text)",
                          minWidth: 100, fontFamily: "inherit",
                        }}/>
                      <button onClick={commitAddInSeg} title="Adicionar" style={{
                        width: 24, height: 24, borderRadius: "50%",
                        background: "var(--teal)", color: "#fff",
                        fontSize: 12, lineHeight: 1, cursor: "pointer", border: "none",
                        display: "inline-flex", alignItems: "center", justifyContent: "center",
                      }}>✓</button>
                      <button onClick={cancelAddInSeg} title="Cancelar" style={{
                        width: 22, height: 22, borderRadius: "50%",
                        background: "var(--bg-light)", color: "var(--text-mute)",
                        fontSize: 12, lineHeight: 1, cursor: "pointer", border: "none",
                        display: "inline-flex", alignItems: "center", justifyContent: "center",
                      }}>✕</button>
                    </span>
                  ) : (
                    <button onClick={() => startAddInSeg(k)} title={`Adicionar série em ${g.label}`} style={{
                      display: "inline-flex", alignItems: "center", gap: 4,
                      padding: "7px 14px", borderRadius: 999,
                      background: "transparent", border: `1.5px dashed ${g.c}80`,
                      fontSize: 13.5, fontWeight: 600, color: g.c, cursor: "pointer",
                    }}>+ série</button>
                  )}
                </div>
              </div>
            );
          })}

          {/* Add nova série */}
          <div style={{
            display: "flex", gap: 8, marginTop: 8,
            paddingTop: 16, borderTop: "1px dashed var(--border)",
          }}>
            <input
              value={newName}
              onChange={e => setNewName(e.target.value)}
              onKeyDown={e => { if (e.key === "Enter") addSeries(); }}
              placeholder='Adicionar série (ex: "Maternal", "Pré II", "1ª série EM")'
              style={{
                flex: 1, padding: "10px 14px",
                border: "1.5px solid var(--border)", borderRadius: 10,
                fontSize: 13.5, background: "var(--bg-soft)",
                color: "var(--text)", outline: "none", fontFamily: "inherit",
              }}/>
            <select
              value={newSegId || resolveSegment(newName).id}
              onChange={e => setNewSegId(e.target.value)}
              title="Em qual segmento entra"
              style={{
                padding: "10px 12px",
                border: "1.5px solid var(--border)", borderRadius: 10,
                fontSize: 13.5, fontWeight: 600, background: "var(--bg-soft)",
                color: "var(--text)", outline: "none", fontFamily: "inherit", cursor: "pointer",
              }}>
              {SEGMENTS_DEF.map(s => <option key={s.id} value={s.id}>{labelFor(s.id, s.label)}</option>)}
              <option value="outros">{labelFor("outros", "Outros")}</option>
            </select>
            <BtnTeal onClick={addSeries} style={{ padding: "10px 18px", whiteSpace: "nowrap" }}>
              + Adicionar série
            </BtnTeal>
          </div>
        </div>

        <div style={{
          marginTop: 14, padding: "12px 16px",
          background: "#fff", border: "1px solid var(--border)", borderRadius: 10,
          fontSize: 12.5, color: "var(--text-mute)", lineHeight: 1.5,
        }}>
          💡 As séries aqui definem todas as próximas etapas, curadoria, didáticos, papelaria e o link das famílias terão uma página por série.
        </div>
      </div>
    </div>
  );
}

function Step1_PastList() {
  const { data, setData } = useApp();
  const choice = data.pastListChoice;
  const set = (v) => setData(d => ({ ...d, pastListChoice: v }));
  return (
    <div>
      <Heading
        eyebrow="Preparação · Passo 1"
        title="Vocês já tem uma lista do ano passado?"
        subtitle="Envie os PDFs ou a planilha Excel do que foi adotado — eu reconheço os ISBNs automaticamente e uso como base." />
      <LexBubble pose="books">
        Uma lista que funcionou bem ano passado é sempre ótimo ponto de partida 📚
      </LexBubble>

      <div style={{ marginTop: 32, maxWidth: 720 }}>
        <OptionCard selected={choice === "upload"} onClick={() => set("upload")}>
          <div style={{fontSize: 30, marginBottom: 8}}>📄</div>
          <div style={{fontSize: 17, fontWeight: 700, marginBottom: 6}}>Vou subir a lista antiga</div>
          <div style={{fontSize: 14, color: "var(--text-mute)", lineHeight: 1.5}}>
            Envie os PDFs ou planilha Excel da lista do ano passado. Eu reconheço os ISBNs automaticamente.
          </div>
        </OptionCard>

        {choice === "upload" && (
          <div style={{ marginTop: 24 }}>
            <UploadZone
              label="Envie os PDFs ou Excel da lista 2025"
              files={data.pastListFiles}
              onAdd={(names) => setData(d => ({ ...d, pastListFiles: [...(d.pastListFiles||[]), ...names] }))}
              extractIsbns
              onIsbnsFound={(fileName, isbns) => setData(d => ({
                ...d,
                pastListIsbns: Array.from(new Set([...(d.pastListIsbns || []), ...isbns])),
              }))}
            />
          </div>
        )}

        <OptionCard selected={choice === "skip"} onClick={() => set("skip")}
          style={{marginTop: 16}}>
          <div style={{display:"flex", alignItems:"center", gap: 14}}>
            <div style={{fontSize: 22}}>🆕</div>
            <div>
              <div style={{fontSize: 15, fontWeight: 700}}>É a primeira vez, começar do zero</div>
              <div style={{fontSize: 13, color: "var(--text-mute)"}}>Sem base histórica. Vou partir só dos dados do <Scolex/> e dos temas que você escolher.</div>
            </div>
          </div>
        </OptionCard>
      </div>
    </div>
  );
}

// Step 3: Themes
const THEMES = [
  { id:"identidade", t:"Identidade e Pertencimento", emoji:"🪞", c:"#e79cc5" },
  { id:"diversidade", t:"Diversidade e Representatividade", emoji:"🌍", c:"#6fc48a" },
  { id:"sustent", t:"Sustentabilidade e Meio Ambiente", emoji:"🌱", c:"#c7de40" },
  { id:"emocoes", t:"Emoções e Socioemocional", emoji:"💛", c:"#f5b942" },
  { id:"historia", t:"História do Brasil", emoji:"📜", c:"#b58863" },
  { id:"mundo", t:"Culturas do Mundo", emoji:"🌏", c:"#2f97a1" },
  { id:"ciencia", t:"Ciência e Descoberta", emoji:"🔬", c:"#8a7fff" },
  { id:"aventura", t:"Aventura e Imaginação", emoji:"🗺️", c:"#f28b5a" },
  { id:"familia", t:"Família e Relacionamentos", emoji:"👨‍👩‍👧", c:"#e0798e" },
  { id:"valores", t:"Valores e Cidadania", emoji:"🤝", c:"#2c4ffc" },
  { id:"classicos", t:"Clássicos da Literatura", emoji:"📚", c:"#7a5d3f" },
  { id:"mitologia", t:"Mitos e Folclore", emoji:"🐉", c:"#9c4dcc" },
];

// Segmentos (para agrupar séries)
const SEGMENTS = [
  { id: "fund1", label: "Fundamental I", series: ["1º ano","2º ano","3º ano","4º ano","5º ano"], c: "#c7de40" },
  { id: "fund2", label: "Fundamental II", series: ["6º ano","7º ano","8º ano","9º ano"], c: "#2f97a1" },
  { id: "em", label: "Ensino Médio", series: ["1º EM","2º EM","3º EM"], c: "#2c4ffc" },
];

function Step2_Themes() {
  const { data, setData } = useApp();
  const selected = data.themes || [];
  const customThemes = data.customThemes || {}; // { escopoId: [tema1, tema2] }
  const [scope, setScope] = useState("all"); // all | seg:fund1 | ser:1º ano
  const [input, setInput] = useState("");

  const toggle = (id) => {
    const next = selected.includes(id) ? selected.filter(x => x !== id) : [...selected, id];
    setData(d => ({ ...d, themes: next }));
  };

  const addCustom = () => {
    const t = input.trim();
    if (!t) return;
    const list = customThemes[scope] || [];
    if (list.includes(t)) return;
    setData(d => ({ ...d, customThemes: { ...(d.customThemes||{}), [scope]: [...list, t] } }));
    setInput("");
  };
  const removeCustom = (sc, t) => {
    const list = (customThemes[sc] || []).filter(x => x !== t);
    setData(d => ({ ...d, customThemes: { ...(d.customThemes||{}), [sc]: list } }));
  };

  const scopeLabel = (sc) => {
    if (sc === "all") return "Toda a escola";
    if (sc.startsWith("seg:")) return SEGMENTS.find(s => s.id === sc.slice(4))?.label || sc;
    if (sc.startsWith("ser:")) return sc.slice(4);
    return sc;
  };
  const scopeColor = (sc) => {
    if (sc === "all") return "var(--teal-dark)";
    if (sc.startsWith("seg:")) return SEGMENTS.find(s => s.id === sc.slice(4))?.c || "var(--teal)";
    return "var(--blue)";
  };

  const totalCustom = Object.values(customThemes).reduce((a,l) => a + l.length, 0);

  return (
    <div>
      <Heading
        eyebrow="Preparação · Passo 1, Diretrizes pedagógicas"
        title="Quais temas vocês querem trabalhar em literatura este ano?"
        subtitle="Comece pelos temas prontos e, se quiser, adicione temas próprios por segmento ou por série, eu uso tudo pra ranquear a curadoria." />
      <LexBubble pose="read">
        Dica: marque os temas da escola inteira primeiro. Depois, se Fundamental I e Médio pedem coisas diferentes, adicione temas específicos lá embaixo ✨
      </LexBubble>

      {/* ========== TEMAS PRONTOS ========== */}
      <div style={{ marginTop: 32 }}>
        <div style={{
          display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 14,
        }}>
          <div style={{ fontSize: 14, fontWeight: 700, color: "var(--teal-dark)", textTransform:"uppercase", letterSpacing: 1 }}>
            Temas da biblioteca Scolex®
          </div>
          <div style={{ fontSize: 13, color: "var(--text-mute)" }}>
            <span style={{ color: "var(--teal)", fontWeight: 700 }}>{selected.length}</span> de {THEMES.length} selecionados
          </div>
        </div>
        <div style={{
          display:"grid", gridTemplateColumns:"repeat(3, 1fr)", gap: 12,
        }}>
          {THEMES.map(t => {
            const on = selected.includes(t.id);
            return (
              <button key={t.id} onClick={() => toggle(t.id)} style={{
                background: "#fff",
                border: `2px solid ${on ? "var(--teal)" : "var(--border)"}`,
                borderRadius: 16, padding: "16px 18px",
                textAlign: "left", transition: "all 0.15s",
                boxShadow: on ? "0 6px 18px rgba(47,151,161,0.15)" : "var(--shadow-sm)",
                position: "relative", cursor: "pointer",
              }}>
                <div style={{ display:"flex", alignItems:"center", gap: 12 }}>
                  <div style={{
                    width: 44, height: 44, borderRadius: 12,
                    background: t.c + "22",
                    display:"flex", alignItems:"center", justifyContent:"center",
                    fontSize: 22,
                  }}>{t.emoji}</div>
                  <div style={{fontSize: 14.5, fontWeight: 600, color: "var(--text)", lineHeight: 1.25}}>{t.t}</div>
                </div>
                {on && <div style={{
                  position: "absolute", top: 10, right: 10,
                  width: 22, height: 22, borderRadius: "50%",
                  background: "var(--teal)", color: "#fff",
                  display: "flex", alignItems: "center", justifyContent: "center",
                  fontSize: 12, fontWeight: 700,
                }}>✓</div>}
              </button>
            );
          })}
        </div>
      </div>

      {/* ========== TEMAS CUSTOMIZADOS ========== */}
      <div style={{
        marginTop: 36, background: "#fff",
        border: "1px solid var(--border)", borderRadius: 20,
        padding: 28, boxShadow: "var(--shadow-sm)",
      }}>
        <div style={{ display: "flex", alignItems: "baseline", gap: 10, marginBottom: 4, flexWrap: "wrap" }}>
          <div style={{ fontSize: 18, fontWeight: 700, color: "var(--text)" }}>
            Temas próprios da escola
          </div>
          {totalCustom > 0 && <div style={{
            fontSize: 12, fontWeight: 700, color: "var(--teal-dark)",
            background: "var(--bg-light)", padding: "3px 10px", borderRadius: 12,
          }}>{totalCustom} adicionado{totalCustom !== 1 ? "s" : ""}</div>}
        </div>
        <div style={{ fontSize: 14, color: "var(--text-mute)", marginBottom: 20 }}>
          Adicione temas do seu PPP, projetos do ano, ou eixos curriculares. Escolha o escopo: toda a escola, por segmento, ou por série específica.
        </div>

        {/* Seletor de escopo */}
        <div style={{ marginBottom: 14 }}>
          <div style={{ fontSize: 11.5, fontWeight: 700, color: "var(--text-mute)", textTransform: "uppercase", letterSpacing: 0.8, marginBottom: 8 }}>
            Aplicar a
          </div>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
            <button onClick={() => setScope("all")} style={scopeBtnStyle(scope === "all", "var(--teal-dark)")}>
              Toda a escola
            </button>
            {SEGMENTS.map(seg => (
              <button key={seg.id} onClick={() => setScope("seg:"+seg.id)} style={scopeBtnStyle(scope === "seg:"+seg.id, seg.c)}>
                {seg.label}
              </button>
            ))}
          </div>
          <div style={{ marginTop: 10 }}>
            <div style={{ fontSize: 10.5, fontWeight: 600, color: "var(--text-mute)", textTransform: "uppercase", letterSpacing: 0.6, marginBottom: 6 }}>
              Ou por série específica
            </div>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
              {SEGMENTS.flatMap(s => s.series).map(sr => (
                <button key={sr} onClick={() => setScope("ser:"+sr)} style={{
                  ...scopeBtnStyle(scope === "ser:"+sr, "var(--blue)"),
                  fontSize: 12, padding: "5px 11px",
                }}>
                  {sr}
                </button>
              ))}
            </div>
          </div>
        </div>

        {/* Input */}
        <div style={{ display: "flex", gap: 10, marginTop: 6 }}>
          <input
            value={input}
            onChange={e => setInput(e.target.value)}
            onKeyDown={e => { if (e.key === "Enter") addCustom(); }}
            placeholder={`Ex: Bullying, Combate ao racismo, Ecoalfabetização…`}
            style={{
              flex: 1, padding: "12px 16px",
              border: "1.5px solid var(--border)", borderRadius: 10,
              fontSize: 14, background: "var(--bg-soft)",
              color: "var(--text)", outline: "none",
            }}
            onFocus={e => e.currentTarget.style.borderColor = scopeColor(scope)}
            onBlur={e => e.currentTarget.style.borderColor = "var(--border)"}
          />
          <BtnTeal onClick={addCustom} style={{ padding: "12px 22px", whiteSpace: "nowrap" }}>
            + Adicionar em {scopeLabel(scope)}
          </BtnTeal>
        </div>

        {/* Lista de temas por escopo */}
        {totalCustom > 0 && (
          <div style={{ marginTop: 22, display: "flex", flexDirection: "column", gap: 14 }}>
            {Object.entries(customThemes).filter(([, l]) => l.length > 0).map(([sc, list]) => (
              <div key={sc} style={{
                padding: "14px 16px", background: "var(--bg-light)",
                border: `1px solid var(--border)`, borderRadius: 12,
                borderLeft: `4px solid ${scopeColor(sc)}`,
              }}>
                <div style={{ fontSize: 11.5, fontWeight: 700, color: scopeColor(sc), textTransform: "uppercase", letterSpacing: 0.8, marginBottom: 8 }}>
                  {scopeLabel(sc)} · {list.length} tema{list.length !== 1 ? "s" : ""}
                </div>
                <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
                  {list.map(t => (
                    <span key={t} style={{
                      display: "inline-flex", alignItems: "center", gap: 8,
                      padding: "6px 6px 6px 14px",
                      background: "#fff", border: `1.5px solid ${scopeColor(sc)}40`,
                      borderRadius: 20, fontSize: 13.5, fontWeight: 600, color: "var(--text)",
                    }}>
                      {t}
                      <button onClick={() => removeCustom(sc, t)} style={{
                        width: 22, height: 22, borderRadius: "50%",
                        background: "var(--bg-light)", color: "var(--text-mute)",
                        display: "inline-flex", alignItems: "center", justifyContent: "center",
                        fontSize: 14, lineHeight: 1, fontWeight: 700,
                      }}>×</button>
                    </span>
                  ))}
                </div>
              </div>
            ))}
          </div>
        )}

        {totalCustom === 0 && (
          <div style={{
            marginTop: 18, padding: "16px 18px",
            background: "var(--bg-soft)", border: "1px dashed var(--border)",
            borderRadius: 12, fontSize: 13.5, color: "var(--text-mute)", textAlign: "center",
          }}>
            Nenhum tema próprio ainda. Você pode seguir só com os da biblioteca acima, ou adicionar seus temas por segmento ou série.
          </div>
        )}
      </div>

      {/* Resumo */}
      <div style={{
        marginTop: 20, padding: "14px 18px",
        background: "#fff", border: "1px solid var(--border)", borderRadius: 12,
        fontSize: 14, color: "var(--text-mute)",
        display: "flex", alignItems: "center", gap: 12, flexWrap: "wrap",
      }}>
        <span><span style={{color: "var(--teal)", fontWeight: 700}}>{selected.length}</span> temas da biblioteca</span>
        <span style={{color: "var(--border)"}}>·</span>
        <span><span style={{color: "var(--blue)", fontWeight: 700}}>{totalCustom}</span> temas próprios</span>
        <span style={{ marginLeft: "auto", color: "var(--teal-dark)", fontSize: 13 }}>
          Sugestão: 3 a 6 temas principais no total
        </span>
      </div>
    </div>
  );
}

function scopeBtnStyle(active, color) {
  return {
    padding: "7px 14px",
    borderRadius: 20,
    border: `1.5px solid ${active ? color : "var(--border)"}`,
    background: active ? color : "#fff",
    color: active ? "#fff" : "var(--text)",
    fontSize: 13, fontWeight: 600,
    transition: "all 0.12s",
    cursor: "pointer",
  };
}

// Step 4: Scolex (EN + PT em colunas)
function Step3_Scolex() {
  const { data, setData } = useApp();
  const cEN = data.scolexEN;
  const cPT = data.scolexPT;
  const setEN = (v) => setData(d => ({...d, scolexEN: v }));
  const setPT = (v) => setData(d => ({...d, scolexPT: v }));

  const Column = ({ lang, langLabel, flag, c, set, files, filesKey, connectedNote, themeColor }) => (
    <div style={{
      background: "#fff", border: "1px solid var(--border)", borderRadius: 18,
      padding: 22, boxShadow: "var(--shadow-sm)",
      display: "flex", flexDirection: "column", gap: 14,
    }}>
      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
        <div style={{
          width: 38, height: 38, borderRadius: 10,
          background: themeColor, color: "#fff",
          display: "inline-flex", alignItems: "center", justifyContent: "center",
          fontSize: 18, fontWeight: 800, letterSpacing: 0.4,
        }}>{flag}</div>
        <div>
          <div style={{ fontSize: 11, fontWeight: 700, color: "var(--text-mute)", textTransform: "uppercase", letterSpacing: 0.8 }}>{langLabel}</div>
          <div style={{ fontSize: 17, fontWeight: 800, color: "var(--text)" }}>Nível <Scolex/> em {lang}</div>
        </div>
      </div>

      <OptionCard selected={c === "connected"} onClick={() => set("connected")}>
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <div style={{ fontSize: 22 }}>🔗</div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 14, fontWeight: 700 }}>A escola já usa <Scolex/></div>
            <div style={{ fontSize: 12.5, color: "var(--text-mute)", marginTop: 2 }}>Eu conecto e puxo os níveis atualizados.</div>
          </div>
        </div>
        {c === "connected" && (
          <div style={{
            marginTop: 10, padding: "8px 12px", background: "var(--bg-light)",
            border: "1px solid var(--teal)", borderRadius: 8, fontSize: 12,
            display: "flex", gap: 6, alignItems: "center",
          }}>
            <span style={{ color: "var(--teal)" }}>●</span> {connectedNote}
          </div>
        )}
      </OptionCard>

      <OptionCard selected={c === "upload"} onClick={() => set("upload")}>
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <div style={{ fontSize: 22 }}>📊</div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 14, fontWeight: 700 }}>Subir uma planilha</div>
            <div style={{ fontSize: 12.5, color: "var(--text-mute)", marginTop: 2 }}>Excel/CSV com aluno, série e nível.</div>
          </div>
        </div>
      </OptionCard>

      {c === "upload" && (
        <UploadZone
          label={`Planilha de níveis em ${lang.toLowerCase()}`}
          accept=".xlsx,.csv"
          files={files}
          onAdd={names => setData(d => ({...d, [filesKey]: [...(d[filesKey]||[]), ...names] }))}
        />
      )}

      <OptionCard selected={c === "none"} onClick={() => set("none")}>
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <div style={{ fontSize: 20 }}>⚠️</div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 13.5, fontWeight: 700 }}>Não temos esses dados</div>
            <div style={{ fontSize: 12, color: "var(--text-mute)", marginTop: 2 }}>Eu aproximo por série.</div>
          </div>
        </div>
      </OptionCard>
    </div>
  );

  return (
    <div>
      <Heading
        eyebrow="Preparação · Passo 1, Dados dos alunos"
        title={<>Vocês têm o nível <Scolex/> dos alunos?</>}
        subtitle={<>O <Scolex/> é o que me permite recomendar livros com a complexidade léxica certa pra cada turma. Quanto mais preciso, melhor a lista, em <strong>Português</strong> e em <strong>Inglês</strong>.</>} />
      <LexBubble>
        Se a escola já usa o <strong><Scolex/></strong>, eu puxo direto. Se você tem planilha, sobe aqui. Sem esses dados eu faço uma aproximação, explico no próximo passo.
      </LexBubble>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18, marginTop: 28 }}>
        <Column
          lang="Português" langLabel="Idioma principal" flag="PT"
          c={cPT} set={setPT}
          files={data.ptFiles} filesKey="ptFiles"
          connectedNote="Conectado · 412 alunos · média Scolex®-PT 523"
          themeColor="#2f97a1"
        />
        <Column
          lang="Inglês" langLabel="Segundo idioma" flag="EN"
          c={cEN} set={setEN}
          files={data.enFiles} filesKey="enFiles"
          connectedNote="Conectado · 387 alunos com Scolex®-EN"
          themeColor="#2c4ffc"
        />
      </div>

      <ExtraLanguagesSubQuestion />
    </div>
  );
}

// Sub-pergunta: outros idiomas trabalhados pela escola (sem Scolex® disponível).
// Define data.extraLangs (ex.: ["es","fr","de"]), propaga p/ Calibragem e Didáticos.
function ExtraLanguagesSubQuestion() {
  const { data, setData } = useApp();
  const extras = data.extraLangs || [];
  const toggle = (code) => setData(d => {
    const cur = d.extraLangs || [];
    return { ...d, extraLangs: cur.includes(code) ? cur.filter(c => c !== code) : [...cur, code] };
  });
  const LANGS = [
    { code: "es", label: "Espanhol", flag: "ES", color: "#e0a800" },
    { code: "fr", label: "Francês",  flag: "FR", color: "#0055a4" },
    { code: "de", label: "Alemão",   flag: "DE", color: "#1a1a1a" },
  ];
  return (
    <div style={{
      marginTop: 28, padding: "20px 22px",
      background: "#fff", border: "1px dashed var(--border)", borderRadius: 14,
    }}>
      <div style={{ display: "flex", gap: 14, alignItems: "flex-start" }}>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 12, fontWeight: 700, color: "var(--text-mute)", textTransform: "uppercase", letterSpacing: 0.8 }}>
            Sub-pergunta · idiomas adicionais
          </div>
          <div style={{ fontSize: 15.5, fontWeight: 800, color: "var(--text)", marginTop: 4, letterSpacing: -0.2 }}>
            A escola trabalha com mais algum idioma além de PT e EN?
          </div>
          <div style={{ fontSize: 12.5, color: "var(--text-mute)", marginTop: 2, lineHeight: 1.5 }}>
            Pra esses, ainda não temos <Scolex/>, uso aproximação por série. A escolha aqui aparece na Calibragem e nos Didáticos.
          </div>
        </div>
      </div>
      <div style={{ display: "flex", gap: 10, marginTop: 14, flexWrap: "wrap" }}>
        {LANGS.map(l => {
          const sel = extras.includes(l.code);
          return (
            <button key={l.code} type="button" onClick={() => toggle(l.code)}
              style={{
                display: "inline-flex", alignItems: "center", gap: 8,
                padding: "8px 14px", borderRadius: 999, cursor: "pointer",
                border: sel ? `2px solid ${l.color}` : "1.5px solid var(--border)",
                background: sel ? `${l.color}15` : "#fff",
                fontSize: 13, fontWeight: 700, color: sel ? l.color : "var(--text)",
                transition: "all .15s",
              }}>
              <span style={{
                width: 22, height: 22, borderRadius: 5, background: l.color, color: "#fff",
                display: "inline-flex", alignItems: "center", justifyContent: "center",
                fontSize: 10, fontWeight: 800, letterSpacing: 0.3,
              }}>{l.flag}</span>
              {l.label}
              {sel && <span style={{ fontSize: 11 }}>✓</span>}
            </button>
          );
        })}
      </div>
    </div>
  );
}

// Calibragem, primeiro passo da Curadoria Literária.
// Combina: resumo da coleta + "quantos livros por série/ano".
function Step5_Calibration() {
  const { data, setData } = useApp();
  const hasNone = data.scolexEN === "none" || data.scolexPT === "none";
  const hasEN = data.scolexEN !== "none";
  const extras = data.extraLangs || [];

  const EXTRA_META = {
    es: { label: "Espanhol", flag: "ES", color: "#e0a800" },
    fr: { label: "Francês",  flag: "FR", color: "#0055a4" },
    de: { label: "Alemão",   flag: "DE", color: "#1a1a1a" },
  };

  const qtyPT = data.qtyPerYearPT ?? 3;
  const qtyEN = hasEN ? (data.qtyPerYearEN ?? 2) : 0;
  const qtyExtras = data.qtyPerYearExtras || {};
  const extraTotal = extras.reduce((s, c) => s + (qtyExtras[c] ?? 0), 0);
  const qty = qtyPT + qtyEN + extraTotal;
  const setPT = v => setData(d => ({ ...d, qtyPerYearPT: v }));
  const setEN = v => setData(d => ({ ...d, qtyPerYearEN: v }));
  const setExtra = (code, v) => setData(d => ({ ...d, qtyPerYearExtras: { ...(d.qtyPerYearExtras || {}), [code]: v } }));

  const collectRows = [
    { k: <>Base histórica</>, v: data.pastListChoice === "upload" ? `${(data.pastListFiles||[]).length} arquivo(s)` : "Primeira vez", ok: !!data.pastListChoice },
    { k: "Diretrizes pedagógicas", v: `${(data.themes||[]).length} tema(s) selecionado(s)`, ok: (data.themes||[]).length > 0 },
    { k: <><Scolex/> · Português</>, v: data.scolexPT === "connected" ? "Conectado · 412 alunos" : data.scolexPT === "upload" ? `${(data.ptFiles||[]).length} planilha(s)` : data.scolexPT === "none" ? "Aproximação por série" : "—", ok: !!data.scolexPT && data.scolexPT !== "none" },
    { k: <><Scolex/> · Inglês</>, v: data.scolexEN === "connected" ? "Conectado · 387 alunos" : data.scolexEN === "upload" ? `${(data.enFiles||[]).length} planilha(s)` : data.scolexEN === "none" ? "Aproximação por série" : "—", ok: !!data.scolexEN && data.scolexEN !== "none" },
    ...(extras.length ? [{ k: "Idiomas adicionais", v: extras.map(c => EXTRA_META[c]?.label).join(" · "), ok: true, note: "Aproximação por série" }] : []),
  ];

  return (
    <div>
      <PremiumHeader
        image="assets/lex-curadoria-calibragem.png"
        imageAlt="Lex calibrada na biblioteca"
        eyebrow="Curadoria Literária · Passo 1, Calibragem"
        title="Tudo calibrado, pronto pra recomendar"
        subtitle={hasNone
          ? "Onde faltarem dados Scolex®, eu uso aproximação por série. A recomendação fica boa, mas o ideal é fazer o diagnóstico pra personalização por aluno."
          : "Com tudo coletado, consigo recomendar livros na zona de leitura ideal de cada série, onde o aluno se desafia sem desanimar."}
      />

      <div style={{ marginTop: 24, display: "grid", gridTemplateColumns: "1.2fr 1fr", gap: 18, alignItems: "start" }}>
        {/* Resumo da coleta */}
        <div style={{
          background: "#fff", border: "1px solid var(--border)",
          borderRadius: 16, padding: 22, boxShadow: "var(--shadow-sm)",
        }}>
          <div style={{ fontSize: 12, fontWeight: 700, color: "var(--teal-dark)", textTransform: "uppercase", letterSpacing: 1, marginBottom: 14 }}>
            Resumo da coleta
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {collectRows.map((r, i) => (
              <div key={i} style={{
                padding: "12px 14px", background: "var(--bg-light)",
                border: "1px solid var(--border)", borderRadius: 10,
                display: "flex", gap: 12, alignItems: "center",
              }}>
                <div style={{
                  width: 22, height: 22, borderRadius: "50%",
                  background: r.ok ? "var(--teal)" : "#bbb",
                  color: "#fff", fontSize: 11, fontWeight: 700,
                  display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0,
                }}>{r.ok ? "✓" : "—"}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 11, color: "var(--text-mute)", fontWeight: 700, textTransform: "uppercase", letterSpacing: 0.5 }}>{r.k}</div>
                  <div style={{ fontSize: 13.5, color: "var(--text)", fontWeight: 600, marginTop: 1 }}>{r.v}</div>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Quantos livros por série/ano?, sliders separados PT/EN */}
        <div style={{
          background: "#fff", border: "1px solid var(--border)",
          borderRadius: 16, padding: 22, boxShadow: "var(--shadow-sm)",
        }}>
          <div style={{ fontSize: 12, fontWeight: 700, color: "var(--teal-dark)", textTransform: "uppercase", letterSpacing: 1 }}>
            Volume da curadoria
          </div>
          <div style={{ fontSize: 17, fontWeight: 800, color: "var(--text)", marginTop: 8, letterSpacing: -0.3 }}>
            Quantos livros por série, por ano?
          </div>
          <div style={{ fontSize: 13, color: "var(--text-mute)", marginTop: 4, lineHeight: 1.5 }}>
            Eu cuido da curadoria, você define o volume por idioma.
          </div>

          {/* Slider PT */}
          <div style={{ marginTop: 22 }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 6 }}>
              <div style={{ fontSize: 13, fontWeight: 700, color: "var(--text)" }}>Português</div>
              <div><span style={{ fontSize: 28, fontWeight: 800, color: "var(--teal-dark)", letterSpacing: -1 }}>{qtyPT}</span><span style={{ fontSize: 12, color: "var(--text-mute)", marginLeft: 4 }}>livros</span></div>
            </div>
            <input type="range" min={0} max={8} value={qtyPT} onChange={e => setPT(+e.target.value)}
              style={{ width: "100%", accentColor: "var(--teal)" }} />
            <div style={{ display: "flex", justifyContent: "space-between", fontSize: 10.5, color: "var(--text-mute)", marginTop: 2 }}>
              <span>0</span><span>8</span>
            </div>
          </div>

          {/* Slider EN */}
          <div style={{ marginTop: 18, opacity: hasEN ? 1 : 0.4 }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 6 }}>
              <div style={{ fontSize: 13, fontWeight: 700, color: "var(--text)" }}>Inglês</div>
              <div><span style={{ fontSize: 28, fontWeight: 800, color: "#2c4ffc", letterSpacing: -1 }}>{qtyEN}</span><span style={{ fontSize: 12, color: "var(--text-mute)", marginLeft: 4 }}>livros</span></div>
            </div>
            <input type="range" min={0} max={8} value={qtyEN} disabled={!hasEN} onChange={e => setEN(+e.target.value)}
              style={{ width: "100%", accentColor: "#2c4ffc" }} />
            <div style={{ display: "flex", justifyContent: "space-between", fontSize: 10.5, color: "var(--text-mute)", marginTop: 2 }}>
              <span>0</span><span>{hasEN ? "8" : "Sem inglês"}</span>
            </div>
          </div>

          {/* Sliders extras (ES/FR/DE) */}
          {extras.map(code => {
            const m = EXTRA_META[code]; if (!m) return null;
            const v = qtyExtras[code] ?? 1;
            return (
              <div key={code} style={{ marginTop: 18 }}>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 6 }}>
                  <div style={{ fontSize: 13, fontWeight: 700, color: "var(--text)", display: "flex", alignItems: "center", gap: 6 }}>
                    {m.label}
                    <span style={{ fontSize: 9.5, fontWeight: 700, padding: "2px 5px", borderRadius: 4, background: "#f4f4f4", color: "var(--text-mute)", letterSpacing: 0.3 }}>APROX. POR SÉRIE</span>
                  </div>
                  <div><span style={{ fontSize: 28, fontWeight: 800, color: m.color, letterSpacing: -1 }}>{v}</span><span style={{ fontSize: 12, color: "var(--text-mute)", marginLeft: 4 }}>livros</span></div>
                </div>
                <input type="range" min={0} max={6} value={v} onChange={e => setExtra(code, +e.target.value)}
                  style={{ width: "100%", accentColor: m.color }} />
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: 10.5, color: "var(--text-mute)", marginTop: 2 }}>
                  <span>0</span><span>6</span>
                </div>
              </div>
            );
          })}

          {/* Total */}
          <div style={{ marginTop: 18, padding: "12px 14px", background: "var(--bg-light)", borderRadius: 10, display: "flex", justifyContent: "space-between", alignItems: "center" }}>
            <div style={{ fontSize: 12.5, color: "var(--text)" }}>
              <strong>{qty}</strong> {qty === 1 ? "livro" : "livros"} por série<span style={{ color: "var(--text-mute)" }}> · 12 séries × {qty} = <strong style={{ color: "var(--text)" }}>{qty * 12}</strong> total</span>
            </div>
          </div>
        </div>
      </div>

      {hasNone && (
        <div style={{
          marginTop: 18, padding: "14px 18px",
          background: "linear-gradient(90deg, rgba(44,79,252,0.06), rgba(47,151,161,0.06))",
          border: "1px solid var(--blue)", borderRadius: 12,
          display: "flex", gap: 14, alignItems: "center",
        }}>
          <div style={{ fontSize: 22 }}>💡</div>
          <div style={{ fontSize: 13.5, lineHeight: 1.5, color: "var(--text)" }}>
            <strong>Quer a personalização ideal?</strong> Agende o <a href="#" style={{ color: "var(--blue)", fontWeight: 700, textDecoration: "none" }}>diagnóstico <Scolex/></a> esse mês, 10 min por aluno, resultado em 48h.
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { THEMES, SEGMENTS, Step0_Welcome, Step1_Calendar, Step1_PastList, Step2_Themes, Step3_Scolex, Step5_Calibration });
