// ============================================================
// flow1a.jsx · A1–A5 · Configuración inicial (sysadmin)
// ============================================================

const SYSADMIN_HEADER = { kind: "xokai-sysadmin", badge: "SYSADMIN", badgeTone: "purple",
  person: { name: "Ez Baez", sub: "ez@xokai.app", avatarName: "Ez Baez", color: "var(--xk-accent)" } };

// ---------- A1 · Dashboard sysadmin ----------
function A1({ state = "happy", openModal }) {
  const header = { ...SYSADMIN_HEADER };
  const schools = [
    { name: window.b("school.name"), city: "Guadalajara, Jal · 0 alumnos", status: "Pendiente onboarding", tone: "warning", color: "var(--tenant-brand)" },
    { name: "Colegio Montessori del Valle", city: "CDMX · 280 alumnos", status: "Activa", tone: "success", color: "#378ADD" },
    { name: "Instituto Bilingüe Roble", city: "Monterrey, NL · 412 alumnos", status: "Activa", tone: "success", color: "#D85A30" },
  ];
  return (
    <ScreenFrame header={header} maxWidth={1080}>
      {state === "loading" && (
        <div style={{ display: "flex", flexDirection: "column", gap: 24 }}>
          <div><Sk w={180} h={26} style={{ marginBottom: 10 }} /><Sk w={320} h={13} /></div>
          <SLoading variant="kpis" />
          <SLoading variant="hero" />
          <SLoading variant="table" rows={3} />
        </div>
      )}
      {state === "error" && (
        <SError title="No pudimos cargar las escuelas" body="Hubo un problema al conectar con el servidor. Revisa tu conexión e intenta de nuevo." technical="ERR_NETWORK · /api/v1/schools" />
      )}
      {state === "empty" && (
        <div style={{ display: "flex", flexDirection: "column", gap: 24 }}>
          <div><h1 style={{ margin: 0, fontSize: 26, fontWeight: 600, letterSpacing: "-0.02em" }}>Buenos días</h1>
            <div style={{ fontSize: 13.5, color: "var(--xk-text-secondary)", marginTop: 4 }}>jueves 29 de mayo, 2026</div></div>
          <SEmpty illustration="school" title="Aún no has creado escuelas" body="Empieza con la primera · el alta toma unos 5 minutos en 3 pasos." cta="Crear primera escuela" ctaIcon="plus" onCta={() => window.goTo("A2")} />
        </div>
      )}
      {state === "happy" && (
        <div style={{ display: "flex", flexDirection: "column", gap: 22 }}>
          <div className="animate-fade-up">
            <h1 style={{ margin: 0, fontSize: 26, fontWeight: 600, letterSpacing: "-0.02em" }}>Buenos días</h1>
            <div style={{ fontSize: 13.5, color: "var(--xk-text-secondary)", marginTop: 5 }}>
              jueves 29 de mayo, 2026 · <span style={{ color: "var(--xk-text)", fontWeight: 500 }}>13 escuelas activas · 1,847 alumnos en plataforma</span>
            </div>
          </div>
          <KpiGrid items={[
            { label: "Trial activo", value: "3", sub: "en periodo de prueba" },
            { label: "Pagas", value: "9", sub: "facturando", tone: "success" },
            { label: "MRR", value: "$2,340", sub: "USD · mensual" },
            { label: "Onboarding pendiente", value: "1", sub: "sin completar", tone: "warning" },
          ]} />
          {/* Hero card */}
          <div className="animate-fade-up" style={{ animationDelay: "0.1s", background: "var(--xokai-purple)", borderRadius: 16, padding: "24px 26px", display: "flex", alignItems: "center", gap: 20, color: "#fff" }}>
            <span style={{ width: 48, height: 48, borderRadius: 12, background: "rgba(255,255,255,0.16)", display: "inline-flex", alignItems: "center", justifyContent: "center" }}><Icon name="plus" size={24} color="#fff" /></span>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 17, fontWeight: 600 }}>Crear nueva escuela</div>
              <div style={{ fontSize: 13, opacity: 0.88, marginTop: 3 }}>3 pasos · ~5 min · datos fiscales, plan e invitación al director</div>
            </div>
            <Btn variant="secondary" iconRight="arrow-right" style={{ background: "#fff", borderColor: "#fff" }} onClick={() => window.goTo("A2")}>Empezar</Btn>
          </div>
          {/* Schools list */}
          <div>
            <Eyebrow>Escuelas</Eyebrow>
            <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
              {schools.map((s, i) => (
                <Card key={i} interactive style={{ padding: "13px 16px", display: "flex", alignItems: "center", gap: 14 }} onClick={() => openModal(<MSchoolDetail onClose={openModal.close} school={s} />)}>
                  {/Hábitat/.test(s.name)
                    ? <span style={{ width: 38, height: 38, borderRadius: 10, background: "#fff", border: "1px solid var(--xk-border)", display: "inline-flex", alignItems: "center", justifyContent: "center", padding: 4, flexShrink: 0 }}><img src="assets/habitat-iso.png" alt="" style={{ width: "100%", height: "100%", objectFit: "contain" }} /></span>
                    : <span style={{ width: 38, height: 38, borderRadius: 10, background: s.color, color: "#fff", display: "inline-flex", alignItems: "center", justifyContent: "center", fontWeight: 700, fontSize: 16 }}>{s.name[0]}</span>}
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 14, fontWeight: 600 }}>{s.name}</div>
                    <div style={{ fontSize: 12, color: "var(--xk-text-muted)", marginTop: 2 }}>{s.city}</div>
                  </div>
                  <Badge tone={s.tone} dot>{s.status}</Badge>
                  <Icon name="chevron-right" size={16} color="var(--xk-text-muted)" />
                </Card>
              ))}
              <button className="xk-dashed" onClick={() => openModal(<MAllSchools onClose={openModal.close} />)} style={{ padding: "11px", background: "transparent", border: "1px dashed var(--xk-border-strong)", borderRadius: 12, fontSize: 13, color: "var(--xk-text-secondary)", cursor: "pointer", fontWeight: 500 }}>Ver las otras 10 escuelas</button>
            </div>
          </div>
        </div>
      )}
    </ScreenFrame>
  );
}

