/* eslint-disable */
// ============================================================
// Finaz — shared UI components
// ============================================================

const { useState, useEffect, useRef, useMemo, useCallback } = React;

// ----------------------------------------------------------------
// Brand mark
// ----------------------------------------------------------------
function FinazMark({ size = 18 }) {
  return (
    <span
      style={{
        display: "inline-flex",
        alignItems: "center",
        gap: 8,
        fontFamily: "var(--serif)",
        fontWeight: 500,
        fontSize: size,
        letterSpacing: "-0.01em",
        color: "var(--ink)"
      }}
    >
      <svg width={size + 4} height={size + 4} viewBox="0 0 24 24" fill="none">
        <rect x="2" y="2" width="20" height="20" rx="3" fill="var(--ink)" />
        <path d="M7 7h10M7 12h7M7 17h4" stroke="var(--paper)" strokeWidth="1.6" strokeLinecap="square" />
      </svg>
      <span>Finaz</span>
    </span>
  );
}

// ----------------------------------------------------------------
// Inline glossary — supports drawer, popover, sidebar modes
// ----------------------------------------------------------------
const GlossaryContext = React.createContext({ open: () => {}, mode: "popover" });

function GlossaryProvider({ children, mode = "popover" }) {
  const [active, setActive] = useState(null); // {term, anchor}
  const open = useCallback((key, anchorEl) => {
    setActive({ key, anchorEl });
  }, []);
  const close = useCallback(() => setActive(null), []);

  return (
    <GlossaryContext.Provider value={{ open, mode }}>
      {children}
      {active && <GlossaryOverlay item={active} mode={mode} onClose={close} />}
    </GlossaryContext.Provider>
  );
}

function useGlossary() {
  return React.useContext(GlossaryContext);
}

function GlossTerm({ k, children }) {
  const { open } = useGlossary();
  const ref = useRef(null);
  return (
    <span
      ref={ref}
      tabIndex={0}
      role="button"
      className="gloss-trigger"
      onClick={(e) => { e.stopPropagation(); open(k, ref.current); }}
      onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); open(k, ref.current); } }}
    >
      {children}
    </span>
  );
}

function GlossaryCard({ item, compact }) {
  if (!item) return null;
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
      <div>
        <div className="t-eyebrow" style={{ marginBottom: 4 }}>Término</div>
        <div className="t-display" style={{ fontSize: compact ? 22 : 28, fontWeight: 500 }}>{item.term}</div>
      </div>
      <div style={{ fontSize: 14, lineHeight: 1.55, color: "var(--ink-2)" }}>{item.definition}</div>
      {item.formula && (
        <div>
          <div className="t-eyebrow" style={{ marginBottom: 4 }}>Fórmula</div>
          <div
            className="t-mono"
            style={{
              background: "var(--paper-2)",
              padding: "10px 12px",
              borderRadius: 8,
              fontSize: 13,
              color: "var(--ink)"
            }}
          >
            {item.formula}
          </div>
        </div>
      )}
      <div>
        <div className="t-eyebrow" style={{ marginBottom: 4 }}>Ejemplo</div>
        <div style={{ fontSize: 13, color: "var(--ink-2)", lineHeight: 1.5 }}>{item.example}</div>
      </div>
      <div>
        <div className="t-eyebrow" style={{ marginBottom: 4 }}>Por qué importa</div>
        <div style={{ fontSize: 13, color: "var(--ink-2)", lineHeight: 1.5 }}>{item.why}</div>
      </div>
      <div style={{
        background: "var(--amber-tint)", padding: "10px 12px", borderRadius: 8,
        fontSize: 12, color: "var(--amber)", lineHeight: 1.5
      }}>
        <span className="t-label" style={{ display: "block", color: "var(--amber)", marginBottom: 2 }}>Confusión típica</span>
        {item.miscon}
      </div>
      <button className="btn small ghost" style={{ alignSelf: "flex-start" }}>＋ Añadir a flashcards</button>
    </div>
  );
}

function GlossaryOverlay({ item, mode, onClose }) {
  const data = window.FZ_GLOSSARY[item.key];

  useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onClose]);

  if (mode === "drawer") {
    return (
      <>
        <div
          onClick={onClose}
          style={{
            position: "fixed", inset: 0, background: "rgba(22,25,34,0.18)", zIndex: 200,
            animation: "fadeIn 0.18s"
          }}
        />
        <div
          className="anim-in"
          style={{
            position: "fixed", top: 0, right: 0, bottom: 0, width: 420, zIndex: 201,
            background: "var(--card-elev)", borderLeft: "1px solid var(--rule)",
            padding: 28, overflow: "auto"
          }}
        >
          <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 16 }}>
            <span className="t-label">Glosario · {item.key}</span>
            <button className="btn small ghost" onClick={onClose}>Cerrar ✕</button>
          </div>
          <GlossaryCard item={data} />
        </div>
      </>
    );
  }

  if (mode === "sidebar") {
    // For sidebar, we render inline. The overlay still exists for keyboard/click-out.
    // But the parent likely shows a fixed sidebar. We'll still pop a small card so the
    // term highlights momentarily.
    return null;
  }

  // popover (default)
  const anchor = item.anchorEl?.getBoundingClientRect();
  if (!anchor) return null;
  const style = {
    position: "fixed",
    top: Math.min(anchor.bottom + 8, window.innerHeight - 460),
    left: Math.max(16, Math.min(anchor.left, window.innerWidth - 360)),
    zIndex: 200,
    width: 340
  };
  return (
    <>
      <div onClick={onClose} style={{ position: "fixed", inset: 0, zIndex: 199 }} />
      <div className="popover anim-in" style={style}>
        <GlossaryCard item={data} compact />
      </div>
    </>
  );
}

