/* eslint-disable */
// ============================================================
// Screens 3+4+5+7 — Episode Player Shell (interactive)
// Walks the user through S1 Hook → S2 Concepto → S3 Lab → S4 Memo
// for M00.E00 — "Dos empresas, mismo P/E"
// ============================================================

function EpisodePlayer({ tweaks }) {
  const ep = window.FZ_EPISODE;
  const [step, setStep] = useState(0); // 0..3
  const [prediction, setPrediction] = useState("");
  const [chosen, setChosen] = useState(null); // 'tessari' | 'lormac' | 'insuf'
  const [calc, setCalc] = useState({ tessari: {}, lormac: {} });
  const [memo, setMemo] = useState("");
  const stepperLayout = tweaks?.stepperLayout || "horizontal";

  const goNext = () => setStep((s) => Math.min(3, s + 1));
  const goPrev = () => setStep((s) => Math.max(0, s - 1));

  return (
    <div style={{
      background: "var(--paper)", minHeight: 1100, fontFamily: "var(--sans)"
    }}>
      {/* Top chrome */}
      <header style={{
        padding: "18px 40px", borderBottom: "1px solid var(--rule)",
        background: "var(--card-elev)",
        display: "flex", alignItems: "center", justifyContent: "space-between"
      }}>
        <div style={{ display: "flex", alignItems: "center", gap: 18 }}>
          <FinazMark size={16} />
          <span style={{ fontSize: 12, color: "var(--ink-3)" }}>›</span>
          <a style={{ fontSize: 12, color: "var(--ink-3)" }}>C04-A</a>
          <span style={{ fontSize: 12, color: "var(--ink-3)" }}>›</span>
          <a style={{ fontSize: 12, color: "var(--ink-3)" }}>M00 · Diagnóstico</a>
          <span style={{ fontSize: 12, color: "var(--ink-3)" }}>›</span>
          <span style={{ fontSize: 12, color: "var(--ink)" }}>{ep.id}</span>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
          <span className="t-mono" style={{ fontSize: 11, color: "var(--ink-3)" }}>
            Paso {step + 1}/4 · {ep.steps[step].minutes} min
          </span>
          <button className="btn ghost small">Notas</button>
          <button className="btn ghost small">Guardar y salir</button>
        </div>
      </header>

      {/* Title strip */}
      <div style={{ padding: "32px 40px 0", maxWidth: 1400, margin: "0 auto" }}>
        <ModuleRibbon code={ep.module.split(" · ")[0]} title={ep.module.split(" · ")[1]} />
        <h1 className="t-display" style={{ fontSize: 40, margin: "12px 0 8px", maxWidth: 900, lineHeight: 1.1 }}>
          {ep.title}
        </h1>
        <div style={{
          fontFamily: "var(--serif)", fontStyle: "italic", fontSize: 18, color: "var(--accent)",
          marginBottom: 18
        }}>“{ep.big_question}”</div>
      </div>

      {/* Stepper */}
      <Stepper steps={ep.steps} active={step} layout={stepperLayout} onJump={setStep} />

      {/* Body */}
      <div style={{
        display: "grid",
        gridTemplateColumns: tweaks?.glossaryMode === "sidebar" ? "1fr 300px" : "1fr",
        gap: 24,
        padding: "24px 40px 80px",
        maxWidth: 1400,
        margin: "0 auto"
      }}>
        <div>
          {step === 0 && <HookPanel prediction={prediction} setPrediction={setPrediction} />}
          {step === 1 && <ConceptoPanel />}
          {step === 2 && (
            <LabPanel
              calc={calc} setCalc={setCalc}
              chosen={chosen} setChosen={setChosen}
              prediction={prediction}
              tweaks={tweaks}
            />
          )}
          {step === 3 && (
            <MemoPanel memo={memo} setMemo={setMemo} chosen={chosen} prediction={prediction} />
          )}

          {/* footer nav */}
          <div style={{
            display: "flex", justifyContent: "space-between", alignItems: "center",
            marginTop: 32, paddingTop: 20, borderTop: "1px solid var(--rule)"
          }}>
            <button className="btn" onClick={goPrev} disabled={step === 0} style={{ opacity: step === 0 ? 0.5 : 1 }}>
              ← Anterior
            </button>
            <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
              {ep.steps.map((s, i) => (
                <span key={s.key}
                  className={`dot ${i === step ? "active" : i < step ? "done" : ""}`} />
              ))}
            </div>
            {step < 3 ? (
              <button className="btn primary" onClick={goNext}>
                Continuar a {ep.steps[step + 1].label} →
              </button>
            ) : (
              <button className="btn primary">Enviar para feedback →</button>
            )}
          </div>
        </div>

        <GlossarySidebar />
      </div>
    </div>
  );
}