// ---------- Wizard scaffold for A2–A4 ----------
function CreateSchoolWizard({ step, openModal, children, head, footer }) {
  const header = { ...SYSADMIN_HEADER, breadcrumb: ["Dashboard", "Nueva escuela"] };
  return (
    <ScreenFrame header={header} maxWidth={840}>
      <WizardStepper steps={["Datos", "Plan", "Director"]} current={step} style={{ marginBottom: 30 }} />
      {head}
      <Card style={{ padding: 26 }}>{children}</Card>
      {footer}
    </ScreenFrame>
  );
}

// ---------- A2 · Datos fiscales ----------
function A2({ state = "happy", openModal }) {
  const [shake, setShake] = useState(false);
  const validation = state === "validation";
  const grid = { display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 };
  return (
    <CreateSchoolWizard step={1} openModal={openModal}
      head={<WizardHead eyebrow="Paso 1 de 3" title="Datos de la escuela" subtitle="Capturamos lo indispensable para crear el tenant · el director completa el resto en su onboarding." />}
      footer={<WizardFooter back={false} nextLabel="Continuar a plan" onNext={() => { if (validation) { setShake(true); setTimeout(() => setShake(false), 350); } else { window.goTo("A3"); } }}>
        <Btn variant="secondary" onClick={() => openModal(<MConfirmCancel onClose={openModal.close} onConfirm={openModal.close} description="Los datos capturados se perderán · esta escuela aún no se ha creado." />)}>Cancelar</Btn>
      </WizardFooter>}>
      <Label>Identidad</Label>
      <div style={{ ...grid, marginTop: 10 }}>
        <Field label="Nombre completo" required full><Input value={window.b("school.name")} /></Field>
        <Field label="Nombre corto"><Input value={window.b("school.short_name")} /></Field>
        <Field label="Zona horaria"><Select value="America/Mexico_City" options={["America/Mexico_City", "America/Cancun", "America/Monterrey"]} /></Field>
        <Field label="Dirección" full><Input value="Av. Américas 1254, Country Club" /></Field>
        <Field label="Estado"><Select value="Jalisco" options={window.MX_ESTADOS} /></Field>
        <Field label="Ciudad"><Input value="Guadalajara" /></Field>
      </div>
      <Divider dashed style={{ margin: "20px 0" }} />
      <Label>Datos fiscales · CFDI</Label>
      <div style={{ ...grid, marginTop: 10 }}>
        <Field label="RFC" required error={validation ? "Formato de RFC inválido · 12 o 13 caracteres" : null}>
          <Input mono value={validation ? "HLC18052" : window.b("school.rfc")} error={validation} shake={shake} />
        </Field>
        <Field label="Régimen fiscal"><Select value="603 · Personas Morales con Fines no Lucrativos" options={["603 · Personas Morales con Fines no Lucrativos", "601 · General de Ley Personas Morales"]} /></Field>
        <Field label="Razón social" full><Input value={window.b("school.razon_social")} /></Field>
      </div>
      <Banner tone="info" style={{ marginTop: 18 }}>Estos datos se usan para la facturación CFDI y aparecen pre-llenados en el onboarding del director.</Banner>
    </CreateSchoolWizard>
  );
}

