// Library.jsx — the reference shelf. Each doc is a first-class specimen card.
// Click any status chip to return to Board with that status highlighted.

const { useState: useLibState } = React;

function Library({ onOpen }) {
  const { docs, transitions } = CONTENT;
  return (
    <section id="library" className="relative border-t border-[color:var(--line)]">
      <div className="max-w-[1280px] mx-auto px-8 py-16">
        <div className="eyebrow">03 · Library</div>
        <h2 className="font-display text-[34px] font-medium mt-2 text-[color:var(--ink)] max-w-3xl">
          The six documents.
        </h2>
        <p className="mt-4 text-[14.5px] leading-relaxed text-[color:var(--ink-dim)]">
          {transitions.orthogonalToLibrary}
        </p>

        <div className="mt-10 space-y-5">
          {docs.map(d => <DocCard key={d.id} doc={d} onOpen={onOpen} />)}
        </div>
      </div>
    </section>
  );
}

function DocCard({ doc, onOpen }) {
  const { roles, initiativeStatuses, epicStatuses, cardStatuses } = CONTENT;
  const rolesById = Object.fromEntries(roles.map(r => [r.id, r]));

  // Which statuses reference this doc as active
  const allStatuses = [
    ...initiativeStatuses.map(s => ({ ...s, _track: "Initiative" })),
    ...epicStatuses.map(s => ({ ...s, _track: "Epic" })),
    ...cardStatuses.map(s => ({ ...s, _track: "Card" })),
  ];
  const activeAt = allStatuses.filter(s => s.activeDoc === doc.id);
  const derivedAt = allStatuses.filter(s => s.derivedArtifact === doc.id);
  const trackLabel = doc.jiraType
    ? (doc.jiraType === "Initiative" ? "Initiative" : doc.jiraType === "Epic" ? "Epic" : "Card")
    : null;

  const isCustomerFull = doc.customerFacing === "full";
  const isCustomerPartial = doc.customerFacing === "partial";
  const isDerived = !!doc.derived;

  return (
    <div className={`rounded-2xl p-6 md:p-7 transition-all ${isCustomerFull ? "cell-customer" : ""}`}
      style={{
        background: isCustomerFull
          ? "linear-gradient(180deg, rgba(125,238,200,0.06), rgba(14,26,28,0.55))"
          : "linear-gradient(180deg, rgba(25,33,54,0.55), rgba(12,17,31,0.55))",
        border: `1px solid ${isCustomerFull ? "rgba(125,238,200,0.25)" : "var(--line)"}`,
      }}>
      {/* Header */}
      <div className="flex flex-wrap items-start justify-between gap-4 mb-5">
        <div>
          <div className="flex items-center gap-2 flex-wrap">
            {isDerived && (
              <span className="font-mono text-[9.5px] uppercase tracking-[0.25em]"
                style={{ color: "oklch(0.85 0.08 75)" }}>
                Derived publication
              </span>
            )}
            {doc.jiraType && (
              <span className="font-mono text-[9.5px] uppercase tracking-[0.25em] text-[color:var(--ink-faint)]">
                Jira · {doc.jiraType}
              </span>
            )}
          </div>
          <h3 className="font-display text-[28px] font-medium text-[color:var(--ink)] mt-1 leading-tight">
            {doc.name}
          </h3>
          <p className="mt-2 font-serif italic text-[15px] text-[color:var(--ink-dim)] max-w-xl leading-snug">
            {doc.details.split(".")[0]}.
          </p>
        </div>
        <div className="flex flex-col items-end gap-1.5">
          {isCustomerFull && (
            <span className="customer-pill rounded-full px-2.5 py-0.5 text-[10px] font-mono uppercase tracking-[0.22em] flex items-center gap-1.5">
              <span className="customer-dot" /> Customer-facing
            </span>
          )}
          {isCustomerPartial && (
            <span className="customer-pill rounded-full px-2.5 py-0.5 text-[10px] font-mono uppercase tracking-[0.22em] opacity-80">
              Partial customer-facing
            </span>
          )}
          {doc.visuals && (() => {
            const level = doc.visuals.level;
            const label = level === "required" ? "Required"
                        : level === "encouraged" ? "Encouraged"
                        : "Situational";
            const tone = level === "required"
              ? { bg: "rgba(191,148,255,0.14)", border: "rgba(191,148,255,0.42)", ink: "oklch(0.85 0.12 300)" }
              : level === "encouraged"
              ? { bg: "rgba(191,148,255,0.08)", border: "rgba(191,148,255,0.28)", ink: "oklch(0.78 0.08 300)" }
              : { bg: "rgba(255,255,255,0.03)", border: "var(--line-strong)", ink: "var(--ink-faint)" };
            return (
              <span className="rounded-full px-2.5 py-0.5 text-[10px] font-mono uppercase tracking-[0.22em] inline-flex items-center gap-1.5"
                style={{ background: tone.bg, border: `1px solid ${tone.border}`, color: tone.ink }}
                title={doc.visuals.content}>
                <svg width="9" height="9" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6">
                  <rect x="2" y="3" width="12" height="9" rx="1"/>
                  <path d="M2 11l3.5-3 2.5 2 3-3 3 3"/>
                  <circle cx="6" cy="6" r="0.8" fill="currentColor"/>
                </svg>
                Visuals · {label}
              </span>
            );
          })()}
          {doc.acFormat !== "—" && (
            <span className="rounded-full px-2.5 py-0.5 text-[10px] font-mono uppercase tracking-[0.22em] inline-flex items-center"
              style={{
                background: "rgba(255,255,255,0.04)",
                border: "1px solid var(--line-strong)",
                color: "var(--ink-dim)",
              }}>
              AC · {doc.acFormat}
            </span>
          )}
        </div>
      </div>

      {/* Metadata grid */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4 py-4 border-y border-[color:var(--line)]">
        <div>
          <div className="eyebrow mb-1.5">Author</div>
          <div className="flex flex-wrap gap-1">
            {doc.author.map(rid => {
              const r = rolesById[rid]; if (!r) return null;
              const cls = r.tier === "customer" ? "role-chip-customer" : r.tier === "oversight" ? "role-chip-oversight" : "role-chip";
              return (
                <button key={rid} onClick={() => onOpen({ type: "role", id: rid })}
                  className={`${cls} rounded-full px-2 py-0.5 text-[10px] font-mono uppercase tracking-[0.2em]`}>
                  {r.name}
                </button>
              );
            })}
          </div>
        </div>
        <div>
          <div className="eyebrow mb-1.5">Approver</div>
          <div className="flex flex-wrap gap-1">
            {doc.approver.map(rid => {
              const r = rolesById[rid]; if (!r) return null;
              const cls = r.tier === "customer" ? "role-chip-customer" : r.tier === "oversight" ? "role-chip-oversight" : "role-chip";
              return (
                <button key={rid} onClick={() => onOpen({ type: "role", id: rid })}
                  className={`${cls} rounded-full px-2 py-0.5 text-[10px] font-mono uppercase tracking-[0.2em]`}>
                  {r.name}
                </button>
              );
            })}
          </div>
        </div>
        <div className="md:col-span-2">
          <div className="eyebrow mb-1.5">Storage</div>
          <div className="font-mono text-[11.5px] text-[color:var(--ink-dim)]">{doc.location}</div>
        </div>
      </div>

      {/* Body: sections + full detail */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mt-5">
        <div>
          <div className="eyebrow mb-2">Sections</div>
          <ol className="list-decimal pl-5 space-y-1 text-[12.5px] text-[color:var(--ink-dim)]">
            {doc.sections.map((s, i) => (
              <li key={i}><span className="font-mono text-[12px]">{s}</span></li>
            ))}
          </ol>
        </div>
        <div>
          <div className="eyebrow mb-2">Detail</div>
          <p className="text-[13px] leading-relaxed text-[color:var(--ink)]">{doc.details}</p>
        </div>
      </div>

      {/* Visuals callout — only for docs that carry visual artifacts */}
      {doc.visuals && (
        <div className="mt-5 pt-5 border-t border-[color:var(--line)]">
          <div className="flex flex-wrap items-start gap-x-5 gap-y-3">
            <div className="flex-shrink-0">
              <div className="flex items-center gap-2">
                <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5"
                  style={{ color: "oklch(0.82 0.1 300)" }}>
                  <rect x="2" y="3" width="12" height="9" rx="1"/>
                  <path d="M2 11l3.5-3 2.5 2 3-3 3 3"/>
                  <circle cx="6" cy="6" r="0.9" fill="currentColor"/>
                </svg>
                <div className="eyebrow" style={{ color: "oklch(0.82 0.1 300)" }}>Visuals</div>
              </div>
              <div className="font-mono text-[11px] text-[color:var(--ink-faint)] mt-1">
                {doc.visuals.section}
              </div>
            </div>
            <div className="flex-1 min-w-[200px]">
              <div className="eyebrow mb-1">What counts</div>
              <p className="text-[12.5px] leading-relaxed text-[color:var(--ink-dim)]">
                {doc.visuals.content}
              </p>
            </div>
            <div className="flex-shrink-0">
              <div className="eyebrow mb-1">Role</div>
              <div className="text-[12.5px] text-[color:var(--ink)]">{doc.visuals.role}</div>
            </div>
          </div>
        </div>
      )}

      {/* Lifecycle presence — which statuses activate this doc */}
      {(activeAt.length > 0 || derivedAt.length > 0) && (
        <div className="mt-5 pt-5 border-t border-[color:var(--line)]">
          {activeAt.length > 0 && (
            <>
              <div className="eyebrow mb-2">
                Active through {trackLabel ? `${trackLabel} · ` : ""}
                {activeAt.length} status{activeAt.length === 1 ? "" : "es"}
              </div>
              <div className="flex flex-wrap gap-1.5 mb-3">
                {activeAt.map(s => (
                  <button key={s.id} onClick={() => onOpen({ type: "status", id: s.id })}
                    className="role-chip rounded-full px-2.5 py-0.5 text-[10.5px] font-mono uppercase tracking-[0.2em] hover:opacity-85"
                    title={s.activityVerb}>
                    {s._track !== trackLabel ? `${s._track} · ${s.name}` : s.name}
                  </button>
                ))}
              </div>
            </>
          )}
          {derivedAt.length > 0 && (
            <>
              <div className="eyebrow mb-2">Surfaces at · {derivedAt.length} status{derivedAt.length === 1 ? "" : "es"}</div>
              <div className="flex flex-wrap gap-1.5">
                {derivedAt.map(s => (
                  <button key={s.id} onClick={() => onOpen({ type: "status", id: s.id })}
                    className="customer-pill rounded-full px-2.5 py-0.5 text-[10.5px] font-mono uppercase tracking-[0.2em] hover:opacity-85"
                    title={s.activityVerb}>
                    ↑ {s.name}
                  </button>
                ))}
              </div>
            </>
          )}
        </div>
      )}
    </div>
  );
}

window.Library = Library;