// ----------------------------------------------------------------
// Stepper — supports horizontal, vertical (sidebar), tabs
// ----------------------------------------------------------------
function Stepper({ steps, active, layout, onJump }) {
  if (layout === "vertical") {
    return (
      <div style={{
        position: "absolute", marginLeft: -260, width: 240,
        // we still render inline below as fallback — but vertical works nicely as a sidebar
      }}>
      </div>
    );
  }

  if (layout === "tabs") {
    return (
      <div style={{
        maxWidth: 1400, margin: "0 auto", padding: "0 40px",
        display: "flex", borderBottom: "1px solid var(--rule)"
      }}>
        {steps.map((s, i) => (
          <button key={s.key}
            onClick={() => onJump(i)}
            style={{
              border: 0, background: "transparent", padding: "14px 22px",
              fontSize: 14, color: i === active ? "var(--ink)" : "var(--ink-3)",
              fontFamily: "var(--sans)", cursor: "pointer",
              borderBottom: i === active ? "2px solid var(--accent)" : "2px solid transparent",
              marginBottom: -1
            }}>
            <span className="t-label" style={{ display: "block", marginBottom: 4, color: i === active ? "var(--accent)" : "var(--ink-3)" }}>
              {s.key}
            </span>
            <span style={{ fontWeight: 500 }}>{s.label}</span>
          </button>
        ))}
      </div>
    );
  }

  // horizontal (default)
  return (
    <div style={{ maxWidth: 1400, margin: "8px auto 0", padding: "0 40px" }}>
      <div style={{
        display: "flex", alignItems: "center", gap: 8,
        background: "var(--card)", border: "1px solid var(--rule)", borderRadius: 12,
        padding: 8
      }}>
        {steps.map((s, i) => {
          const done = i < active;
          const isActive = i === active;
          return (
            <React.Fragment key={s.key}>
              <button onClick={() => onJump(i)} style={{
                flex: 1, border: 0, background: isActive ? "var(--accent)" : "transparent",
                color: isActive ? "var(--paper)" : "var(--ink-2)",
                padding: "10px 14px", borderRadius: 8, cursor: "pointer",
                display: "flex", alignItems: "center", gap: 12, textAlign: "left",
                fontFamily: "var(--sans)"
              }}>
                <span style={{
                  width: 24, height: 24, borderRadius: "50%",
                  background: isActive ? "var(--paper)" : done ? "var(--green)" : "var(--paper-2)",
                  color: isActive ? "var(--accent)" : done ? "var(--paper)" : "var(--ink-3)",
                  display: "flex", alignItems: "center", justifyContent: "center",
                  fontSize: 11, fontFamily: "var(--mono)", fontWeight: 600
                }}>{done ? "✓" : s.key.replace("S", "")}</span>
                <div style={{ display: "flex", flexDirection: "column" }}>
                  <span style={{ fontSize: 13, fontWeight: 500 }}>{s.label}</span>
                  <span className="t-mono" style={{
                    fontSize: 10, color: isActive ? "rgba(243,239,229,0.7)" : "var(--ink-3)",
                    letterSpacing: 0.04
                  }}>{s.title}</span>
                </div>
              </button>
              {i < steps.length - 1 && <span style={{ color: "var(--ink-4)" }}>→</span>}
            </React.Fragment>
          );
        })}
      </div>
    </div>
  );
}