// ---------- A3 · Modalidad billing ----------
function A3({ state = "happy", openModal }) {
  const [sel, setSel] = useState(1);
  const [currency, setCurrency] = useState("USD");
  const [cycle, setCycle] = useState("anual");
  const RATES = {
    USD: { mensual: "$9.00 USD", anual: "$7.50 USD" },
    MXN: { mensual: "$162 MXN", anual: "$135 MXN" },
  };
  const ANNUAL_EST = {
    USD: { mensual: "$35,100 USD", anual: "$29,250 USD" },
    MXN: { mensual: "$631,800 MXN", anual: "$526,500 MXN" },
  };
  const price = RATES[currency][cycle];
  const annual = ANNUAL_EST[currency][cycle];
  const billNote = cycle === "anual" ? "por alumno · mes · facturado anual" : "por alumno · mes";
  const modes = [
    { t: "Standard", d: "Trial 30 días · auto-convierte al término", badge: null },
    { t: "Extendido", d: "Trial 60 días · setup concierge incluido", badge: "PILOTO" },
    { t: "Pago directo", d: "Activo desde el día 1 · sin trial", badge: null },
  ];
  const included = ["Pickup semáforo", "Delegación de tutores", "Admisiones e inscripciones", "Avisos multi-tutor", "Mensajes 1-a-1", "Asistencia", "Calendario y menú", "Cobranza manual", "Roles de staff", "Soporte L1"];
  const soon = ["Pagos en línea + CFDI", "Firma Docuseal", "Reconciliación bancaria"];
  return (
    <CreateSchoolWizard step={2} openModal={openModal}
      head={<WizardHead title="Modalidad de billing" subtitle="Plataforma completa · todas las features incluidas · solo cambia cuándo se cobra." />}
      footer={<WizardFooter nextLabel="Continuar a director" />}>
      <Label>Modalidad</Label>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 12, marginTop: 10 }}>
        {modes.map((m, i) => {
          const active = sel === i;
          return (
            <div key={i} onClick={() => setSel(i)} className="xk-card-interactive" style={{ padding: 16, borderRadius: 12, cursor: "pointer",
              border: active ? "2px solid var(--xk-accent)" : "1px solid var(--xk-border-strong)",
              background: active ? "var(--xokai-purple-tint)" : "var(--xk-surface)" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 6 }}>
                <span style={{ fontSize: 14, fontWeight: 600 }}>{m.t}</span>
                {m.badge && <Badge tone="purple">{m.badge}</Badge>}
                {active && <span style={{ marginLeft: "auto" }}><Icon name="check-circle-2" size={17} color="var(--xk-accent)" /></span>}
              </div>
              <div style={{ fontSize: 12, color: "var(--xk-text-secondary)", lineHeight: 1.5 }}>{m.d}</div>
            </div>
          );
        })}
      </div>

      <Label style={{ marginTop: 22 }}>Pricing al término del trial</Label>
      <div style={{ display: "flex", gap: 14, alignItems: "stretch", marginTop: 10 }}>
        <div style={{ flex: 1, background: "var(--xk-surface-2)", borderRadius: 12, padding: "18px 20px", display: "flex", alignItems: "center", gap: 22 }}>
          <div style={{ display: "flex", flexDirection: "column", gap: 9 }}>
            <Toggle options={["USD", "MXN"]} value={currency} onChange={setCurrency} />
            <Toggle options={[{ v: "mensual", l: "Mensual" }, { v: "anual", l: "Anual −16%" }]} value={cycle} onChange={setCycle} greenHint />
          </div>
          <div style={{ borderLeft: "1px solid var(--xk-border-strong)", paddingLeft: 22 }}>
            <div className="xk-mono" style={{ fontSize: 30, fontWeight: 600, letterSpacing: "-0.03em", transition: "all 200ms ease" }}>{price}</div>
            <div style={{ fontSize: 12, color: "var(--xk-text-muted)", marginTop: 2 }}>{billNote}</div>
          </div>
        </div>
        <div style={{ width: 200, background: "var(--xk-surface-2)", borderRadius: 12, padding: "18px 20px" }}>
          <div className="xk-overline" style={{ marginBottom: 8 }}>Estimado anual</div>
          <div className="xk-mono" style={{ fontSize: 20, fontWeight: 600, letterSpacing: "-0.02em" }}>{annual}</div>
          <div style={{ fontSize: 12, color: "var(--xk-text-muted)", marginTop: 4 }}>325 alumnos</div>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, marginTop: 16 }}>
        <Field label="Máximo de alumnos"><Input value="350" mono /></Field>
        <Field label="Trial vence"><Input value="2026-07-29" mono /></Field>
      </div>

      <Label style={{ marginTop: 22 }}>Todo incluido · plataforma completa</Label>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "8px 22px", marginTop: 10 }}>
        {included.map((f, i) => (
          <div key={i} style={{ display: "flex", alignItems: "center", gap: 9, fontSize: 13, color: "var(--xk-text)" }}>
            <Icon name="check" size={15} color="var(--xk-success)" />{f}
          </div>
        ))}
        {soon.map((f, i) => (
          <div key={i} style={{ display: "flex", alignItems: "center", gap: 9, fontSize: 13, color: "var(--xk-text-secondary)" }}>
            <Icon name="clock" size={15} color="var(--xk-warning)" />{f}<Badge tone="warning" style={{ marginLeft: "auto" }}>PRONTO</Badge>
          </div>
        ))}
      </div>
    </CreateSchoolWizard>
  );
}

