// ============================================================
// lib.jsx · Tenant data, binding system, logos, primitives
// ============================================================
const { useState, useEffect, useRef, createContext, useContext } = React;

// ---- Tenant + director data (default Hábitat for mockups) ----
const TENANT = {
  "school.name":            "Hábitat Learning Community",
  "school.short_name":      "Hábitat",
  "school.brand_color":     "#88B83C",
  "school.subdomain":       "habitat",
  "school.pedagogy":        "Reggio Emilia bilingüe",
  "school.students_count":  "325",
  "school.guardians_count": "614",
  "school.staff_count":     "28",
  "school.rfc":             "HLC180523AB1",
  "school.razon_social":    "HLC Educación A.C.",
  "director.full_name":     "Norma Guinto",
  "director.first_name":    "Norma",
  "director.title":         "Directora Pedagógica",
  "director.email":         "norma.guinto@habitatlc.mx",
  "guardian.first_name":    "Ezdraz",
};

// ---- Estados de México (32) ----
window.MX_ESTADOS = [
  "Aguascalientes", "Baja California", "Baja California Sur", "Campeche",
  "Chiapas", "Chihuahua", "Ciudad de México", "Coahuila", "Colima", "Durango",
  "Estado de México", "Guanajuato", "Guerrero", "Hidalgo", "Jalisco",
  "Michoacán", "Morelos", "Nayarit", "Nuevo León", "Oaxaca", "Puebla",
  "Querétaro", "Quintana Roo", "San Luis Potosí", "Sinaloa", "Sonora",
  "Tabasco", "Tamaulipas", "Tlaxcala", "Veracruz", "Yucatán", "Zacatecas",
];

// binding resolver — reads global mode set by App
window.b = function b(key) {
  if (window.__XK_BINDMODE === "tokens") return "{{ " + key + " }}";
  return TENANT[key] != null ? TENANT[key] : "{{ " + key + " }}";
};
// uppercase variant binding e.g. school.short_name|uppercase
window.bU = function bU(key) {
  if (window.__XK_BINDMODE === "tokens") return "{{ " + key + "|uppercase }}";
  return (TENANT[key] || "").toUpperCase();
};

// ---- Flow navigation (wired by App) ----
window.goTo = function goTo(id) { if (window.__XK_GO) window.__XK_GO(id); };
window.goNext = function goNext() {
  const f = window.__XK_FLOW || []; const i = f.indexOf(window.__XK_CUR);
  if (i >= 0 && i < f.length - 1) window.goTo(f[i + 1]);
};
window.goBack = function goBack() {
  const f = window.__XK_FLOW || []; const i = f.indexOf(window.__XK_CUR);
  if (i > 0) window.goTo(f[i - 1]);
};

// ---- Lucide icon ----
function Icon({ name, size = 16, color, stroke = 1.5, style }) {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    el.innerHTML = '<i data-lucide="' + name + '"></i>';
    if (window.lucide) window.lucide.createIcons();
    const svg = el.querySelector("svg");
    if (svg) { svg.setAttribute("width", size); svg.setAttribute("height", size); svg.style.strokeWidth = stroke; svg.style.display = "block"; }
  }, [name, size, stroke]);
  return <span ref={ref} style={{ width: size, height: size, color: color || "currentColor", display: "inline-flex", alignItems: "center", justifyContent: "center", flexShrink: 0, ...style }}></span>;
}
window.Icon = Icon;