// ----------------------------------------------------------------
// S1 Hook — narrative + prediction
// ----------------------------------------------------------------
function HookPanel({ prediction, setPrediction }) {
  const dialogue = window.FZ_DIALOGUE;
  return (
    <div className="anim-in">
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 32 }}>
        {/* Narrative */}
        <div className="card" style={{ padding: 28, background: "var(--card-elev)" }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 18 }}>
            <span className="t-label">S1 · Hook narrativo</span>
            <div style={{ display: "flex", gap: 6 }}>
              <button className="btn small ghost" title="Reproducir locución">▶ Audio</button>
              <button className="btn small ghost">Transcripción</button>
            </div>
          </div>
          <div style={{
            fontFamily: "var(--serif)", fontSize: 26, fontWeight: 500, lineHeight: 1.25,
            marginBottom: 24, color: "var(--ink)"
          }}>
            Mismo P/E. Mismo sector. Dos historias completamente distintas.
          </div>

          <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            {dialogue.map((d, i) => (
              <DialogueBubble key={i} {...d} />
            ))}
          </div>

          <div style={{
            marginTop: 24, padding: "12px 14px", background: "var(--paper-2)", borderRadius: 8,
            display: "flex", gap: 10, fontSize: 12, color: "var(--ink-2)"
          }}>
            <span style={{ fontFamily: "var(--serif)", fontStyle: "italic", color: "var(--accent)", fontSize: 16, lineHeight: 1 }}>“</span>
            <span style={{ lineHeight: 1.5 }}>
              <strong style={{ color: "var(--ink)" }}>El múltiplo es síntoma, no diagnóstico.</strong>{" "}
              Aprenderemos a leerlo condicionado por crecimiento, ROE y coste del capital.
            </span>
          </div>
        </div>

        {/* Prediction */}
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <div className="card" style={{ padding: 28 }}>
            <div className="t-label" style={{ marginBottom: 8 }}>Predicción inicial · obligatoria</div>
            <div style={{
              fontFamily: "var(--serif)", fontSize: 20, fontWeight: 500, lineHeight: 1.25,
              marginBottom: 14, color: "var(--ink)"
            }}>
              Antes de calcular, ¿qué empresa esperas que merezca premium?
            </div>
            <p style={{ fontSize: 13, color: "var(--ink-2)", lineHeight: 1.5, marginTop: 0, marginBottom: 16 }}>
              No vale "no sé". Escribe tu apuesta y el motivo. Comparamos contra tu cálculo al final del episodio.
            </p>
            <textarea
              value={prediction}
              onChange={(e) => setPrediction(e.target.value)}
              placeholder="Mi apuesta es que la Empresa __ merece premium porque…"
              rows={5}
              style={{ resize: "vertical", lineHeight: 1.5 }}
            />
            <div style={{
              display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 10
            }}>
              <span className="t-mono" style={{ fontSize: 11, color: "var(--ink-3)" }}>
                {prediction.split(/\s+/).filter(Boolean).length} palabras · mín. 15
              </span>
              <span className="chip green" style={{ visibility: prediction.length > 80 ? "visible" : "hidden" }}>
                ✓ guardada
              </span>
            </div>
          </div>

          <div className="card" style={{ padding: 20, background: "var(--paper-2)", borderColor: "var(--rule-soft)" }}>
            <div className="t-label" style={{ marginBottom: 10 }}>Objetivo de este episodio</div>
            <div style={{ fontSize: 13, color: "var(--ink-2)", lineHeight: 1.55, marginBottom: 12 }}>
              {window.FZ_EPISODE.objective}
            </div>
            <ul style={{ margin: 0, paddingLeft: 16, color: "var(--ink-2)", fontSize: 12, lineHeight: 1.6 }}>
              {window.FZ_EPISODE.success.map((s) => <li key={s}>{s}</li>)}
            </ul>
          </div>
        </div>
      </div>
    </div>
  );
}

function DialogueBubble({ who, role, text }) {
  const colorMap = {
    "Sofía": "var(--accent)",
    "Mateo": "var(--gold)",
    "Tutor Finaz": "var(--green)"
  };
  return (
    <div style={{ display: "flex", gap: 12, alignItems: "flex-start" }}>
      <div style={{
        width: 32, height: 32, borderRadius: "50%", background: colorMap[who] || "var(--ink-3)",
        color: "var(--paper)", display: "flex", alignItems: "center", justifyContent: "center",
        fontFamily: "var(--serif)", fontWeight: 500, fontSize: 14, flexShrink: 0
      }}>{who[0]}</div>
      <div>
        <div style={{ fontSize: 12, color: "var(--ink-3)", marginBottom: 2 }}>
          <strong style={{ color: "var(--ink)", fontWeight: 500 }}>{who}</strong> · {role}
        </div>
        <div style={{ fontSize: 14, color: "var(--ink-2)", lineHeight: 1.5 }}>{text}</div>
      </div>
    </div>
  );
}