function Toggle({ options, value, onChange, greenHint }) {
  const opts = options.map(o => typeof o === "string" ? { v: o, l: o } : o);
  return (
    <div style={{ display: "inline-flex", background: "var(--xk-surface-3)", borderRadius: 8, padding: 3, gap: 2 }}>
      {opts.map(o => {
        const active = value === o.v;
        const green = greenHint && o.l.includes("−16%");
        return (
          <button key={o.v} onClick={() => onChange(o.v)} style={{ border: "none", cursor: "pointer", padding: "5px 12px", borderRadius: 6, fontSize: 12, fontWeight: 500,
            background: active ? "var(--xk-text)" : "transparent", color: active ? "#fff" : (green ? "var(--xk-success)" : "var(--xk-text-secondary)") }}>{o.l}</button>
        );
      })}
    </div>
  );
}
window.Toggle = Toggle;

// ---------- A4 · Invitar director ----------
function A4({ state = "happy", openModal }) {
  const [submitting, setSubmitting] = useState(false);
  const summary = [
    ["Escuela", window.b("school.name")],
    ["RFC", window.b("school.rfc"), true],
    ["Plan", "Trial extendido · 60 días"],
    ["Módulos", "Plataforma completa"],
    ["Director", window.b("director.full_name") + " · " + window.b("director.email")],
    ["Remitente", "hola@xokai.app"],
  ];
  return (
    <CreateSchoolWizard step={3} openModal={openModal}
      head={<WizardHead title="Invitar al director" subtitle="Magic link al email · un clic y completa el onboarding · ~30 min en total." />}
      footer={<WizardFooter next={false}>
        <Btn variant="primary" icon={submitting ? null : "send"} onClick={() => {
          setSubmitting(true);
          if (state === "error") { setTimeout(() => { setSubmitting(false); openModal(<MConfirmDestructive title="Email ya registrado" description={"Ya existe una cuenta con " + window.b("director.email") + " en otra escuela. Usa un correo distinto o contacta a soporte."} actionLabel="Entendido" onClose={openModal.close} onConfirm={openModal.close} />); }, 1200); }
          else { setTimeout(() => { setSubmitting(false); window.goTo("A5"); }, 1500); }
        }}>
          {submitting ? <span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}><Spinner size={15} color="#fff" />Creando tenant…</span> : "Crear escuela y enviar invitación"}
        </Btn>
      </WizardFooter>}>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
        <Field label="Nombre del director" required><Input value={window.b("director.full_name")} /></Field>
        <Field label="Cargo"><Input value={window.b("director.title")} /></Field>
        <Field label="Email" required full><Input value={window.b("director.email")} /></Field>
      </div>

      <Label style={{ marginTop: 22 }}>Vista previa del email</Label>
      <div data-tour="su-invite" onClick={() => openModal(<MPreviewEmail onClose={openModal.close} branded={false} />)} className="xk-card-interactive" style={{ borderRadius: 12, marginTop: 10, cursor: "pointer" }}>
        <EmailMock branded={false} />
      </div>
      <div style={{ fontSize: 11.5, color: "var(--xk-text-muted)", marginTop: 6, textAlign: "center" }}>Clic para ver a tamaño completo</div>

      <Label style={{ marginTop: 22 }}>Resumen pre-creación</Label>
      <div style={{ marginTop: 10, background: "var(--xk-surface-2)", borderRadius: 12, padding: "6px 18px" }}>
        {summary.map(([k, v, mono], i) => (
          <div key={i} style={{ display: "flex", padding: "10px 0", borderBottom: i === summary.length - 1 ? "none" : "1px solid var(--xk-border)", fontSize: 13 }}>
            <span style={{ width: 130, color: "var(--xk-text-muted)" }}>{k}</span>
            <span style={{ flex: 1, fontWeight: 500, fontFamily: mono ? "var(--xk-font-mono)" : "inherit" }}>{v}</span>
          </div>
        ))}
      </div>
    </CreateSchoolWizard>
  );
}

