// ─────────────────────────────────────────────────────────────
// REFERENCES VIEW — Lista de suplementos como uma gaveta
// (cada nome de suplemento abre/fecha as referências dele,
// igual ao padrão visual da lista de produtos).
// ─────────────────────────────────────────────────────────────

const { useState: useStateRefs, useMemo: useMemoRefs } = React;

function ReferenceCard({ r, i, t }) {
  const inner = (
    <>
      <div style={{
        display: "flex", alignItems: "baseline", gap: 8, marginBottom: 8,
      }}>
        <span style={{
          fontFamily: TYPE.mono, fontSize: 10, color: t.ink4,
          fontVariantNumeric: "tabular-nums",
        }}>[{String(i + 1).padStart(2, "0")}]</span>
        {r.year && (
          <span style={{
            fontFamily: TYPE.sans, fontSize: 10, color: t.ink3,
            letterSpacing: "0.10em", textTransform: "uppercase", fontWeight: 700,
          }}>{r.year}</span>
        )}
        {r.type && (
          <span style={{
            fontFamily: TYPE.sans, fontSize: 9.5, color: t.ink4,
            letterSpacing: "0.08em", textTransform: "uppercase", fontWeight: 600,
          }}>· {r.type}</span>
        )}
      </div>
      <div style={{
        fontFamily: TYPE.sans, fontSize: 13.5, lineHeight: 1.45,
        color: t.ink1, fontWeight: 600, marginBottom: 8,
        textAlign: "justify",
      }}>{r.title}</div>
      {r.authors && (
        <div style={{
          fontFamily: TYPE.sans, fontSize: 12, lineHeight: 1.5,
          color: t.ink2, marginBottom: 6,
        }}>{r.authors}</div>
      )}
      {r.journal && (
        <div style={{
          fontFamily: TYPE.sans, fontSize: 11, lineHeight: 1.4,
          color: t.ink3, fontStyle: "italic",
        }}>{r.journal}</div>
      )}
      {r.link && (
        <div style={{
          marginTop: 10, paddingTop: 10, borderTop: `1px solid ${t.border}`,
          display: "flex", alignItems: "center", gap: 6,
          fontFamily: TYPE.mono, fontSize: 10.5, color: t.ink2,
          letterSpacing: "0.04em",
        }}>
          <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M10 14a5 5 0 0 0 7.07 0l3-3a5 5 0 0 0-7.07-7.07l-1.5 1.5"></path>
            <path d="M14 10a5 5 0 0 0-7.07 0l-3 3a5 5 0 0 0 7.07 7.07l1.5-1.5"></path>
          </svg>
          <span style={{
            overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", flex: 1,
          }}>Abrir fonte</span>
        </div>
      )}
    </>
  );
  const card = {
    display: "block",
    textAlign: "left",
    background: t.bg0, border: `1px solid ${t.border}`, borderRadius: 12,
    padding: "14px 16px",
    color: "inherit", textDecoration: "none",
    cursor: r.link ? "pointer" : "default",
  };
  return r.link ? (
    <a href={r.link} target="_blank" rel="noreferrer" style={card}>{inner}</a>
  ) : (
    <div style={card}>{inner}</div>
  );
}