// ----------------------------------------------------------------
// S2 Concepto — annotated formula
// ----------------------------------------------------------------
function ConceptoPanel() {
  return (
    <div className="anim-in" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 32 }}>
      <div>
        <span className="t-label">S2 · Concepto anotado</span>
        <h2 className="t-display" style={{ fontSize: 30, margin: "8px 0 14px", lineHeight: 1.15 }}>
          P/E teórico de Gordon — calibrar antes de comparar.
        </h2>
        <p style={{ fontFamily: "var(--serif)", fontSize: 17, color: "var(--ink-2)", lineHeight: 1.5, marginTop: 0 }}>
          Dos empresas pueden compartir un mismo <GlossTerm k="p_e">P/E</GlossTerm> y, sin embargo,
          una merecer premium y la otra descuento. La fórmula de <GlossTerm k="gordon">Gordon</GlossTerm> permite
          estimar qué <span className="t-mono">P/E*</span> justifican los fundamentales — y leer el mercado a la luz de esa referencia.
        </p>

        <div className="card" style={{ padding: 24, marginTop: 20, background: "var(--card-elev)" }}>
          <div className="t-label" style={{ marginBottom: 10 }}>Fórmula</div>
          <div className="t-mono" style={{
            fontSize: 26, color: "var(--ink)", letterSpacing: "-0.02em", lineHeight: 1.4,
            padding: "18px 0", textAlign: "center",
            borderTop: "1px solid var(--rule-soft)", borderBottom: "1px solid var(--rule-soft)",
            marginBottom: 16
          }}>
            <span style={{ color: "var(--ink-3)" }}>P/E* = </span>
            <span style={{ display: "inline-block", verticalAlign: "middle" }}>
              <span style={{ display: "block", borderBottom: "1px solid var(--ink)", padding: "0 8px" }}>
                1 − <GlossTerm k="growth">g</GlossTerm> / <GlossTerm k="roe">ROE</GlossTerm>
              </span>
              <span style={{ display: "block", padding: "0 8px" }}>
                <GlossTerm k="ke">Ke</GlossTerm> − g
              </span>
            </span>
          </div>

          <ul style={{ margin: 0, padding: 0, listStyle: "none", display: "flex", flexDirection: "column", gap: 10 }}>
            <li style={{ fontSize: 13, color: "var(--ink-2)", lineHeight: 1.5 }}>
              <strong style={{ color: "var(--ink)" }}>g</strong> — crecimiento sostenible
              <span style={{ color: "var(--ink-3)" }}> · no extrapolar el último año</span>
            </li>
            <li style={{ fontSize: 13, color: "var(--ink-2)", lineHeight: 1.5 }}>
              <strong style={{ color: "var(--ink)" }}>ROE</strong> — return on equity
              <span style={{ color: "var(--ink-3)" }}> · sostenibilidad pendiente de verificar</span>
            </li>
            <li style={{ fontSize: 13, color: "var(--ink-2)", lineHeight: 1.5 }}>
              <strong style={{ color: "var(--ink)" }}>Ke</strong> — coste del equity
              <span style={{ color: "var(--ink-3)" }}> · refleja el riesgo del negocio</span>
            </li>
          </ul>
        </div>
      </div>

      <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
        <div className="card" style={{ padding: 24 }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 12 }}>
            <div className="t-label">Mini-check de comprensión</div>
            <span className="chip">no puntúa</span>
          </div>
          <div style={{ fontSize: 14, color: "var(--ink), lineHeight: 1.5", marginBottom: 14 }}>
            ¿Puedes explicar Gordon <em>sin</em> repetir la fórmula? Sustituye los símbolos por la idea que esconden.
          </div>
          <ConceptCheck />
        </div>

        <div className="card" style={{ padding: 24, background: "var(--amber-tint)", borderColor: "transparent" }}>
          <div className="t-label" style={{ color: "var(--amber)", marginBottom: 8 }}>Confusión típica</div>
          <div style={{ fontSize: 14, color: "var(--ink), lineHeight: 1.5" }}>
            Tratar el P/E teórico como precio objetivo. <strong>No lo es.</strong> Es una calibración:
            si el observado se aleja del teórico, hay una historia que entender —
            no necesariamente un veredicto.
          </div>
        </div>

        <div style={{ display: "flex", gap: 8 }}>
          <span className="chip accent">+ 4 términos · añadidos a flashcards</span>
        </div>
      </div>
    </div>
  );
}

function ConceptCheck() {
  const [val, setVal] = useState("");
  const [submitted, setSubmitted] = useState(false);
  return (
    <div>
      <textarea
        value={val}
        onChange={(e) => setVal(e.target.value)}
        placeholder="Gordon dice que un P/E justo equivale a…"
        rows={3}
        style={{ resize: "vertical" }}
      />
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 8 }}>
        <span className="t-mono" style={{ fontSize: 11, color: "var(--ink-3)" }}>
          {val.length}/240
        </span>
        <button className="btn small" onClick={() => setSubmitted(true)}>Revisar</button>
      </div>
      {submitted && val.length > 30 && (
        <div className="anim-in" style={{
          marginTop: 12, padding: 12, background: "var(--green-tint)", borderRadius: 8,
          fontSize: 12, color: "var(--green)", lineHeight: 1.5
        }}>
          <strong>Bien.</strong> El P/E teórico premia el crecimiento <em>de calidad</em> (g pequeño respecto a ROE)
          y penaliza el riesgo (Ke alto). Que no es lo mismo que "crecer mucho".
        </div>
      )}
    </div>
  );
}