// ---------- A5 · Tenant creado · celebration ----------
function A5({ state = "happy", openModal }) {
  const header = { ...SYSADMIN_HEADER, breadcrumb: ["Dashboard", "Nueva escuela", "Creada"] };
  return (
    <ScreenFrame header={header} maxWidth={760}>
      <CelebrationHero variant="soft" icon="school" confettiCount={12}
        title={window.b("school.name") + " · creada"}
        subtitle={"Invitación enviada desde hola@xokai.app a " + window.b("director.email") + " · hace 3 segundos."}
        summary={[
          { icon: "calendar-clock", value: "60 d", label: "de trial" },
          { icon: "users", value: "350", label: "alumnos de cupo" },
          { icon: "mail-check", label: "magic link enviado" },
        ]} />

      <div style={{ marginTop: 26, display: "flex", flexDirection: "column", gap: 22 }}>
        <div className="animate-fade-up" style={{ animationDelay: "0.15s" }}>
          <Eyebrow>Acceso directo · por si el director necesita el link</Eyebrow>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
            <CopyField label="Join code" value="HABITAT24" />
            <CopyField label="Link de onboarding" value="habitat.xokai.app/start/aZ91k" />
          </div>
        </div>
        <div className="animate-fade-up" style={{ animationDelay: "0.3s" }}>
          <Eyebrow>Status del tenant</Eyebrow>
          <KpiGrid items={[
            { label: "Alumnos", value: "0 / 350" },
            { label: "Staff", value: "1" },
            { label: "Onboarding", value: "0%", tone: "warning" },
            { label: "Trial", value: "60 d" },
          ]} />
        </div>
        <div className="animate-fade-up" style={{ animationDelay: "0.45s" }}>
          <Eyebrow>Próximos pasos</Eyebrow>
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {[
              ["El director recibe el magic link y entra a configurar", "XOKAI", "purple"],
              ["Completa el onboarding · perfil, branding, estructura", "DIRECTOR", "info"],
              ["Carga la comunidad desde el Centro de carga", "AMBOS", "warning"],
              ["Activación masiva de padres · go-live", "MOMENTO", "gray"],
            ].map(([t, badge, tone], i) => (
              <div key={i} style={{ display: "flex", alignItems: "center", gap: 12, padding: "11px 14px", background: "var(--xk-surface)", border: "1px solid var(--xk-border)", borderRadius: 10 }}>
                <span className="xk-mono" style={{ width: 22, height: 22, borderRadius: 999, background: "var(--xk-surface-2)", display: "inline-flex", alignItems: "center", justifyContent: "center", fontSize: 12, color: "var(--xk-text-secondary)" }}>{i + 1}</span>
                <span style={{ flex: 1, fontSize: 13 }}>{t}</span>
                <Badge tone={tone}>{badge}</Badge>
              </div>
            ))}
          </div>
        </div>
        <div className="animate-fade-up" style={{ animationDelay: "0.6s", display: "flex", gap: 12 }}>
          <Btn variant="secondary" full onClick={() => openModal(<MSchoolDetail onClose={openModal.close} school={{ name: window.b("school.name"), city: "Guadalajara, Jal · 0 alumnos", status: "Pendiente onboarding", tone: "warning", color: "var(--tenant-brand)" }} fresh />)}>Ver detalle</Btn>
          <Btn variant="primary" full onClick={() => window.goTo("A1")}>Volver al dashboard</Btn>
        </div>
      </div>
    </ScreenFrame>
  );
}