function SupplementRefsDrawer({ supp, refs, t, expanded, onToggle }) {
  return (
    <div style={{
      background: t.bg1, border: `1px solid ${t.border}`,
      borderRadius: 14, overflow: "hidden",
    }}>
      {/* CABEÇALHO — clicável */}
      <button onClick={onToggle} style={{
        all: "unset",
        cursor: "pointer",
        display: "flex", alignItems: "center", gap: 14,
        padding: "16px 18px",
        width: "100%", boxSizing: "border-box",
      }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{
            fontFamily: TYPE.display, fontSize: 20, color: t.ink1,
            letterSpacing: "-0.005em", lineHeight: 1.1, textTransform: "uppercase",
            marginBottom: 4,
          }}>{supp}</div>
          <div style={{
            fontFamily: TYPE.sans, fontSize: 11, color: t.ink3,
            letterSpacing: "0.10em", textTransform: "uppercase", fontWeight: 700,
          }}>
            {refs.length} {refs.length === 1 ? "referência" : "referências"}
          </div>
        </div>
        <div style={{
          flexShrink: 0,
          width: 34, height: 34, borderRadius: 999,
          background: t.bg0, border: `1px solid ${t.border}`,
          display: "flex", alignItems: "center", justifyContent: "center",
          color: t.ink2,
          transition: "transform 0.2s ease",
          transform: expanded ? "rotate(180deg)" : "rotate(0deg)",
        }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
            <polyline points="6 9 12 15 18 9"></polyline>
          </svg>
        </div>
      </button>

      {/* GAVETA */}
      {expanded && (
        <div style={{
          padding: "0 14px 16px",
          display: "flex", flexDirection: "column", gap: 8,
          borderTop: `1px solid ${t.border}`,
          paddingTop: 14, marginTop: 0,
        }}>
          {refs.map((r, i) => <ReferenceCard key={i} r={r} i={i} t={t} />)}
        </div>
      )}
    </div>
  );
}

function ReferencesView({ t, query }) {
  const all = (typeof REFERENCIAS_SUPLEMENTOS !== "undefined" ? REFERENCIAS_SUPLEMENTOS : []);

  const q = (query || "").toLowerCase().trim();
  const filtered = q
    ? all.filter(r => (
        r.supplement.toLowerCase().includes(q) ||
        (r.title || "").toLowerCase().includes(q) ||
        (r.authors || "").toLowerCase().includes(q) ||
        (r.journal || "").toLowerCase().includes(q)
      ))
    : all;

  // Agrupa por suplemento (preservando ordem de aparição)
  const grouped = useMemoRefs(() => {
    const map = new Map();
    filtered.forEach(r => {
      if (!map.has(r.supplement)) map.set(r.supplement, []);
      map.get(r.supplement).push(r);
    });
    return Array.from(map.entries());
  }, [filtered]);

  // Estado: quais suplementos estão expandidos
  // Quando há busca ativa, abre todos automaticamente
  const [expandedSet, setExpandedSet] = useStateRefs(() => new Set());
  const toggle = (supp) => {
    setExpandedSet(prev => {
      const next = new Set(prev);
      if (next.has(supp)) next.delete(supp); else next.add(supp);
      return next;
    });
  };

  if (filtered.length === 0) {
    return (
      <div style={{
        padding: "40px 24px", textAlign: "center",
        fontFamily: TYPE.sans, fontSize: 13, color: t.ink3, lineHeight: 1.6,
      }}>
        Nenhuma referência encontrada{q ? ` para "${query}"` : ""}.
      </div>
    );
  }

  return (
    <div style={{ padding: "8px 16px 12px" }}>
      {/* Cabeçalho introdutório */}
      <div style={{
        marginBottom: 16, padding: "16px 18px",
        background: t.bg1, border: `1px solid ${t.border}`, borderRadius: 14,
      }}>
        <div style={{
          fontFamily: TYPE.sans, fontSize: 10, color: t.ink3,
          letterSpacing: "0.18em", textTransform: "uppercase", fontWeight: 700,
          marginBottom: 8,
        }}>Referências bibliográficas</div>
        <p style={{
          fontFamily: TYPE.sans, fontSize: 13, lineHeight: 1.6, color: t.ink2,
          margin: 0, textAlign: "justify",
        }}>
          Estudos clínicos, revisões sistemáticas e meta-análises que embasam o conteúdo deste acervo. Toque no nome do suplemento para abrir a gaveta com as referências.
        </p>
      </div>

      {/* Lista de gavetas — uma por suplemento */}
      <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
        {grouped.map(([supp, refs]) => (
          <SupplementRefsDrawer
            key={supp}
            supp={supp}
            refs={refs}
            t={t}
            expanded={q ? true : expandedSet.has(supp)}
            onToggle={() => toggle(supp)}
          />
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { ReferencesView });