// ----------------------------------------------------------------
// S3 Lab — interactive calculator + comparison
// ----------------------------------------------------------------
function LabPanel({ calc, setCalc, chosen, setChosen, prediction, tweaks }) {
  const [a, b] = window.FZ_COMPANIES;

  const peStar = (c) => {
    const g = c.growth / 100;
    const roe = c.roe / 100;
    const ke = c.ke / 100;
    if (ke - g <= 0) return null;
    return ((1 - g / roe) / (ke - g));
  };

  const peStarA = peStar(a);
  const peStarB = peStar(b);
  const premiumA = peStarA ? (peStarA / a.pe - 1) * 100 : null;
  const premiumB = peStarB ? (peStarB / b.pe - 1) * 100 : null;

  return (
    <div className="anim-in">
      <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 18 }}>
        <div>
          <span className="t-label">S3 · Laboratorio CASE-X</span>
          <h2 className="t-display" style={{ fontSize: 28, margin: "6px 0 4px" }}>
            Calcula los drivers. Compara con el P/E observado.
          </h2>
          <div style={{ fontSize: 13, color: "var(--ink-3)" }}>
            Tolerancia ±5%. Los datos están etiquetados como pedagógicos / sintéticos.
          </div>
        </div>
        <div style={{ display: "flex", gap: 8 }}>
          <span className="chip">datos sintéticos</span>
          <span className="chip accent">CASE-X</span>
        </div>
      </div>

      {/* Two-company comparison */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, marginBottom: 24 }}>
        <CompanyCalcCard
          company={a} peStar={peStarA} premium={premiumA}
          chosen={chosen === a.id}
          style={tweaks?.calcStyle}
        />
        <CompanyCalcCard
          company={b} peStar={peStarB} premium={premiumB}
          chosen={chosen === b.id}
          style={tweaks?.calcStyle}
        />
      </div>

      {/* Side-by-side comparison strip */}
      <div className="card" style={{ padding: 24, background: "var(--card-elev)", marginBottom: 24 }}>
        <div className="t-label" style={{ marginBottom: 14 }}>Lectura comparada · señales</div>
        <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr 1fr 1fr", gap: 24, alignItems: "center" }}>
          <div className="t-label" style={{ color: "var(--ink-3)" }}>Driver</div>
          <div className="t-label" style={{ color: "var(--ink)" }}>{a.label} · {a.name}</div>
          <div className="t-label" style={{ color: "var(--ink)" }}>{b.label} · {b.name}</div>
          <div className="t-label" style={{ color: "var(--ink-3)" }}>Lectura</div>

          <ComparisonRow
            driver="Crecimiento sostenible (g)"
            vA={`${a.growth}%`} vB={`${b.growth}%`}
            winner="A"
            read="Tessari crece casi 4× más rápido y de forma orgánica."
          />
          <ComparisonRow
            driver="ROE"
            vA={`${a.roe}%`} vB={`${b.roe}%`}
            winner="A"
            read="ROE alto sostenido vs deteriorado en B."
          />
          <ComparisonRow
            driver="Coste del equity (Ke)"
            vA={`${a.ke}%`} vB={`${b.ke}%`}
            winner="A"
            read="Beta baja y deuda contenida en A; B con riesgo creciente."
          />
          <ComparisonRow
            driver="P/E* Gordon"
            vA={peStarA ? peStarA.toFixed(1) + "x" : "n/d"}
            vB={peStarB ? peStarB.toFixed(1) + "x" : "n/d"}
            winner={peStarA > peStarB ? "A" : "B"}
            read="A justifica >20x; B no llega al observado 14x."
            highlight
          />
        </div>
      </div>

      {/* Decision */}
      <div className="card" style={{
        padding: 28, background: "var(--card-elev)",
        borderColor: chosen ? "var(--accent)" : "var(--rule)"
      }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 18 }}>
          <div>
            <div className="t-label" style={{ marginBottom: 6 }}>Decisión · CASE-X</div>
            <div className="t-display" style={{ fontSize: 22, lineHeight: 1.2 }}>
              ¿Cuál merece premium hoy?
            </div>
          </div>
          <div style={{
            background: "var(--paper-2)", padding: "8px 12px", borderRadius: 8,
            fontFamily: "var(--mono)", fontSize: 11, color: "var(--ink-3)"
          }}>
            <span style={{ color: "var(--ink-2)" }}>Mantra:</span> dato → hipótesis → evidencia pendiente → lenguaje prudente
          </div>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 12, marginBottom: 16 }}>
          <ChoiceBtn
            label="A · Tessari merece premium"
            sub="Drivers superiores sostienen P/E > 14x"
            selected={chosen === "tessari"}
            onClick={() => setChosen("tessari")}
            tone="green"
          />
          <ChoiceBtn
            label="B · Lormac merece descuento"
            sub="Drivers no justifican 14x"
            selected={chosen === "lormac"}
            onClick={() => setChosen("lormac")}
            tone="red"
          />
          <ChoiceBtn
            label="Evidencia insuficiente"
            sub="Necesito más datos antes de decidir"
            selected={chosen === "insuf"}
            onClick={() => setChosen("insuf")}
            tone="amber"
          />
        </div>

        {chosen === "tessari" && (
          <div className="anim-in" style={{
            background: "var(--green-tint)", padding: 16, borderRadius: 10, fontSize: 13, lineHeight: 1.55,
            color: "var(--ink-2)"
          }}>
            <strong style={{ color: "var(--green)" }}>Coherente con los drivers.</strong>{" "}
            Tessari sostiene P/E ~ {peStarA.toFixed(1)}x según Gordon, frente a 14x observado. Antes de cerrar la tesis,
            verifica: <em>sostenibilidad del ROE a 5 años</em>, <em>capex de marca</em>, <em>concentración geográfica</em>.
          </div>
        )}
        {chosen === "lormac" && (
          <div className="anim-in" style={{
            background: "var(--red-tint)", padding: 16, borderRadius: 10, fontSize: 13, lineHeight: 1.55,
            color: "var(--ink-2)"
          }}>
            <strong style={{ color: "var(--red)" }}>Hipótesis consistente con los drivers.</strong>{" "}
            Sus fundamentales no justifican P/E 14x: Gordon indica ~{peStarB ? peStarB.toFixed(1) : "n/d"}x.
            Cuidado con concluir "cara": defiende "descuento justificado por g bajo y Ke creciente".
          </div>
        )}
        {chosen === "insuf" && (
          <div className="anim-in" style={{
            background: "var(--amber-tint)", padding: 16, borderRadius: 10, fontSize: 13, lineHeight: 1.55,
            color: "var(--ink-2)"
          }}>
            <strong style={{ color: "var(--amber)" }}>Respuesta válida y prudente.</strong>{" "}
            Antes de cerrar criterio: ¿qué evidencia falta? sostenibilidad del ROE, ciclo de capex,
            calidad del beneficio (recurrente vs one-off), pasivos fuera de balance.
          </div>
        )}
      </div>

      {/* Prediction vs decision */}
      {prediction && chosen && (
        <div style={{
          marginTop: 18, padding: "14px 18px",
          background: "var(--paper-2)", borderRadius: 10, fontSize: 13, color: "var(--ink-2)",
          display: "flex", gap: 16, alignItems: "flex-start"
        }}>
          <span className="t-label" style={{ color: "var(--accent)", flexShrink: 0 }}>Tu predicción</span>
          <span style={{ fontStyle: "italic", lineHeight: 1.5 }}>“{prediction.slice(0, 200)}{prediction.length > 200 ? "…" : ""}”</span>
        </div>
      )}
    </div>
  );
}

