// FilterBar.jsx — minimal sticky bar: single role lens + customer toggle.
// The role picker answers "how does this apply to me?" — everything
// else (doc, cycle, card-type filtering) still works via in-board chip
// clicks and drawer navigation, not header pills.
const { useState: useFilterState, useEffect: useFilterEffect, useRef: useFilterRef } = React;

function FilterBar({ filter, setFilter, customerOnly, setCustomerOnly }) {
  const { roles } = CONTENT;
  const [open, setOpen] = useFilterState(false);
  const wrapRef = useFilterRef(null);

  // Close on outside click
  useFilterEffect(() => {
    if (!open) return;
    const onDoc = (e) => {
      if (wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(false);
    };
    document.addEventListener("mousedown", onDoc);
    return () => document.removeEventListener("mousedown", onDoc);
  }, [open]);

  // Close on Esc
  useFilterEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") setOpen(false); };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [open]);

  const activeRole = filter?.type === "role" ? roles.find(r => r.id === filter.id) : null;

  // Only the Delivery tier (COL, PM, DM, PE, SE, QA) — six roles.
  const deliveryRoles = roles.filter(r => r.tier === "engagement");

  const pickRole = (rid) => {
    if (rid === null) setFilter(null);
    else setFilter({ type: "role", id: rid });
    setOpen(false);
  };

  return (
    <div className="sticky top-0 z-30 no-print"
      style={{ background: "rgba(7,10,19,0.88)", backdropFilter: "blur(14px)", WebkitBackdropFilter: "blur(14px)", borderBottom: "1px solid var(--line-strong)" }}>
      <div className="max-w-[1440px] mx-auto px-4 sm:px-8 py-3 flex items-center gap-3 sm:gap-5">

        {/* Role picker */}
        <div ref={wrapRef} className="relative flex-shrink-0">
          <button
            onClick={() => setOpen(v => !v)}
            className="flex items-center gap-2.5 h-8 pl-3 pr-2.5 rounded-lg border border-[color:var(--line-strong)] hover:border-[color:var(--accent-soft)] hover:bg-white/[0.03] transition-colors"
            aria-haspopup="true"
            aria-expanded={open}
            title="Change perspective">
            {activeRole ? (
              <>
                <span className="font-mono text-[10px] uppercase tracking-[0.22em] text-[color:var(--ink-faint)] hidden sm:inline">I am a</span>
                <span className="font-mono text-[10px] uppercase tracking-[0.22em] text-[color:var(--ink-faint)] sm:hidden">Lens</span>
                <span className="font-display text-[13px] font-medium text-[color:var(--ink)]">
                  {activeRole.name}
                </span>
              </>
            ) : (
              <span className="font-mono text-[10.5px] uppercase tracking-[0.22em] text-[color:var(--ink-dim)]">
                Show all
              </span>
            )}
            <svg width="10" height="10" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6"
              className={`text-[color:var(--ink-dim)] transition-transform ${open ? "rotate-180" : ""}`}>
              <path d="M4 6l4 4 4-4"/>
            </svg>
          </button>

          {/* Dropdown */}
          {open && (
            <div
              role="menu"
              className="absolute left-0 top-full mt-2 w-[min(88vw,340px)] rounded-xl overflow-hidden z-40"
              style={{
                background: "rgba(12,17,31,0.985)",
                border: "1px solid var(--line-strong)",
                boxShadow: "0 24px 60px -12px rgba(0,0,0,0.8)",
                backdropFilter: "blur(14px)",
              }}>
              <div className="px-4 py-3 border-b border-[color:var(--line)]">
                <div className="eyebrow">Show the model as seen by…</div>
                <p className="mt-1 text-[11.5px] leading-snug text-[color:var(--ink-faint)]">
                  Irrelevant statuses, docs and owners dim.
                </p>
              </div>

              <button
                onClick={() => pickRole(null)}
                className={`w-full text-left px-4 py-2.5 flex items-center justify-between hover:bg-white/[0.04] transition-colors border-b border-[color:var(--line)] ${!activeRole ? "bg-white/[0.03]" : ""}`}>
                <span className="font-display text-[13.5px] text-[color:var(--ink)]">Show all</span>
                {!activeRole && (
                  <svg width="11" height="11" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2"
                    className="flex-shrink-0 text-[color:var(--accent-ink)]">
                    <path d="M3 8l3.5 3.5L13 4.5"/>
                  </svg>
                )}
              </button>

              <div className="py-2">
                <div className="px-4 pb-1.5 eyebrow">Delivery team</div>
                {deliveryRoles.map(r => {
                  const active = activeRole?.id === r.id;
                  return (
                    <button key={r.id}
                      onClick={() => pickRole(r.id)}
                      className={`w-full text-left px-4 py-2 flex items-baseline gap-2.5 hover:bg-white/[0.04] transition-colors ${active ? "bg-white/[0.05]" : ""}`}>
                      <span className="font-mono text-[10.5px] font-medium text-[color:var(--accent-ink)] w-10 flex-shrink-0">{r.name}</span>
                      <span className="font-display text-[12.5px] text-[color:var(--ink)]">{r.fullName}</span>
                      {active && (
                        <svg width="11" height="11" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2"
                          className="ml-auto flex-shrink-0 text-[color:var(--accent-ink)]">
                          <path d="M3 8l3.5 3.5L13 4.5"/>
                        </svg>
                      )}
                    </button>
                  );
                })}
              </div>
            </div>
          )}
        </div>

        {/* Active-lens rationale — only shown when a role is picked, desktop only */}
        {activeRole && (
          <div className="hidden lg:flex flex-1 min-w-0 items-baseline gap-2 pr-4">
            <span className="font-mono uppercase tracking-[0.18em] text-[color:var(--ink-faint)] text-[10px] flex-shrink-0">Mission</span>
            <p className="text-[11.5px] text-[color:var(--ink-dim)] leading-snug truncate">
              {activeRole.mission}
            </p>
          </div>
        )}

        {!activeRole && <div className="flex-1" />}

        {/* Clear chip — appears when a lens is active, giving a simple way out */}
        {activeRole && (
          <button
            onClick={() => setFilter(null)}
            className="font-mono text-[10.5px] uppercase tracking-[0.18em] text-[color:var(--ink-dim)] hover:text-[color:var(--accent-ink)] transition-colors flex-shrink-0">
            Show all ✕
          </button>
        )}
      </div>
    </div>
  );
}
window.FilterBar = FilterBar;