function CopyField({ label, value }) {
  const [copied, setCopied] = useState(false);
  return (
    <div style={{ background: "var(--xk-surface)", border: "1px solid var(--xk-border)", borderRadius: 10, padding: "12px 14px" }}>
      <div className="xk-overline" style={{ marginBottom: 7 }}>{label}</div>
      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
        <span className="xk-mono" style={{ flex: 1, fontSize: 13, fontWeight: 600, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{value}</span>
        <button onClick={() => { setCopied(true); setTimeout(() => setCopied(false), 1400); }} style={{ border: "none", background: "transparent", cursor: "pointer", color: copied ? "var(--xk-success)" : "var(--xk-text-muted)", display: "inline-flex" }}>
          <Icon name={copied ? "check" : "copy"} size={15} />
        </button>
      </div>
    </div>
  );
}
window.CopyField = CopyField;

Object.assign(window, { A1, A2, A3, A4, A5 });

// ---- School detail drawer-modal ----
function MSchoolDetail({ onClose, school, fresh }) {
  const pending = fresh || /pendiente|onboarding/i.test(school.status || "");
  const rows = pending
    ? [["RFC", fresh ? window.b("school.rfc") : "HLC180523AB1", true], ["Plan", "Trial extendido · 60 días"], ["Alumnos", "0 / 350"], ["Staff", "1"], ["Director", fresh ? window.b("director.full_name") : "Norma Guinto"], ["Onboarding", "0% · pendiente"]]
    : [["RFC", "MVD120534XY8", true], ["Plan", "Pago directo"], ["Alumnos", "280 / 320"], ["Staff", "26"], ["Director", "Patricia Salgado"], ["Onboarding", "100% · completo"]];
  return (
    <ModalShell width={520} onClose={onClose}>
      <div style={{ padding: "20px 24px", borderBottom: "1px solid var(--xk-border)", display: "flex", alignItems: "center", gap: 13 }}>
        {/Hábitat/.test(school.name)
          ? <span style={{ width: 44, height: 44, borderRadius: 11, background: "#fff", border: "1px solid var(--xk-border)", display: "inline-flex", alignItems: "center", justifyContent: "center", padding: 5, flexShrink: 0 }}><img src="assets/habitat-iso.png" alt="" style={{ width: "100%", height: "100%", objectFit: "contain" }} /></span>
          : <span style={{ width: 44, height: 44, borderRadius: 11, background: school.color, color: "#fff", display: "inline-flex", alignItems: "center", justifyContent: "center", fontWeight: 700, fontSize: 18 }}>{school.name[0]}</span>}
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 16, fontWeight: 600 }}>{school.name}</div>
          <div style={{ fontSize: 12, color: "var(--xk-text-muted)" }}>{school.city}</div>
        </div>
        <Badge tone={school.tone} dot>{school.status}</Badge>
      </div>
      <div style={{ padding: "8px 24px 4px" }}>
        {rows.map((r, i) => (
          <div key={i} style={{ display: "flex", padding: "11px 0", borderBottom: i === rows.length - 1 ? "none" : "1px solid var(--xk-border)", fontSize: 13 }}>
            <span style={{ width: 110, color: "var(--xk-text-muted)" }}>{r[0]}</span>
            <span style={{ flex: 1, fontWeight: 500, fontFamily: r[2] ? "var(--xk-font-mono)" : "inherit" }}>{r[1]}</span>
          </div>
        ))}
      </div>
      <div style={{ padding: "14px 24px", borderTop: "1px solid var(--xk-border)", display: "flex", alignItems: "center", gap: 10 }}>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 11, color: "var(--xk-text-muted)" }}><Icon name="shield" size={13} />Acción auditada</span>
        <div style={{ flex: 1 }}></div>
        <Btn variant="secondary" onClick={onClose}>Cerrar</Btn>
        {pending && !fresh
          ? <Btn variant="primary" icon="send" onClick={onClose}>Reenviar invitación</Btn>
          : fresh
            ? <Btn variant="primary" icon="send" onClick={onClose}>Reenviar invitación</Btn>
            : <Btn variant="primary" iconRight="arrow-right" onClick={() => { onClose(); window.enterSupport && window.enterSupport(school.name); }}>Entrar como soporte</Btn>}
      </div>
    </ModalShell>
  );
}
window.MSchoolDetail = MSchoolDetail;