function CompanyCalcCard({ company: c, peStar, premium, chosen, style }) {
  const styleMode = style || "visible";
  return (
    <div className="card" style={{
      padding: 24,
      background: "var(--card-elev)",
      borderColor: chosen ? "var(--accent)" : "var(--rule)",
      borderWidth: chosen ? 1.5 : 1
    }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 16 }}>
        <div>
          <div className="t-label" style={{ marginBottom: 4 }}>{c.label}</div>
          <div className="t-display" style={{ fontSize: 22, fontWeight: 500, lineHeight: 1.1 }}>
            {c.flag} {c.name}
          </div>
          <div style={{ fontSize: 11, color: "var(--ink-3)", marginTop: 4 }}>{c.sector}</div>
        </div>
        <div style={{ textAlign: "right" }}>
          <div className="t-label" style={{ marginBottom: 2 }}>P/E observado</div>
          <div className="t-mono" style={{ fontSize: 28, fontWeight: 500, color: "var(--ink)" }}>
            {c.pe.toFixed(1)}<span style={{ fontSize: 14, color: "var(--ink-3)" }}>x</span>
          </div>
        </div>
      </div>

      {/* Inputs */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 10, marginBottom: 14 }}>
        <InputBox label="g (%)" value={c.growth} mono />
        <InputBox label="ROE (%)" value={c.roe} mono />
        <InputBox label="Ke (%)" value={c.ke} mono />
      </div>

      {styleMode !== "collapsed" && (
        <div style={{
          background: "var(--paper)", padding: "14px 16px", borderRadius: 10,
          border: "1px dashed var(--rule)", marginBottom: 14
        }}>
          <div className="t-label" style={{ marginBottom: 8 }}>Cálculo</div>
          {styleMode === "step" ? (
            <div style={{ display: "flex", flexDirection: "column", gap: 6, fontSize: 12, color: "var(--ink-2)" }}>
              <div className="t-mono">1) g / ROE = {(c.growth / c.roe).toFixed(3)}</div>
              <div className="t-mono">2) 1 − g/ROE = {(1 - c.growth / c.roe).toFixed(3)}</div>
              <div className="t-mono">3) Ke − g = {((c.ke - c.growth) / 100).toFixed(3)}</div>
              <div className="t-mono" style={{ color: "var(--ink)", paddingTop: 4, borderTop: "1px solid var(--rule-soft)", marginTop: 4 }}>
                4) P/E* = {peStar ? peStar.toFixed(2) : "n/d"}x
              </div>
            </div>
          ) : (
            <div className="t-mono" style={{ fontSize: 13, color: "var(--ink-2)", lineHeight: 1.6 }}>
              P/E* = (1 − {c.growth}/{c.roe}) / ({c.ke}% − {c.growth}%)
              <br />
              <span style={{ color: "var(--ink)" }}>= {peStar ? peStar.toFixed(2) : "n/d"}x</span>
            </div>
          )}
        </div>
      )}

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginBottom: 14 }}>
        <div>
          <div className="t-label" style={{ marginBottom: 4 }}>P/E* Gordon</div>
          <div className="t-mono" style={{ fontSize: 22, fontWeight: 500 }}>
            {peStar ? peStar.toFixed(1) : "—"}<span style={{ fontSize: 12, color: "var(--ink-3)" }}>x</span>
          </div>
        </div>
        <div>
          <div className="t-label" style={{ marginBottom: 4 }}>Premium implícito</div>
          <div className="t-mono" style={{
            fontSize: 22, fontWeight: 500,
            color: premium && premium > 10 ? "var(--green)" : premium && premium < -10 ? "var(--red)" : "var(--ink)"
          }}>
            {premium !== null ? (premium >= 0 ? "+" : "") + premium.toFixed(0) + "%" : "—"}
          </div>
        </div>
      </div>

      <div style={{
        padding: "10px 12px", background: "var(--paper-2)", borderRadius: 8,
        fontSize: 11, color: "var(--ink-3)", lineHeight: 1.5,
        fontFamily: "var(--sans)"
      }}>
        <strong style={{ color: "var(--ink-2)" }}>Notas: </strong>{c.note}
      </div>
    </div>
  );
}