// ============================================================
// LOGO · three correct applications
// ============================================================
// 1 · Isotipo (symbol only) — for ≤32px avatars, favicon, app-store icon
function XokaiIso({ size = 28, radius }) {
  const r = radius != null ? radius : Math.round(size * 0.25);
  return (
    <svg viewBox="0 0 72 72" width={size} height={size} style={{ display: "block", flexShrink: 0 }}>
      <rect width="72" height="72" rx="18" fill="#6D4AE8" />
      <path d="M15 57 C15 29 29 15 57 15" stroke="white" strokeWidth="8" strokeLinecap="round" fill="none" />
      <circle cx="57" cy="15" r="7" fill="white" />
    </svg>
  );
}
// 2 · Logotipo completo (lockup): iso + "xo"+"kai"
function XokaiLockup({ size = 26, dark = false, wordSize }) {
  const ws = wordSize || Math.round(size * 0.78);
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: size * 0.34 }}>
      <XokaiIso size={size} />
      <span style={{ fontWeight: 600, fontSize: ws, letterSpacing: "-0.02em", lineHeight: 1, fontFamily: "var(--xk-font-sans)" }}>
        <span style={{ color: dark ? "#FFFFFF" : "var(--xk-text)" }}>xo</span>
        <span style={{ color: "#6D4AE8", fontStyle: "italic" }}>kai</span>
      </span>
    </span>
  );
}
// 3 · Tenant logo (real school isotype) for I0-I5 headers
function TenantLogo({ size = 28, withName = false }) {
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 9 }}>
      <span style={{ width: size, height: size, borderRadius: Math.round(size * 0.24), background: "#fff", border: "1px solid var(--xk-border)", display: "inline-flex", alignItems: "center", justifyContent: "center", flexShrink: 0, overflow: "hidden", padding: Math.round(size * 0.1) }}>
        <img src="assets/habitat-iso.png" alt="" style={{ width: "100%", height: "100%", objectFit: "contain", display: "block" }} />
      </span>
      {withName && <span style={{ fontWeight: 600, fontSize: size * 0.5, letterSpacing: "-0.01em" }}>{window.b("school.name")}</span>}
    </span>
  );
}
Object.assign(window, { XokaiIso, XokaiLockup, TenantLogo });

// Tenant lockup (real school logo + wordmark) — for brand moments (emails)
function TenantLockup({ height = 40 }) {
  return <img src="assets/habitat-lockup.webp" alt={window.b("school.name")} style={{ height, width: "auto", display: "block" }} />;
}
window.TenantLockup = TenantLockup;

// ============================================================
// PRIMITIVES
// ============================================================
function Card({ children, elevated, interactive, style, className = "", ...rest }) {
  return (
    <div className={"xk-card " + (interactive ? "xk-card-interactive " : "") + className}
      style={{ borderRadius: elevated ? 14 : 12, boxShadow: elevated ? "var(--xk-shadow-sm)" : "var(--xk-shadow-xs)", ...style }} {...rest}>
      {children}
    </div>
  );
}
function Eyebrow({ children, style }) {
  return <div className="xk-overline" style={{ marginBottom: 10, ...style }}>{children}</div>;
}
function Label({ children, htmlFor, required }) {
  return (
    <label htmlFor={htmlFor} style={{ display: "block", fontSize: 11, fontWeight: 600, letterSpacing: "0.04em", textTransform: "uppercase", color: "var(--xk-text-secondary)", marginBottom: 6 }}>
      {children}{required && <span style={{ color: "var(--xk-danger)", marginLeft: 3 }}>·</span>}
    </label>
  );
}
Object.assign(window, { Card, Eyebrow, Label });

// ---- Badge / Pill system ----
const BADGE_TONES = {
  neutral:  { bg: "var(--xk-subtle)",        fg: "var(--xk-text-secondary)" },
  gray:     { bg: "var(--xk-surface-2)",     fg: "var(--xk-text-muted)" },
  success:  { bg: "var(--xk-success-tint)",  fg: "var(--xk-success)" },
  warning:  { bg: "var(--xk-warning-tint)",  fg: "var(--xk-warning)" },
  danger:   { bg: "var(--xk-danger-tint)",   fg: "var(--xk-danger)" },
  info:     { bg: "var(--xk-info-tint)",     fg: "var(--xk-info)" },
  purple:   { bg: "var(--xk-accent-light)",  fg: "var(--xk-accent)" },
};
function Badge({ tone = "neutral", children, dot, style }) {
  const t = BADGE_TONES[tone] || BADGE_TONES.neutral;
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 5, padding: "3px 8px", background: t.bg, color: t.fg, fontSize: 10.5, fontWeight: 600, borderRadius: 4, letterSpacing: "0.02em", lineHeight: 1.3, ...style }}>
      {dot && <span style={{ width: 5, height: 5, borderRadius: 999, background: t.fg }}></span>}
      {children}
    </span>
  );
}
window.Badge = Badge;
window.BADGE_TONES = BADGE_TONES;