// ---- All schools list modal ----
function MAllSchools({ onClose }) {
  const all = [
    ["Colegio del Bosque", "Guadalajara · 340", "success", "#1D9E75"], ["Liceo Anáhuac", "Puebla · 290", "success", "#378ADD"],
    ["Instituto Cumbres", "Querétaro · 410", "success", "#D85A30"], ["Colegio Williams", "CDMX · 520", "success", "#6D4AE8"],
    ["Escuela Sierra Nevada", "CDMX · 480", "success", "#0F9E8A"], ["Colegio Vista Hermosa", "Mérida · 220", "success", "#D4537E"],
    ["Instituto Patria", "Monterrey · 360", "success", "#BA7517"], ["Colegio Inglés", "León · 195", "warning", "#378ADD"],
    ["Liceo Mexicano", "Toluca · 310", "success", "#1D9E75"], ["Colegio Alemán", "CDMX · 600", "success", "#D85A30"],
  ];
  return (
    <ModalShell width={540} onClose={onClose}>
      <div style={{ padding: "18px 22px", borderBottom: "1px solid var(--xk-border)", display: "flex", alignItems: "center" }}>
        <h3 style={{ margin: 0, fontSize: 15, fontWeight: 600 }}>Todas las escuelas · 13</h3>
        <button onClick={onClose} className="xk-iconbtn" style={{ marginLeft: "auto" }}><Icon name="x" size={18} /></button>
      </div>
      <div className="no-scrollbar" style={{ maxHeight: 380, overflowY: "auto", padding: "8px 14px" }}>
        {all.map((s, i) => (
          <div key={i} className="xk-trow" style={{ display: "flex", alignItems: "center", gap: 12, padding: "10px 8px", borderRadius: 9, cursor: "pointer" }}>
            <span style={{ width: 32, height: 32, borderRadius: 8, background: s[3], color: "#fff", display: "inline-flex", alignItems: "center", justifyContent: "center", fontWeight: 700, fontSize: 13 }}>{s[0][0]}</span>
            <div style={{ flex: 1 }}><div style={{ fontSize: 13, fontWeight: 600 }}>{s[0]}</div><div style={{ fontSize: 11.5, color: "var(--xk-text-muted)" }}>{s[1]} alumnos</div></div>
            <Badge tone={s[2]} dot>{s[2] === "success" ? "Activa" : "Trial"}</Badge>
            <Icon name="chevron-right" size={15} color="var(--xk-text-muted)" />
          </div>
        ))}
      </div>
    </ModalShell>
  );
}
window.MAllSchools = MAllSchools;