function InputBox({ label, value, mono }) {
  return (
    <div>
      <div className="t-label" style={{ marginBottom: 4 }}>{label}</div>
      <input
        defaultValue={value}
        className={mono ? "t-mono-input" : ""}
        style={{ padding: "8px 10px", textAlign: "right" }}
      />
    </div>
  );
}

function ComparisonRow({ driver, vA, vB, winner, read, highlight }) {
  return (
    <>
      <div style={{
        fontSize: 13, color: "var(--ink-2)",
        fontWeight: highlight ? 500 : 400,
        paddingTop: 8, borderTop: "1px solid var(--rule-soft)"
      }}>{driver}</div>
      <div className="t-mono" style={{
        fontSize: highlight ? 18 : 15, color: winner === "A" ? "var(--ink)" : "var(--ink-3)",
        fontWeight: winner === "A" ? 500 : 400,
        paddingTop: 8, borderTop: "1px solid var(--rule-soft)"
      }}>{vA}</div>
      <div className="t-mono" style={{
        fontSize: highlight ? 18 : 15, color: winner === "B" ? "var(--ink)" : "var(--ink-3)",
        fontWeight: winner === "B" ? 500 : 400,
        paddingTop: 8, borderTop: "1px solid var(--rule-soft)"
      }}>{vB}</div>
      <div style={{
        fontSize: 12, color: "var(--ink-3)", fontStyle: "italic", fontFamily: "var(--serif)",
        paddingTop: 8, borderTop: "1px solid var(--rule-soft)"
      }}>{read}</div>
    </>
  );
}

function ChoiceBtn({ label, sub, selected, onClick, tone }) {
  const toneClass = tone || "accent";
  return (
    <button
      onClick={onClick}
      style={{
        border: 0, padding: "16px 18px", borderRadius: 12, cursor: "pointer",
        background: selected ? `var(--${toneClass}-tint)` : "var(--paper-2)",
        borderLeft: `3px solid ${selected ? `var(--${toneClass})` : "transparent"}`,
        textAlign: "left", fontFamily: "var(--sans)",
        transition: "all 0.15s"
      }}>
      <div style={{ fontSize: 14, fontWeight: 500, color: "var(--ink)", marginBottom: 4 }}>{label}</div>
      <div style={{ fontSize: 12, color: "var(--ink-3)", lineHeight: 1.4 }}>{sub}</div>
    </button>
  );
}