// ---- Button ----
function Btn({ variant = "primary", size = "md", children, icon, iconRight, full, onClick, disabled, type, style }) {
  const sizes = {
    sm: { padding: "6px 11px", fontSize: 12.5, gap: 6 },
    md: { padding: "9px 15px", fontSize: 13.5, gap: 7 },
    lg: { padding: "13px 20px", fontSize: 15, gap: 8 },
  }[size];
  const variants = {
    primary:   { background: "var(--xk-accent)", color: "#fff", border: "1px solid var(--xk-accent)" },
    secondary: { background: "var(--xk-surface)", color: "var(--xk-text)", border: "1px solid var(--xk-border-strong)" },
    ghost:     { background: "transparent", color: "var(--xk-text-secondary)", border: "1px solid transparent" },
    danger:    { background: "var(--xk-danger)", color: "#fff", border: "1px solid var(--xk-danger)" },
    tenant:    { background: "var(--tenant-brand)", color: "#fff", border: "1px solid var(--tenant-brand)" },
  }[variant];
  return (
    <button type={type || "button"} onClick={onClick} disabled={disabled} className="xk-btn-press"
      style={{ display: "inline-flex", alignItems: "center", justifyContent: "center", ...sizes, ...variants,
        fontWeight: 500, borderRadius: 9, cursor: disabled ? "not-allowed" : "pointer",
        opacity: disabled ? 0.5 : 1, width: full ? "100%" : "auto", whiteSpace: "nowrap",
        transition: "background 120ms ease, transform 100ms ease, box-shadow 120ms ease", ...style }}>
      {icon && <Icon name={icon} size={size === "lg" ? 17 : 15} />}
      {children}
      {iconRight && <Icon name={iconRight} size={size === "lg" ? 17 : 15} />}
    </button>
  );
}
window.Btn = Btn;

// ---- Input field ----
function Field({ label, required, error, helper, children, style, full }) {
  return (
    <div style={{ gridColumn: full ? "1 / -1" : "auto", ...style }}>
      {label && <Label required={required}>{label}</Label>}
      {children}
      {error && <div style={{ fontSize: 11.5, color: "var(--xk-danger)", marginTop: 5, display: "flex", alignItems: "center", gap: 5 }}><Icon name="alert-circle" size={12} />{error}</div>}
      {!error && helper && <div style={{ fontSize: 11.5, color: "var(--xk-text-muted)", marginTop: 5 }}>{helper}</div>}
    </div>
  );
}
function Input({ value, placeholder, mono, error, shake, type, suffix, onChange, style }) {
  const cls = "xk-input" + (error ? " is-error" : "") + (shake ? " animate-shake" : "");
  const inp = <input className={cls} type={type || "text"} defaultValue={value} placeholder={placeholder} onChange={onChange}
    style={{ fontFamily: mono ? "var(--xk-font-mono)" : "var(--xk-font-sans)", textTransform: mono ? "uppercase" : "none", ...(suffix ? { borderTopRightRadius: 0, borderBottomRightRadius: 0, borderRight: "none" } : {}), ...style }} />;
  if (!suffix) return inp;
  return (
    <div style={{ display: "flex", alignItems: "stretch" }}>
      {inp}
      <span style={{ display: "inline-flex", alignItems: "center", padding: "0 11px", background: "var(--xk-subtle)", border: "1px solid var(--xk-border-strong)", borderLeft: "none", borderTopRightRadius: 8, borderBottomRightRadius: 8, fontSize: 13, color: "var(--xk-text-muted)", fontFamily: "var(--xk-font-mono)", whiteSpace: "nowrap" }}>{suffix}</span>
    </div>
  );
}
function Select({ value, options, error, onChange, style }) {
  return (
    <div style={{ position: "relative" }}>
      <select className={"xk-input" + (error ? " is-error" : "")} defaultValue={value} onChange={onChange}
        style={{ appearance: "none", paddingRight: 30, cursor: "pointer", ...style }}>
        {(options || []).map((o, i) => <option key={i} value={typeof o === "string" ? o : o.value}>{typeof o === "string" ? o : o.label}</option>)}
      </select>
      <span style={{ position: "absolute", right: 10, top: "50%", transform: "translateY(-50%)", pointerEvents: "none", color: "var(--xk-text-muted)" }}><Icon name="chevron-down" size={15} /></span>
    </div>
  );
}
Object.assign(window, { Field, Input, Select });

// ---- Banner ----
function Banner({ tone = "info", icon, title, children, style }) {
  const t = { ...BADGE_TONES[tone] };
  const icons = { info: "info", success: "check-circle-2", warning: "lightbulb", danger: "alert-circle", purple: "sparkles", neutral: "info", gray: "info" };
  return (
    <div style={{ display: "flex", gap: 10, padding: "12px 14px", background: t.bg, borderRadius: 10,
      border: "1px solid color-mix(in oklab, " + t.fg + " 22%, transparent)", ...style }}>
      <Icon name={icon || icons[tone]} size={16} color={t.fg} style={{ marginTop: 1 }} />
      <div style={{ fontSize: 12.5, lineHeight: 1.5, color: "var(--xk-text-secondary)" }}>
        {title && <div style={{ fontWeight: 600, color: "var(--xk-text)", marginBottom: 2 }}>{title}</div>}
        {children}
      </div>
    </div>
  );
}
window.Banner = Banner;

