// PSM Expert — Glossário de Segurança de Processos

const _GIMG = window.PSM_IMG || "img/";
const _GCATS = window.GLOSS_CATS || [];
const _GTERMS = window.GLOSS_TERMS || [];

function GlossCard({ t, open, onToggle }) {
  return (
    <article style={glossSt.card} id={"g-" + t.id}>
      <button
        style={open ? { ...glossSt.btn, ...glossSt.btnOpen } : glossSt.btn}
        onClick={onToggle}
        aria-expanded={open}
      >
        <div style={{ flex: 1 }}>
          <span style={glossSt.name}>{t.term}</span>
          <span style={glossSt.en}>{t.en}</span>
        </div>
        <svg
          style={open ? { ...glossSt.chev, transform: "rotate(180deg)" } : glossSt.chev}
          width="16" height="16" viewBox="0 0 16 16" fill="none"
          aria-hidden="true"
        >
          <path d="M4 6l4 4 4-4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
        </svg>
      </button>
      {open && (
        <div style={glossSt.body}>
          <p style={glossSt.def}>{t.def}</p>
          <p style={glossSt.pq}>
            <strong style={glossSt.pqL}>Por que importa.&nbsp;</strong>
            {t.pq}
          </p>
          <p style={glossSt.norm}>
            <span style={glossSt.normL}>Referência:&nbsp;</span>
            {t.norma}
          </p>

          {t.img && (
            <img
              src={_GIMG + t.img}
              alt={"Diagrama: " + t.term}
              style={glossSt.termImg}
              loading="lazy"
            />
          )}
        </div>
      )}
    </article>
  );
}

function GlossarioPage() {
  const [q, setQ] = React.useState("");
  const [openMap, setOpenMap] = React.useState({});

  const qLow = q.trim().toLowerCase();
  const searching = qLow.length >= 2;

  const visible = searching
    ? _GTERMS.filter(t =>
        t.term.toLowerCase().includes(qLow) ||
        t.en.toLowerCase().includes(qLow) ||
        t.def.toLowerCase().includes(qLow) ||
        t.norma.toLowerCase().includes(qLow)
      )
    : _GTERMS;

  const isOpen = id => searching ? visible.some(t => t.id === id) : !!openMap[id];
  const toggle = id => setOpenMap(s => ({ ...s, [id]: !s[id] }));

  const byCat = {};
  visible.forEach(t => { (byCat[t.cat] = byCat[t.cat] || []).push(t); });

  const count = visible.length;

  return (
    <>
      <Header />

      {/* ── Hero ── */}
      <section style={glossSt.hero}>
        <div style={glossSt.heroIn}>
          <p style={glossSt.eye}>Referência técnica gratuita · 42 verbetes</p>
          <h1 style={glossSt.h1}>Glossário de Segurança de Processos</h1>
          <p style={glossSt.sub}>
            Termos essenciais de HAZOP, QRA, LOPA, SIL, Bow-Tie e PSM —
            definições claras com referências normativas.
          </p>
          <div style={glossSt.searchWrap}>
            <input
              type="search"
              placeholder="Buscar termo, sigla ou conceito…"
              value={q}
              onChange={e => setQ(e.target.value)}
              style={glossSt.searchIn}
              autoComplete="off"
              aria-label="Buscar no glossário"
            />
          </div>
          {searching && (
            <p style={glossSt.searchHint}>
              {count > 0
                ? `${count} verbete${count > 1 ? "s" : ""} encontrado${count > 1 ? "s" : ""}`
                : "Nenhum verbete encontrado"}
            </p>
          )}
        </div>
      </section>

      {/* ── Category nav ── */}
      <nav style={glossSt.catNav} aria-label="Categorias">
        <div style={glossSt.catNavIn}>
          {_GCATS.map(c => (
            <a key={c.id} href={"#gs-" + c.id} style={glossSt.pill}>{c.label}</a>
          ))}
        </div>
      </nav>

      {/* ── Terms ── */}
      <main style={glossSt.main}>
        {_GCATS.map(cat => {
          const terms = byCat[cat.id];
          if (!terms || !terms.length) return null;
          return (
            <section key={cat.id} id={"gs-" + cat.id} style={glossSt.sec}>
              <div style={glossSt.secIn}>
                <h2 style={glossSt.secH}>{cat.label}</h2>
                <div style={glossSt.grid}>
                  {terms.map(t => (
                    <GlossCard key={t.id} t={t} open={isOpen(t.id)} onToggle={() => toggle(t.id)} />
                  ))}
                </div>
              </div>
            </section>
          );
        })}
        {!visible.length && (
          <div style={glossSt.noRes}>
            <p>Nenhum verbete encontrado para "<strong>{q}</strong>". Tente outro termo ou sigla.</p>
          </div>
        )}
      </main>

      <CtaFinal
        title="Precisa de um estudo de risco?"
        sub="Fale com a PSM Expert. Proposta técnica detalhada em até 48 horas."
        micro="Sem compromisso · HAZOP, QRA, LOPA, SIL, PSM · Todo o Brasil"
      />
      <Footer />
    </>
  );
}