// ----------------------------------------------------------------
// S4 Memo — editor with prohibited-language detector
// ----------------------------------------------------------------
function MemoPanel({ memo, setMemo, chosen, prediction }) {
  const WORD_LIMIT = 150;
  const words = memo.split(/\s+/).filter(Boolean);
  const checklist = window.FZ_MEMO_CHECKLIST;
  const forbidden = window.FZ_FORBIDDEN;
  const lower = memo.toLowerCase();
  const flagged = forbidden.filter((f) => new RegExp(`\\b${f.word}\\b`, "i").test(lower));

  // crude checklist signals
  const signals = {
    data: /\d+(\.\d+)?\s*%|\d+\s*x|p\/e/i.test(memo),
    hyp: /hipótesis|porque|sugiere|señala|indica/i.test(memo),
    ev: /evidencia|pendiente|verificar|sostenibilidad|comprobar/i.test(memo),
    lang: flagged.length === 0,
    noinv: !/(compr[ao]|vend[ae]|recomien)/i.test(memo)
  };

  return (
    <div className="anim-in" style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 28 }}>
      <div>
        <span className="t-label">S4 · Mini-memo de comité</span>
        <h2 className="t-display" style={{ fontSize: 28, margin: "8px 0 6px", lineHeight: 1.15 }}>
          Defiende tu lectura. En 150 palabras.
        </h2>
        <p style={{ fontFamily: "var(--serif)", fontSize: 16, fontStyle: "italic", color: "var(--ink-3)", marginTop: 0, lineHeight: 1.45 }}>
          Un comité no quiere fórmulas. Quiere: qué viste, qué supones, qué falta, y por qué tu lenguaje es honesto.
        </p>

        <div style={{ position: "relative", marginTop: 18 }}>
          <textarea
            value={memo}
            onChange={(e) => setMemo(e.target.value)}
            rows={14}
            placeholder={`Empresa A presenta P/E observado 14x con g sostenible 11.5% y ROE 22%. El P/E teórico de Gordon (Ke 8.5%) supera 20x, lo que sugiere que el mercado no recoge plenamente la calidad de los drivers. Hipótesis: el premium estaría justificado por…\n\nEvidencia pendiente: sostenibilidad del ROE, ciclo del capex…`}
            style={{
              fontFamily: "var(--serif)", fontSize: 16, lineHeight: 1.6, resize: "vertical",
              padding: "18px 20px", minHeight: 320
            }}
          />
        </div>

        {/* Flagged words */}
        {flagged.length > 0 && (
          <div className="anim-in" style={{
            marginTop: 12, padding: 14, background: "var(--red-tint)", borderRadius: 10
          }}>
            <div className="t-label" style={{ color: "var(--red)", marginBottom: 6 }}>Lenguaje prohibido detectado</div>
            <ul style={{ margin: 0, paddingLeft: 18, fontSize: 12, color: "var(--ink-2)", lineHeight: 1.6 }}>
              {flagged.map((f) => (
                <li key={f.word}><strong>"{f.word}"</strong> — {f.reason}</li>
              ))}
            </ul>
          </div>
        )}

        <div style={{
          display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 12
        }}>
          <span className="t-mono" style={{
            fontSize: 12, color: words.length > WORD_LIMIT ? "var(--red)" : "var(--ink-3)"
          }}>
            {words.length} / {WORD_LIMIT} palabras
          </span>
          <div style={{ display: "flex", gap: 8 }}>
            <button className="btn small ghost">Guardar borrador</button>
            <button className="btn small">Preview comité</button>
          </div>
        </div>
      </div>

      <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
        <div className="card" style={{ padding: 22 }}>
          <div className="t-label" style={{ marginBottom: 14 }}>Checklist del memo</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
            {checklist.map((c) => (
              <ChecklistItem key={c.id} {...c} ok={signals[c.id]} />
            ))}
          </div>
        </div>

        {prediction && (
          <div className="card" style={{ padding: 20, background: "var(--paper-2)", borderColor: "var(--rule-soft)" }}>
            <div className="t-label" style={{ marginBottom: 8 }}>Tu predicción inicial</div>
            <div style={{ fontFamily: "var(--serif)", fontStyle: "italic", fontSize: 13, color: "var(--ink-2)", lineHeight: 1.5 }}>
              “{prediction.slice(0, 200)}{prediction.length > 200 ? "…" : ""}”
            </div>
          </div>
        )}

        <div className="card" style={{ padding: 20 }}>
          <div className="t-label" style={{ marginBottom: 10 }}>Tags de evidencia</div>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
            <span className="chip">P/E observado</span>
            <span className="chip">P/E* Gordon</span>
            <span className="chip">ROE 5y</span>
            <span className="chip">Ke estimado</span>
            <span className="chip" style={{ borderStyle: "dashed" }}>+ vincular cálculo</span>
          </div>
        </div>
      </div>
    </div>
  );
}

function ChecklistItem({ id, label, hint, ok }) {
  return (
    <div style={{ display: "flex", gap: 12, alignItems: "flex-start" }}>
      <div style={{
        width: 18, height: 18, borderRadius: 4, marginTop: 2,
        background: ok ? "var(--green)" : "var(--paper-2)",
        border: `1px solid ${ok ? "var(--green)" : "var(--rule)"}`,
        color: "var(--paper)", display: "flex", alignItems: "center", justifyContent: "center",
        fontSize: 11, flexShrink: 0
      }}>{ok && "✓"}</div>
      <div>
        <div style={{ fontSize: 13, fontWeight: 500, color: ok ? "var(--ink)" : "var(--ink-2)" }}>{label}</div>
        <div style={{ fontSize: 11, color: "var(--ink-3)", lineHeight: 1.4, marginTop: 2 }}>{hint}</div>
      </div>
    </div>
  );
}

window.EpisodePlayer = EpisodePlayer;