// ---- Avatar (initials) ----
function Avatar({ name = "", size = 32, color, warn }) {
  const initials = name.split(" ").filter(Boolean).map(s => s[0]).slice(0, 2).join("").toUpperCase();
  return (
    <span style={{ width: size, height: size, borderRadius: 999, flexShrink: 0,
      background: color || "linear-gradient(135deg,#14b8a6,#0f766e)", color: "#fff",
      display: "inline-flex", alignItems: "center", justifyContent: "center",
      fontSize: size * 0.36, fontWeight: 600,
      border: warn ? "2px solid var(--xk-warning)" : "none" }}>{initials}</span>
  );
}
window.Avatar = Avatar;

// ---- KPI grid ----
function KpiGrid({ cols = 4, items, style }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: `repeat(${cols}, 1fr)`, gap: 12, ...style }}>
      {items.map((k, i) => {
        const tone = k.tone ? BADGE_TONES[k.tone] : null;
        return (
          <div key={i} className="animate-fade-up" style={{ animationDelay: (0.05 * i) + "s",
            padding: "14px 16px", borderRadius: 12,
            background: tone ? tone.bg : "var(--xk-surface-2)",
            border: "1px solid " + (tone ? "color-mix(in oklab," + tone.fg + " 20%, transparent)" : "var(--xk-border)") }}>
            <div className="xk-overline" style={{ fontSize: 10.5, color: tone ? tone.fg : "var(--xk-text-muted)", marginBottom: 7 }}>{k.label}</div>
            <div className="xk-mono" style={{ fontSize: 22, fontWeight: 600, letterSpacing: "-0.03em", color: tone ? tone.fg : "var(--xk-text)", lineHeight: 1 }}>{k.value}</div>
            {k.sub && <div style={{ fontSize: 11, color: "var(--xk-text-muted)", marginTop: 5 }}>{k.sub}</div>}
          </div>
        );
      })}
    </div>
  );
}
window.KpiGrid = KpiGrid;

// ---- Icon box (square tinted icon container) ----
function IconBox({ icon, size = 40, bg = "var(--xk-accent-light)", color = "var(--xk-accent)", iconSize, radius = 10 }) {
  return (
    <span style={{ width: size, height: size, borderRadius: radius, background: bg, color, display: "inline-flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
      <Icon name={icon} size={iconSize || Math.round(size * 0.5)} />
    </span>
  );
}
window.IconBox = IconBox;

// ---- Divider ----
function Divider({ dashed, label, style }) {
  if (label) return (
    <div style={{ display: "flex", alignItems: "center", gap: 12, margin: "4px 0", ...style }}>
      <span style={{ flex: 1, height: 1, borderTop: (dashed ? "1px dashed " : "1px solid ") + "var(--xk-border-strong)" }}></span>
      <span className="xk-overline">{label}</span>
      <span style={{ flex: 1, height: 1, borderTop: (dashed ? "1px dashed " : "1px solid ") + "var(--xk-border-strong)" }}></span>
    </div>
  );
  return <div style={{ borderTop: (dashed ? "1px dashed " : "1px solid ") + "var(--xk-border)", margin: "4px 0", ...style }}></div>;
}
window.Divider = Divider;

// ---- Toast (inline, bottom-right) ----
function Toast({ icon = "check", children, tone = "success" }) {
  const t = BADGE_TONES[tone];
  return (
    <div className="animate-toast" style={{ position: "fixed", bottom: 24, right: 24, zIndex: 200,
      display: "flex", alignItems: "center", gap: 10, padding: "12px 16px",
      background: "var(--xk-surface)", border: "1px solid var(--xk-border-strong)",
      borderRadius: 12, boxShadow: "var(--xk-shadow-lg)" }}>
      <span style={{ width: 24, height: 24, borderRadius: 999, background: t.bg, color: t.fg, display: "inline-flex", alignItems: "center", justifyContent: "center" }}><Icon name={icon} size={14} /></span>
      <span style={{ fontSize: 13, fontWeight: 500, color: "var(--xk-text)" }}>{children}</span>
    </div>
  );
}
window.Toast = Toast;