// Renders sidebar version when mode === sidebar
function GlossarySidebar() {
  const { mode } = useGlossary();
  const [recent, setRecent] = useState(["p_e", "gordon", "roe"]);
  if (mode !== "sidebar") return null;
  return (
    <aside style={{
      position: "sticky", top: 80, alignSelf: "flex-start",
      background: "var(--card)", border: "1px solid var(--rule)",
      borderRadius: 12, padding: 18, width: 280, maxHeight: "calc(100vh - 120px)", overflow: "auto"
    }}>
      <div className="t-label" style={{ marginBottom: 12 }}>Glosario · panel fijo</div>
      {recent.map((k) => {
        const item = window.FZ_GLOSSARY[k];
        return (
          <details key={k} style={{ marginBottom: 10, borderBottom: "1px solid var(--rule-soft)", paddingBottom: 10 }}>
            <summary style={{ cursor: "pointer", fontFamily: "var(--serif)", fontSize: 15, fontWeight: 500 }}>
              {item.term}
            </summary>
            <div style={{ marginTop: 8, fontSize: 12, color: "var(--ink-2)", lineHeight: 1.5 }}>{item.definition}</div>
            {item.formula && (
              <div className="t-mono" style={{ marginTop: 6, fontSize: 11, color: "var(--ink-3)" }}>{item.formula}</div>
            )}
          </details>
        );
      })}
    </aside>
  );
}

// ----------------------------------------------------------------
// Module ribbon (compact module label)
// ----------------------------------------------------------------
function ModuleRibbon({ code, title, color = "var(--accent)" }) {
  return (
    <div style={{ display: "inline-flex", alignItems: "center", gap: 10 }}>
      <div style={{
        width: 4, height: 18, background: color, borderRadius: 1
      }} />
      <span className="t-label">{code}</span>
      <span style={{ fontSize: 12, color: "var(--ink-3)" }}>·</span>
      <span style={{ fontSize: 12, color: "var(--ink-2)" }}>{title}</span>
    </div>
  );
}

// ----------------------------------------------------------------
// Progress bar
// ----------------------------------------------------------------
function Bar({ value, of = 1, color = "var(--accent)", height = 4 }) {
  return (
    <div style={{
      background: "var(--rule-soft)", borderRadius: 100, height,
      overflow: "hidden", width: "100%"
    }}>
      <div style={{
        background: color, height: "100%", width: `${Math.min(100, (value / of) * 100)}%`,
        transition: "width 0.4s cubic-bezier(0.22, 1, 0.36, 1)"
      }} />
    </div>
  );
}

// ----------------------------------------------------------------
// Stat block
// ----------------------------------------------------------------
function Stat({ label, value, unit, hint, big }) {
  return (
    <div>
      <div className="t-label" style={{ marginBottom: 4 }}>{label}</div>
      <div className="t-mono" style={{
        fontSize: big ? 32 : 22, fontWeight: 500, color: "var(--ink)",
        letterSpacing: "-0.02em", lineHeight: 1
      }}>
        {value}
        {unit && <span style={{ fontSize: big ? 16 : 12, color: "var(--ink-3)", marginLeft: 3 }}>{unit}</span>}
      </div>
      {hint && <div style={{ fontSize: 11, color: "var(--ink-3)", marginTop: 4 }}>{hint}</div>}
    </div>
  );
}

// ----------------------------------------------------------------
// Disclaimer banner
// ----------------------------------------------------------------
function Disclaimer({ compact }) {
  return (
    <div style={{
      fontFamily: "var(--mono)", fontSize: 10.5, letterSpacing: 0.04,
      color: "var(--ink-3)", display: "flex", alignItems: "center", gap: 8,
      padding: compact ? "6px 10px" : "10px 14px",
      background: "var(--paper-2)", borderRadius: 6, border: "1px solid var(--rule-soft)"
    }}>
      <span style={{
        display: "inline-flex", alignItems: "center", justifyContent: "center",
        width: 14, height: 14, borderRadius: "50%", background: "var(--ink-3)", color: "var(--paper)",
        fontFamily: "var(--serif)", fontStyle: "italic", fontWeight: 600, fontSize: 10
      }}>i</span>
      Contenido educativo. No constituye recomendación de inversión. Datos pedagógicos sintéticos.
    </div>
  );
}

// Expose globals for cross-script use
Object.assign(window, {
  FinazMark, GlossaryProvider, useGlossary, GlossTerm, GlossarySidebar,
  ModuleRibbon, Bar, Stat, Disclaimer
});