const glossSt = {
  // Hero
  hero: { background: "#071C36", padding: "96px 24px 72px" },
  heroIn: { maxWidth: 720, margin: "0 auto", textAlign: "center" },
  eye: { color: "#F5A623", fontFamily: "'IBM Plex Mono',monospace", fontSize: 13, letterSpacing: "0.08em", textTransform: "uppercase", margin: "0 0 20px" },
  h1: { fontFamily: "'Barlow Condensed',sans-serif", fontWeight: 700, fontSize: "clamp(38px,5.5vw,62px)", color: "#fff", margin: "0 0 20px", lineHeight: 1.1 },
  sub: { color: "rgba(255,255,255,.72)", fontSize: 18, lineHeight: 1.6, margin: "0 0 40px" },
  searchWrap: { maxWidth: 540, margin: "0 auto" },
  searchIn: { width: "100%", padding: "14px 20px", borderRadius: 8, border: "1.5px solid rgba(245,166,35,.4)", background: "rgba(255,255,255,.07)", color: "#fff", fontSize: 16, outline: "none", boxSizing: "border-box", fontFamily: "'IBM Plex Sans',sans-serif" },
  searchHint: { color: "rgba(255,255,255,.45)", fontSize: 13, margin: "12px 0 0", fontFamily: "'IBM Plex Mono',monospace" },

  // Cat nav
  catNav: { background: "#0D2540", borderBottom: "1px solid rgba(255,255,255,.08)", position: "sticky", top: 0, zIndex: 90, overflowX: "auto" },
  catNavIn: { display: "flex", maxWidth: 1200, margin: "0 auto", padding: "0 16px" },
  pill: { display: "block", padding: "13px 15px", color: "rgba(255,255,255,.55)", fontSize: 12, fontFamily: "'IBM Plex Mono',monospace", textDecoration: "none", whiteSpace: "nowrap", borderBottom: "2px solid transparent", transition: "color .15s" },

  // Main
  main: { background: "#F2F4F7", minHeight: "60vh" },
  sec: { padding: "60px 24px" },
  secIn: { maxWidth: 1200, margin: "0 auto" },
  secH: { fontFamily: "'Barlow Condensed',sans-serif", fontWeight: 700, fontSize: 30, color: "#071C36", margin: "0 0 28px", paddingBottom: 14, borderBottom: "2px solid #F5A623" },
  grid: { display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(460px, 1fr))", gap: 10 },

  // Card
  card: { background: "#fff", borderRadius: 8, border: "1px solid #E2E7EE", overflow: "hidden" },
  btn: { width: "100%", background: "none", border: "none", padding: "16px 20px", cursor: "pointer", display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 12, textAlign: "left" },
  btnOpen: { borderBottom: "1px solid #E2E7EE" },
  name: { display: "block", fontFamily: "'IBM Plex Sans',sans-serif", fontWeight: 600, fontSize: 15, color: "#071C36", marginBottom: 3 },
  en: { fontFamily: "'IBM Plex Mono',monospace", fontSize: 11, color: "#8A9AAB", display: "block" },
  chev: { flexShrink: 0, color: "#8A9AAB", transition: "transform .2s", marginTop: 3 },

  // Card body
  body: { padding: "20px 20px 24px" },
  def: { fontSize: 14, lineHeight: 1.75, color: "#1A2332", margin: "0 0 14px" },
  pq: { fontSize: 14, lineHeight: 1.65, color: "#3D4F63", margin: "0 0 10px", fontStyle: "italic" },
  pqL: { fontStyle: "normal", color: "#071C36" },
  norm: { fontSize: 12, color: "#8A9AAB", margin: "0 0 12px", fontFamily: "'IBM Plex Mono',monospace" },
  normL: { color: "#6A7A8A" },
  svcLink: { display: "inline-block", fontSize: 13, color: "#F5A623", fontWeight: 600, textDecoration: "none" },
  termImg: { width: "100%", borderRadius: 6, marginTop: 20, display: "block" },

  noRes: { padding: "80px 24px", textAlign: "center", color: "#8A9AAB", fontSize: 17 },
};

ReactDOM.createRoot(document.getElementById("root")).render(<GlossarioPage />);
