// RolesReference.jsx — all nine roles grouped by tier.
// Each role is a first-class specimen card (wide, DocCard-style):
// chip + full name + acronym, mission, detail, metadata strip, statuses owned.

function RolesReference({ onOpen, filter }) {
  const { roles, initiativeStatuses, epicStatuses, cardStatuses, docs, cycles, transitions } = CONTENT;
  const allStatuses = [
    ...initiativeStatuses.map(s => ({ ...s, _track: "Initiative" })),
    ...epicStatuses.map(s => ({ ...s, _track: "Epic" })),
    ...cardStatuses.map(s => ({ ...s, _track: "Card" })),
  ];

  const tiers = [
    { id: "oversight", label: "Oversight", note: "Outside the engagement flow. Accountability presence at the organizational level.", roles: roles.filter(r => r.tier === "oversight") },
    { id: "engagement", label: "Engagement", note: "The flow from customer intent to production. COL → PM → DM → PE/SE → QA.", roles: roles.filter(r => r.tier === "engagement") },
    { id: "customer", label: "Customer", note: "Three explicit touchpoints: Milestone signoff, UAT Review, Milestone Acceptance.", roles: roles.filter(r => r.tier === "customer") },
  ];

  return (
    <section id="roles" className="relative border-t border-[color:var(--line)]">
      <div className="max-w-[1280px] mx-auto px-8 py-16">
        <div className="eyebrow">04 · Roles</div>
        <h2 className="font-display text-[34px] font-medium mt-2 text-[color:var(--ink)] max-w-3xl">
          Nine roles. Three tiers.
        </h2>
        <p className="mt-4 text-[14.5px] leading-relaxed text-[color:var(--ink-dim)]">
          {transitions.libraryToRoles}
        </p>

        {/* Acronym reference — glanceable expansion of every role code */}
        <div className="mt-8 rounded-xl hairline p-5" style={{ background: "rgba(14,19,34,0.5)" }}>
          <div className="eyebrow mb-3">Acronym reference</div>
          <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-x-6 gap-y-2.5">
            {roles.map(r => {
              const chipCls = r.tier === "customer" ? "role-chip-customer" : r.tier === "oversight" ? "role-chip-oversight" : "role-chip";
              return (
                <button key={r.id}
                  onClick={() => onOpen({ type: "role", id: r.id })}
                  className="flex items-baseline gap-2.5 text-left hover:opacity-85 transition-opacity whitespace-nowrap">
                  <span className={`${chipCls} rounded-full px-2 py-0.5 text-[10px] font-mono uppercase tracking-[0.22em] shrink-0`}>
                    {r.name}
                  </span>
                  <span className="text-[13px] text-[color:var(--ink)] leading-tight whitespace-nowrap">
                    {r.fullName}
                  </span>
                </button>
              );
            })}
          </div>
        </div>

        <div className="mt-12 space-y-12">
          {tiers.map(t => (
            <div key={t.id}>
              <div className="mb-5 flex items-baseline gap-4 flex-wrap">
                <div className="font-display text-[20px] font-medium text-[color:var(--ink)]">{t.label}</div>
                <p className="font-serif italic text-[14px] text-[color:var(--ink-dim)] max-w-xl">{t.note}</p>
              </div>
              <div className={`grid ${t.roles.length === 1 ? "grid-cols-1" : "grid-cols-1 lg:grid-cols-2"} gap-5`}>
                {t.roles.map(r => (
                  <RoleCard key={r.id} role={r} allStatuses={allStatuses} filter={filter} onOpen={onOpen} />
                ))}
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ──────────────────────────────────────────────────────────────
// ROLE CARD — wide, DocCard-style. Full name + acronym chip + mission,
// metadata strip (tier / primary cycle / graded on), detail, statuses owned.
// ──────────────────────────────────────────────────────────────
function RoleCard({ role, allStatuses, filter, onOpen }) {
  const { cycles } = CONTENT;
  const owned = allStatuses.filter(s => (s.owners || []).includes(role.id));
  const active = !filter || filter.type !== "role" || filter.id === role.id;
  const chipCls = role.tier === "customer" ? "role-chip-customer" : role.tier === "oversight" ? "role-chip-oversight" : "role-chip";
  const isCustomer = role.tier === "customer";
  const isOversight = role.tier === "oversight";

  // Primary cycles this role owns (from cycles.ownerRoles)
  const primaryCycles = cycles.filter(c => (c.ownerRoles || []).includes(role.id));

  // Extract first sentence of details for mission tagline fallback
  const tagline = role.mission;
  const body = role.details;

  return (
    <div className={`rounded-2xl p-6 md:p-7 transition-all ${active ? "" : "opacity-30 saturate-50"}`}
      style={{
        background: isCustomer
          ? "linear-gradient(180deg, rgba(240,196,132,0.05), rgba(14,26,28,0.55))"
          : isOversight
            ? "linear-gradient(180deg, rgba(180,180,210,0.04), rgba(12,17,31,0.55))"
            : "linear-gradient(180deg, rgba(25,33,54,0.55), rgba(12,17,31,0.55))",
        border: `1px solid ${isCustomer ? "rgba(240,196,132,0.22)" : "var(--line)"}`,
      }}>
      {/* Header */}
      <div className="flex flex-wrap items-start justify-between gap-4 mb-5">
        <div className="min-w-0 flex-1">
          <div className="eyebrow" style={{ color: isCustomer ? "var(--customer)" : isOversight ? "var(--ink-faint)" : "var(--accent-ink)" }}>
            {isOversight ? "Oversight · escalation-triggered" : isCustomer ? "Customer · engagement touchpoint" : "Engagement · in the flow"}
          </div>
          <div className="mt-2 flex items-baseline gap-3 flex-wrap whitespace-nowrap">
            <span className={`${chipCls} rounded-full px-2.5 py-0.5 text-[11px] font-mono uppercase tracking-[0.22em]`}>
              {role.name}
            </span>
            <h3 className="font-display text-[28px] font-medium text-[color:var(--ink)] leading-tight whitespace-nowrap">
              {role.fullName || role.name}
            </h3>
          </div>
          <p className="mt-3 font-serif italic text-[15px] text-[color:var(--ink-dim)] max-w-2xl leading-snug">
            {tagline}
          </p>
        </div>
        <div className="flex flex-col items-end gap-1.5 shrink-0">
          <span className="font-mono text-[10px] uppercase tracking-[0.22em] text-[color:var(--ink-faint)]">
            Owns {owned.length} status{owned.length === 1 ? "" : "es"}
          </span>
        </div>
      </div>

      {/* Metadata strip */}
      <div className="grid grid-cols-2 gap-4 py-4 border-y border-[color:var(--line)]">
        <div>
          <div className="eyebrow mb-1.5">Primary cycle{primaryCycles.length === 1 ? "" : "s"}</div>
          <div className="flex flex-wrap gap-1">
            {primaryCycles.length > 0 ? primaryCycles.map(c => (
              <button key={c.id} onClick={() => onOpen({ type: "cycle", id: c.id })}
                className="rounded px-2 py-0.5 text-[10px] font-mono uppercase tracking-[0.2em] hover:opacity-85"
                style={{ background: "rgba(39,194,182,0.08)", color: "var(--accent-ink)", border: "1px solid rgba(39,194,182,0.25)" }}>
                {c.name.replace(" Cycle", "")}
              </button>
            )) : (
              <span className="font-mono text-[10px] text-[color:var(--ink-faint)] uppercase tracking-[0.2em]">—</span>
            )}
          </div>
        </div>
        <div>
          <div className="eyebrow mb-1.5">Statuses owned</div>
          <div className="text-[13px] text-[color:var(--ink)] tabular-nums">
            {owned.length} · across {new Set(owned.map(s => s._track)).size} track{new Set(owned.map(s => s._track)).size === 1 ? "" : "s"}
          </div>
        </div>
      </div>

      {/* Body */}
      <div className="mt-5">
        <div className="eyebrow mb-2">Detail</div>
        <p className="text-[13px] leading-relaxed text-[color:var(--ink)]">{body}</p>
      </div>

      {/* Also known as — cross-org role equivalents */}
      {role.equivalents && role.equivalents.length > 0 && (
        <div className="mt-5 pt-5 border-t border-[color:var(--line)]">
          <div className="eyebrow mb-2">Also known as</div>
          <p className="text-[13px] leading-relaxed text-[color:var(--ink-dim)]">
            {role.equivalents.map((eq, i) => (
              <React.Fragment key={i}>
                {i > 0 && <span className="text-[color:var(--ink-faint)] mx-2">·</span>}
                <span style={eq.reason ? { color: "var(--accent-ink)", fontWeight: 500 } : undefined}>
                  {eq.label}
                </span>
              </React.Fragment>
            ))}
          </p>
        </div>
      )}

      {/* Statuses owned — grouped by track */}
      {owned.length > 0 && (
        <div className="mt-5 pt-5 border-t border-[color:var(--line)]">
          <div className="eyebrow mb-3">
            Statuses owned · click any to open
          </div>
          <div className="grid grid-cols-1 gap-4">
            {["Initiative", "Epic", "Card"].map(track => {
              const trackStatuses = owned.filter(s => s._track === track);
              if (trackStatuses.length === 0) return null;
              return (
                <div key={track}>
                  <div className="font-mono text-[10px] uppercase tracking-[0.22em] text-[color:var(--ink-faint)] mb-2">
                    {track} · {trackStatuses.length}
                  </div>
                  <div className="flex flex-wrap gap-1.5">
                    {trackStatuses.map(s => (
                      <button key={s.id} onClick={() => onOpen({ type: "status", id: s.id })}
                        className="role-chip rounded-full px-2 py-0.5 text-[10px] font-mono uppercase tracking-[0.2em] hover:opacity-85"
                        title={s.activityVerb}>
                        {s.name}
                      </button>
                    ))}
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}
    </div>
  );
}

window.RolesReference = RolesReference;
