/* T.UI — shared primitives ported from packages/shared/src (and
 * apps/web/src/components/PersonAvatar.tsx). Sources noted per section:
 *   components/ui/{button,badge,input,checkbox,skeleton,card,separator,
 *     progress,dialog,alert-dialog,dropdown-menu,popover,tooltip,select,
 *     tabs,command,avatar,logo-avatar,table,table-scroll-region,
 *     use-hidden-columns,control-pill}
 *   components/{confirm-dialog,page-container,page-header,segmented-switch,
 *     type-chip,signal-filter,filter-popover/*,overflow-menu,table-chrome,
 *     data-table,placeholder-avatar,user-avatar-stack,app-sidebar/*,Logo,
 *     CompanyLogo,DeveloperBar}
 *   lib/{cn→T.cn,brandImage,signal-types}, hooks/use-account-filter-options
 *   features/{run-monitor,imports,people,accounts/import,find-email,find-phone}
 *   feature-flags
 * Radix primitives are re-implemented with plain React + T.Portal +
 * T.useDismiss; classNames and data-state/data-side/data-highlighted
 * attributes are kept verbatim so the compiled CSS variants apply. */
(() => {
  const T = window.T;
  const {
    useState,
    useEffect,
    useLayoutEffect,
    useRef,
    useCallback,
    useMemo,
    useContext,
    createContext,
    forwardRef,
    Fragment,
  } = React;
  const cn = T.cn;

  /* Icon access is lazy (icons.jsx defines T.Icons before this file runs,
   * but a Proxy keeps us resilient to missing glyphs). */
  const iconCache = new Map();
  const G = new Proxy(
    {},
    {
      get: (_, name) => {
        if (iconCache.has(name)) return iconCache.get(name);
        const render = (props, ref) => {
          const C = (T.Icons || {})[name];
          return C ? React.createElement(C, { ...props, ref }) : null;
        };
        const Comp = forwardRef(render);
        Comp.displayName = `Icon(${String(name)})`;
        iconCache.set(name, Comp);
        return Comp;
      },
    },
  );

  /* ============================== utilities ============================== */

  /* class-variance-authority lite — inlines the variant maps verbatim. */
  function cva(base, config = {}) {
    const {
      variants = {},
      compoundVariants = [],
      defaultVariants = {},
    } = config;
    return (props = {}) => {
      const cls = [base];
      const resolved = {};
      for (const key of Object.keys(variants)) {
        const v =
          props[key] !== undefined && props[key] !== null
            ? props[key]
            : defaultVariants[key];
        resolved[key] = v;
        if (v != null && variants[key][v]) cls.push(variants[key][v]);
      }
      for (const cv of compoundVariants) {
        const { class: c1, className: c2, ...conds } = cv;
        const ok = Object.entries(conds).every(([k, val]) =>
          Array.isArray(val) ? val.includes(resolved[k]) : resolved[k] === val,
        );
        if (ok) cls.push(c1 || c2);
      }
      if (props.className) cls.push(props.className);
      return cls.filter(Boolean).join(' ');
    };
  }

  const composeRefs = (...refs) => (node) => {
    for (const r of refs) {
      if (!r) continue;
      if (typeof r === 'function') r(node);
      else r.current = node;
    }
  };

  /* Radix Slot shim: merge props/className/handlers onto the single child. */
  const Slot = forwardRef(function Slot({ children, ...props }, ref) {
    const child = React.Children.only(children);
    const merged = { ...props };
    for (const k of Object.keys(child.props)) {
      if (
        /^on[A-Z]/.test(k) &&
        typeof props[k] === 'function' &&
        typeof child.props[k] === 'function'
      ) {
        const slotHandler = props[k];
        const childHandler = child.props[k];
        merged[k] = (...args) => {
          childHandler(...args);
          slotHandler(...args);
        };
      } else {
        merged[k] = child.props[k];
      }
    }
    merged.className = cn(props.className, child.props.className);
    merged.style = { ...props.style, ...child.props.style };
    merged.ref = composeRefs(ref, child.ref);
    return React.cloneElement(child, merged);
  });

  /* Fixed-position layer under an anchor (getBoundingClientRect), with a
   * simple top/bottom flip + viewport clamp. Sets the --radix-* CSS vars the
   * compiled classNames read (content-available-height, trigger-width,
   * transform-origin). */
  function useLayerPosition(open, anchorRef, contentRef, opts = {}) {
    const { side = 'bottom', align = 'center', sideOffset = 4 } = opts;
    const [pos, setPos] = useState(null);
    useLayoutEffect(() => {
      if (!open) {
        setPos(null);
        return;
      }
      const place = () => {
        const anchor = anchorRef.current;
        const content = contentRef.current;
        if (!anchor || !content) return;
        const a = anchor.getBoundingClientRect();
        const cw = content.offsetWidth;
        const ch = content.offsetHeight;
        const vw = window.innerWidth;
        const vh = window.innerHeight;
        let s = side;
        if (s === 'bottom' && a.bottom + sideOffset + ch > vh - 8 && a.top - sideOffset - ch > 8) s = 'top';
        else if (s === 'top' && a.top - sideOffset - ch < 8 && a.bottom + sideOffset + ch < vh - 8) s = 'bottom';
        else if (s === 'right' && a.right + sideOffset + cw > vw - 8 && a.left - sideOffset - cw > 8) s = 'left';
        else if (s === 'left' && a.left - sideOffset - cw < 8 && a.right + sideOffset + cw < vw - 8) s = 'right';
        let top = 0;
        let left = 0;
        if (s === 'bottom' || s === 'top') {
          top = s === 'bottom' ? a.bottom + sideOffset : a.top - sideOffset - ch;
          if (align === 'start') left = a.left;
          else if (align === 'end') left = a.right - cw;
          else left = a.left + a.width / 2 - cw / 2;
        } else {
          left = s === 'right' ? a.right + sideOffset : a.left - sideOffset - cw;
          if (align === 'start') top = a.top;
          else if (align === 'end') top = a.bottom - ch;
          else top = a.top + a.height / 2 - ch / 2;
        }
        left = Math.max(8, Math.min(left, vw - cw - 8));
        top = Math.max(8, Math.min(top, vh - ch - 8));
        setPos((prev) =>
          prev && prev.top === top && prev.left === left && prev.side === s
            ? prev
            : {
                top,
                left,
                side: s,
                anchorWidth: a.width,
                availableHeight: Math.max(120, vh - (s === 'bottom' ? a.bottom + sideOffset : 0) - 16),
              },
        );
      };
      place();
      const raf = requestAnimationFrame(place);
      window.addEventListener('resize', place);
      window.addEventListener('scroll', place, true);
      return () => {
        cancelAnimationFrame(raf);
        window.removeEventListener('resize', place);
        window.removeEventListener('scroll', place, true);
      };
    }, [open, side, align, sideOffset]);
    return pos;
  }

  const layerStyle = (pos, varPrefix) => {
    const style = {
      position: 'fixed',
      top: pos ? pos.top : 0,
      left: pos ? pos.left : 0,
      visibility: pos ? undefined : 'hidden',
    };
    if (varPrefix && pos) {
      style[`--radix-${varPrefix}-content-available-height`] = `${pos.availableHeight}px`;
      style[`--radix-${varPrefix}-content-transform-origin`] =
        pos.side === 'top' ? 'center bottom' : 'center top';
      if (varPrefix === 'select') {
        style['--radix-select-trigger-width'] = `${pos.anchorWidth}px`;
        style['--radix-select-trigger-height'] = 'var(--radix-select-content-available-height)';
      }
    }
    return style;
  };

  /* T.useDismiss variant for anchored layers: ignores mousedowns inside ANY
   * of the given refs (content + trigger/anchor), so the trigger's own click
   * can toggle the layer closed instead of dismiss-then-reopen. */
  function useDismissLayers(open, onClose, refs) {
    useEffect(() => {
      if (!open) return;
      const onKey = (e) => {
        if (e.key === 'Escape') onClose();
      };
      const onDown = (e) => {
        for (const r of refs) {
          if (r && r.current && r.current.contains(e.target)) return;
        }
        onClose();
      };
      document.addEventListener('keydown', onKey);
      document.addEventListener('mousedown', onDown);
      return () => {
        document.removeEventListener('keydown', onKey);
        document.removeEventListener('mousedown', onDown);
      };
    }, [open, onClose]);
  }

  /* Body scroll lock shared by modal layers. */
  let scrollLocks = 0;
  function useBodyScrollLock(active) {
    useEffect(() => {
      if (!active) return;
      scrollLocks += 1;
      const prev = document.body.style.overflow;
      document.body.style.overflow = 'hidden';
      return () => {
        scrollLocks -= 1;
        if (scrollLocks === 0) document.body.style.overflow = prev;
      };
    }, [active]);
  }

  /* ============ ported from components/ui/button.tsx ============ */
  const buttonVariants = cva(
    "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all cursor-pointer disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
    {
      variants: {
        variant: {
          default:
            'rounded-full bg-accent-brand text-white shadow-sm hover:brightness-[1.07] border-none',
          destructive:
            'rounded-full bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60',
          secondary:
            'rounded-full border border-border-strong bg-transparent text-accent-text hover:border-accent-line hover:bg-accent-soft',
          tertiary:
            'rounded-full border border-border-strong bg-transparent font-normal text-text-secondary hover:bg-surface-well hover:text-text-primary',
          'destructive-outline':
            'rounded-full border border-destructive/30 bg-transparent font-normal text-destructive hover:border-destructive/55 hover:bg-destructive/10 hover:text-destructive',
          'destructive-quiet':
            'rounded-full border border-transparent bg-transparent font-normal text-text-muted hover:border-destructive/55 hover:bg-destructive/10 hover:text-destructive',
          quiet:
            'rounded-full border border-transparent bg-transparent font-normal text-text-muted hover:border-border-strong hover:bg-surface-well hover:text-text-primary',
        },
        size: {
          default: "h-9 px-4 py-2 has-[>svg]:px-3 [&_svg:not([class*='size-'])]:size-4",
          sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5 [&_svg:not([class*='size-'])]:size-3.5",
          xs: "h-7 rounded-md gap-1 px-2.5 text-xs [&_svg:not([class*='size-'])]:size-3.5",
          lg: "h-10 rounded-md px-6 has-[>svg]:px-4 [&_svg:not([class*='size-'])]:size-5",
          icon: "size-9 [&_svg:not([class*='size-'])]:size-4",
          'icon-sm': "size-8 [&_svg:not([class*='size-'])]:size-3.5",
        },
      },
      compoundVariants: [
        {
          variant: [
            'default',
            'secondary',
            'tertiary',
            'destructive',
            'destructive-outline',
            'destructive-quiet',
            'quiet',
          ],
          size: ['xs', 'sm', 'lg'],
          class: 'rounded-full',
        },
      ],
      defaultVariants: { variant: 'default', size: 'default' },
    },
  );

  const Button = forwardRef(function Button(
    {
      className,
      variant,
      size,
      asChild = false,
      loading = false,
      loadingIconPosition = 'start',
      disabled,
      children,
      ...props
    },
    ref,
  ) {
    const Comp = asChild ? Slot : 'button';
    const spinner = <G.Loader2 className="animate-spin" aria-hidden />;
    return (
      <Comp
        ref={ref}
        data-slot="button"
        data-loading={loading || undefined}
        className={cn(buttonVariants({ variant, size, className }))}
        disabled={loading || disabled}
        {...props}
      >
        {loading && !asChild ? (
          loadingIconPosition === 'end' ? (
            <>
              {children}
              {spinner}
            </>
          ) : (
            <>
              {spinner}
              {children}
            </>
          )
        ) : (
          children
        )}
      </Comp>
    );
  });

  /* ============ ported from components/ui/badge.tsx ============ */
  const badgeVariants = cva(
    'inline-flex items-center justify-center rounded-md border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden',
    {
      variants: {
        variant: {
          default:
            'border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90',
          secondary:
            'border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90',
          destructive:
            'border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60',
          outline:
            'text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground',
          count:
            'min-w-5 rounded-full border-transparent bg-accent-soft px-2 font-semibold tabular-nums normal-case tracking-normal text-accent-text',
        },
      },
      defaultVariants: { variant: 'default' },
    },
  );

  const TONE_CLASS = {
    indigo: 'border-indigo-500/30 bg-indigo-500/10 text-indigo-400',
    cyan: 'border-cyan-500/30 bg-cyan-500/10 text-cyan-400',
    amber: 'border-amber-500/30 bg-amber-500/10 text-amber-400',
    rose: 'border-rose-500/30 bg-rose-500/10 text-rose-400',
    emerald: 'border-emerald-500/30 bg-emerald-500/10 text-emerald-400',
    neutral: 'border-border-subtle bg-surface-well text-text-secondary',
  };

  function Badge({ className, variant, tone, asChild = false, ...props }) {
    const Comp = asChild ? Slot : 'span';
    return (
      <Comp
        data-slot="badge"
        className={cn(
          badgeVariants({ variant: tone ? undefined : variant }),
          tone && TONE_CLASS[tone],
          className,
        )}
        {...props}
      />
    );
  }

  /* ============ ported from components/ui/input.tsx ============ */
  const searchFieldClassName = 'h-8 text-body-sm md:text-body-sm w-[210px]';

  const Input = forwardRef(function Input({ className, type, icon, ...props }, ref) {
    const field = (
      <input
        ref={ref}
        type={type}
        data-slot="input"
        className={cn(
          'file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground bg-app-raised dark:bg-surface-well border-input flex h-9 w-full min-w-0 rounded-full border px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm',
          'autofill:shadow-[inset_0_0_0_1000px_var(--color-app-raised)] dark:autofill:shadow-[inset_0_0_0_1000px_var(--color-surface-well)] autofill:[--tw-text-opacity:1] autofill:[-webkit-text-fill-color:var(--text-primary)]',
          'focus-visible:border-accent-line focus-visible:ring-accent-soft focus-visible:ring-[3px]',
          'aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive',
          icon && 'pl-9',
          className,
        )}
        {...props}
      />
    );
    if (!icon) return field;
    return (
      <div className="relative">
        <span
          aria-hidden
          className="pointer-events-none absolute top-1/2 left-3 -translate-y-1/2 text-text-muted [&>svg]:size-3.5"
        >
          {icon}
        </span>
        {field}
      </div>
    );
  });

  /* ============ ported from components/ui/checkbox.tsx (Radix shim) ============ */
  const Checkbox = forwardRef(function Checkbox(
    { className, checked, defaultChecked = false, onCheckedChange, disabled, ...props },
    ref,
  ) {
    const [uncontrolled, setUncontrolled] = useState(defaultChecked);
    const value = checked !== undefined ? checked : uncontrolled;
    const state =
      value === 'indeterminate' ? 'indeterminate' : value ? 'checked' : 'unchecked';
    return (
      <button
        ref={ref}
        type="button"
        role="checkbox"
        aria-checked={value === 'indeterminate' ? 'mixed' : !!value}
        disabled={disabled}
        data-state={state}
        data-disabled={disabled ? '' : undefined}
        data-slot="checkbox"
        onClick={(e) => {
          e.preventDefault();
          const next = value === 'indeterminate' ? true : !value;
          if (checked === undefined) setUncontrolled(next);
          if (onCheckedChange) onCheckedChange(next);
        }}
        className={cn(
          'peer border-border-strong dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary data-[state=indeterminate]:bg-primary data-[state=indeterminate]:text-primary-foreground dark:data-[state=indeterminate]:bg-primary data-[state=indeterminate]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive relative size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50',
          className,
        )}
        {...props}
      >
        {(state === 'checked' || state === 'indeterminate') && (
          <span
            data-slot="checkbox-indicator"
            data-state={state}
            className="absolute inset-0 flex items-center justify-center text-current transition-none"
          >
            {state === 'indeterminate' ? <G.Minus size={12} /> : <G.CheckIcon size={14} />}
          </span>
        )}
      </button>
    );
  });

  /* ============ skeleton / card / separator / progress ============ */
  function Skeleton({ className, ...props }) {
    return (
      <div
        data-slot="skeleton"
        className={cn('bg-accent animate-pulse rounded-md', className)}
        {...props}
      />
    );
  }

  const CARD_SURFACE_CLASS = {
    card: 'bg-card',
    well: 'bg-surface-well',
    row: 'bg-surface-row',
    shell: 'bg-surface-shell',
  };

  function Card({ className, surface = 'card', ...props }) {
    return (
      <div
        data-slot="card"
        className={cn(
          CARD_SURFACE_CLASS[surface],
          'text-card-foreground shadow-card flex flex-col gap-6 rounded-xl border py-6',
          className,
        )}
        {...props}
      />
    );
  }
  function CardHeader({ className, ...props }) {
    return (
      <div
        data-slot="card-header"
        className={cn(
          '@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6',
          className,
        )}
        {...props}
      />
    );
  }
  function CardTitle({ className, ...props }) {
    return <div data-slot="card-title" className={cn('text-card-title', className)} {...props} />;
  }
  function CardDescription({ className, ...props }) {
    return (
      <div
        data-slot="card-description"
        className={cn('text-body text-muted-foreground', className)}
        {...props}
      />
    );
  }
  function CardAction({ className, ...props }) {
    return (
      <div
        data-slot="card-action"
        className={cn('col-start-2 row-span-2 row-start-1 self-start justify-self-end', className)}
        {...props}
      />
    );
  }
  function CardContent({ className, ...props }) {
    return <div data-slot="card-content" className={cn('px-6', className)} {...props} />;
  }
  function CardFooter({ className, ...props }) {
    return (
      <div
        data-slot="card-footer"
        className={cn('flex items-center px-6 [.border-t]:pt-6', className)}
        {...props}
      />
    );
  }

  function Separator({ className, orientation = 'horizontal', decorative = true, ...props }) {
    return (
      <div
        data-slot="separator"
        role={decorative ? 'none' : 'separator'}
        aria-orientation={decorative ? undefined : orientation}
        data-orientation={orientation}
        className={cn(
          'bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:w-px',
          className,
        )}
        {...props}
      />
    );
  }

  const Progress = forwardRef(function Progress(
    { className, value = 0, max = 100, ...props },
    ref,
  ) {
    const percentage = Math.min(Math.max((value / max) * 100, 0), 100);
    return (
      <div
        ref={ref}
        role="progressbar"
        aria-valuemin={0}
        aria-valuemax={max}
        aria-valuenow={value}
        className={cn('bg-secondary relative h-2 w-full overflow-hidden rounded-full', className)}
        {...props}
      >
        <div
          className="bg-primary h-full transition-all duration-300 ease-in-out"
          style={{ width: `${percentage}%` }}
        />
      </div>
    );
  });

  /* ============ avatar suite (components/ui/avatar.tsx, Radix shim) ============ */
  const AvatarStatusContext = createContext(null);

  function Avatar({ className, ...props }) {
    const [status, setStatus] = useState('idle');
    const ctx = useMemo(() => ({ status, setStatus }), [status]);
    return (
      <AvatarStatusContext.Provider value={ctx}>
        <span
          data-slot="avatar"
          className={cn('relative flex size-8 shrink-0 overflow-hidden rounded-full', className)}
          {...props}
        />
      </AvatarStatusContext.Provider>
    );
  }

  function AvatarImage({ className, src, onLoadingStatusChange, alt = '', ...props }) {
    const ctx = useContext(AvatarStatusContext);
    const [status, setStatus] = useState('idle');
    useEffect(() => {
      if (!src) {
        setStatus('error');
        return;
      }
      let cancelled = false;
      setStatus('loading');
      const img = new window.Image();
      img.onload = () => !cancelled && setStatus('loaded');
      img.onerror = () => !cancelled && setStatus('error');
      img.src = src;
      return () => {
        cancelled = true;
      };
    }, [src]);
    useEffect(() => {
      if (onLoadingStatusChange && status !== 'idle') onLoadingStatusChange(status);
      if (ctx) ctx.setStatus(status);
    }, [status]);
    if (status !== 'loaded') return null;
    return (
      <img
        data-slot="avatar-image"
        src={src}
        alt={alt}
        className={cn('aspect-square size-full', className)}
        {...props}
      />
    );
  }

  function AvatarFallback({ className, ...props }) {
    const ctx = useContext(AvatarStatusContext);
    if (ctx && ctx.status === 'loaded') return null;
    return (
      <span
        data-slot="avatar-fallback"
        className={cn('bg-muted flex size-full items-center justify-center rounded-full', className)}
        {...props}
      />
    );
  }

  /* utils/profile-image.ts */
  const isLinkedInSilhouette = (url) => !!url && url.includes('static.licdn.com');

  function StableAvatar({
    src,
    alt,
    fallback,
    personId,
    placeholderBaseUrl,
    className,
    fallbackClassName,
  }) {
    const [imgError, setImgError] = useState(false);
    const validSrc = src && !isLinkedInSilhouette(src) ? src : null;
    const useImage = validSrc && !imgError;
    const showPlaceholder = !useImage && !!personId;
    if (showPlaceholder) {
      return (
        <PlaceholderAvatar
          personId={personId}
          baseUrl={placeholderBaseUrl}
          className={className}
          alt={alt}
        />
      );
    }
    return (
      <div className={cn('relative flex size-8 shrink-0 overflow-hidden rounded-full', className)}>
        <div className={cn('bg-muted flex size-full items-center justify-center rounded-full', fallbackClassName)}>
          {fallback}
        </div>
        {validSrc && !imgError && (
          <img
            src={validSrc}
            alt={alt}
            loading="lazy"
            decoding="async"
            onError={() => setImgError(true)}
            className="absolute inset-0 size-full object-cover"
          />
        )}
      </div>
    );
  }

  /* ============ lib/brandImage.ts (proxy-less port: public favicon service) ============ */
  function brandImageSrc(domainOrUrl) {
    const domain = String(domainOrUrl || '')
      .replace(/^https?:\/\//, '')
      .replace(/^www\./, '')
      .split('/')[0];
    return `https://www.google.com/s2/favicons?domain=${encodeURIComponent(domain)}&sz=64`;
  }
  const headshotSrc = (path) => (path ? path : undefined);
  const isUploadedLogo = (logoUrl) => !!logoUrl && logoUrl.includes('/storage/');
  function logoCandidates(logoUrl, domain) {
    const proxy = domain ? brandImageSrc(domain) : null;
    const stored = logoUrl || null;
    const ordered = isUploadedLogo(stored) ? [stored, proxy] : [proxy, stored];
    return ordered.filter(Boolean);
  }
  const tenantLogoSrc = (logoUrl, domain) => logoCandidates(logoUrl, domain)[0];

  /* ============ components/ui/logo-avatar.tsx ============ */
  const LOGO_SIZE_CLASSES = {
    xs: 'size-6 rounded-xs',
    row: 'size-[22px] rounded-[6px]',
    sm: 'h-7 w-7 rounded-sm',
    md: 'h-8 w-8 rounded-sm',
    lg: 'h-16 w-16 rounded-sm',
  };
  const LOGO_FALLBACK_TEXT_SIZES = {
    xs: 'text-2xs',
    row: 'text-2xs',
    sm: 'text-xs',
    md: 'text-xs',
    lg: 'text-lg',
  };

  function LogoAvatar({
    src,
    domain,
    alt,
    fallbackText,
    size = 'md',
    fallbackClassName = 'bg-[var(--color-avatar-fallback)] text-white',
    className,
  }) {
    const candidates = logoCandidates(src, domain);
    const [failedCount, setFailedCount] = useState(0);
    useEffect(() => setFailedCount(0), [domain, src]);
    const imageSrc = candidates[failedCount];
    return (
      <Avatar className={cn(LOGO_SIZE_CLASSES[size], className)}>
        {imageSrc && (
          <AvatarImage
            src={imageSrc}
            alt={alt}
            className="bg-white"
            onLoadingStatusChange={(status) => {
              if (status === 'error') setFailedCount((c) => c + 1);
            }}
          />
        )}
        <AvatarFallback
          className={cn(
            LOGO_FALLBACK_TEXT_SIZES[size],
            'font-heading font-bold rounded-[inherit]',
            fallbackClassName,
          )}
        >
          {fallbackText}
        </AvatarFallback>
      </Avatar>
    );
  }

  /* ============ components/CompanyLogo.tsx ============ */
  function CompanyLogo({
    domain,
    logoUrl,
    name,
    className,
    fallbackClassName,
    fallbackText,
    fallbackIcon,
  }) {
    const candidates = logoCandidates(logoUrl, domain);
    const [failedCount, setFailedCount] = useState(0);
    useEffect(() => setFailedCount(0), [domain, logoUrl]);
    const src = candidates[failedCount];
    if (src) {
      return (
        <img
          src={src}
          alt={name}
          loading="lazy"
          decoding="async"
          onError={() => setFailedCount((c) => c + 1)}
          className={className}
        />
      );
    }
    return (
      <div className={fallbackClassName}>
        {fallbackIcon ?? fallbackText ?? name.charAt(0).toUpperCase()}
      </div>
    );
  }

  /* ============ components/placeholder-avatar ============ */
  function fnv1a(str) {
    let h = 0x811c9dc5;
    for (let i = 0; i < str.length; i++) {
      h ^= str.charCodeAt(i);
      h = Math.imul(h, 0x01000193);
    }
    return h >>> 0;
  }
  const PLACEHOLDER_AVATAR_COUNT = 50;
  function placeholderAvatarPath(personId) {
    const index = fnv1a(personId) % PLACEHOLDER_AVATAR_COUNT;
    const nn = String(index + 1).padStart(2, '0');
    return `/images/placeholder/${nn}.png`;
  }
  function placeholderAvatarUrl(personId, baseUrl) {
    const trimmed = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;
    return `${trimmed}${placeholderAvatarPath(personId)}`;
  }

  /* The skeleton ships no /images/placeholder PNGs; on image error we fall
   * back to a deterministic gradient (same hash → same look per person). */
  function PlaceholderAvatar({ personId, baseUrl, className, alt = '' }) {
    const [err, setErr] = useState(false);
    const src = baseUrl
      ? placeholderAvatarUrl(personId, baseUrl)
      : placeholderAvatarPath(personId);
    const hue = fnv1a(personId) % 360;
    return (
      <div className={cn('relative size-8 shrink-0 overflow-hidden rounded-full', className)}>
        {err ? (
          <div
            role="img"
            aria-label={alt}
            className="size-full"
            style={{
              background: `linear-gradient(135deg, hsl(${hue} 65% 55%), hsl(${(hue + 45) % 360} 65% 42%))`,
            }}
          />
        ) : (
          <img
            src={src}
            alt={alt}
            loading="lazy"
            decoding="async"
            onError={() => setErr(true)}
            className="size-full object-cover"
          />
        )}
      </div>
    );
  }

  /* ============ components/user-avatar-stack ============ */
  const TRIGGER_RESET =
    'appearance-none border-0 bg-transparent p-0 outline-none rounded-full transition-[box-shadow] focus-visible:ring-ring/50 focus-visible:ring-[3px]';
  const AVATAR_FILL_TONES = [
    'bg-[var(--avatar-fallback-0)]',
    'bg-[var(--avatar-fallback-1)]',
    'bg-[var(--avatar-fallback-2)]',
  ];
  const fillFor = (index) => AVATAR_FILL_TONES[Math.min(index, AVATAR_FILL_TONES.length - 1)];
  const STACK_SIZE_CLASSES = {
    xs: 'h-5 w-5 text-2xs',
    sm: 'h-6 w-6 text-2xs',
    md: 'h-8 w-8 text-xs',
  };

  function getInitials(s) {
    return s
      .split(/\s+|@/)
      .filter(Boolean)
      .slice(0, 2)
      .map((w) => (w[0] ? w[0].toUpperCase() : ''))
      .join('');
  }

  /* Ported from packages/shared/src/components/app-sidebar/sidebar-user-menu.tsx */
  function avatarInitials(value) {
    const base = value.split('@')[0].split('+')[0];
    const words = base.split(/[\s._-]+/).filter(Boolean);
    if (words.length >= 2) return (words[0][0] + words[1][0]).toUpperCase();
    return base.slice(0, 2).toUpperCase() || '?';
  }

  function UserAvatar({ name, avatarUrl, size = 'sm', index = 0, className }) {
    return (
      <Avatar className={cn(STACK_SIZE_CLASSES[size], 'shrink-0 font-bold', className)}>
        {avatarUrl && <AvatarImage src={avatarUrl} alt={name} />}
        <AvatarFallback
          className={cn('text-white [font-family:var(--font-heading)]', fillFor(index))}
        >
          {getInitials(name)}
        </AvatarFallback>
      </Avatar>
    );
  }

  function UnassignedUserAvatar({ size = 'sm', className }) {
    return (
      <Avatar
        title="Unassigned"
        aria-label="Unassigned"
        role="img"
        className={cn(
          STACK_SIZE_CLASSES[size],
          'shrink-0 border-[1.5px] border-dashed border-border-strong bg-transparent',
          className,
        )}
      />
    );
  }

  function UserAvatarStack({ users, maxVisible = 2, size = 'sm', unassigned = false, className }) {
    if (users.length === 0) {
      if (!unassigned) return null;
      return <UnassignedUserAvatar size={size} className={className} />;
    }
    const visible = users.slice(0, maxVisible);
    const overflow = users.length - visible.length;
    const overflowUsers = users.slice(maxVisible);
    return (
      <div className={cn('flex items-center -space-x-1', className)}>
        {visible.map((u, index) => {
          const label = u.name ?? u.email;
          return (
            <Tooltip key={u.id}>
              <TooltipTrigger asChild>
                <button type="button" aria-label={label} className={cn(TRIGGER_RESET, 'relative')}>
                  <UserAvatar
                    name={label}
                    avatarUrl={u.avatarUrl}
                    size={size}
                    index={index}
                    className="ring-surface-card ring-2"
                  />
                </button>
              </TooltipTrigger>
              <TooltipContent>{label}</TooltipContent>
            </Tooltip>
          );
        })}
        {overflow > 0 && (
          <Tooltip>
            <TooltipTrigger asChild>
              <button
                type="button"
                aria-label={`${overflow} more: ${overflowUsers.map((u) => u.name ?? u.email).join(', ')}`}
                className={cn(TRIGGER_RESET, 'relative ml-1')}
              >
                <span
                  className={cn(
                    STACK_SIZE_CLASSES[size],
                    'bg-muted text-muted-foreground ring-background inline-flex items-center justify-center rounded-full font-medium ring-2',
                  )}
                >
                  +{overflow}
                </span>
              </button>
            </TooltipTrigger>
            <TooltipContent>
              {overflowUsers.map((u) => u.name ?? u.email).join(', ')}
            </TooltipContent>
          </Tooltip>
        )}
      </div>
    );
  }

  /* ============ apps/web/src/components/PersonAvatar.tsx ============ */
  const personAvatarLoadedSrcs = new Set();
  const personAvatarInitials = (name) =>
    name
      .split(' ')
      .filter(Boolean)
      .map((n) => (n[0] ? n[0].toUpperCase() : ''))
      .join('')
      .slice(0, 2);

  function PersonAvatar({ src, name, personId, className, onClick, contacted = false }) {
    const [imgError, setImgError] = useState(false);
    const [displaySrc, setDisplaySrc] = useState(src ?? null);
    const [settled, setSettled] = useState(() => (src ? personAvatarLoadedSrcs.has(src) : false));
    const displaySrcRef = useRef(displaySrc);
    displaySrcRef.current = displaySrc;

    useEffect(() => {
      if (!src) {
        setDisplaySrc(null);
        setImgError(false);
        return;
      }
      if (src === displaySrcRef.current) return;
      if (personAvatarLoadedSrcs.has(src)) {
        setDisplaySrc(src);
        setSettled(true);
        setImgError(false);
        return;
      }
      let cancelled = false;
      const pre = new window.Image();
      pre.onload = () => {
        if (cancelled) return;
        personAvatarLoadedSrcs.add(src);
        setSettled(true);
        setImgError(false);
        setDisplaySrc(src);
      };
      pre.onerror = () => {
        if (cancelled) return;
        setImgError(true);
        setDisplaySrc(src);
      };
      pre.src = src;
      return () => {
        cancelled = true;
      };
    }, [src]);

    const useImage = !!displaySrc && !imgError;

    const circle =
      !useImage && personId ? (
        <PlaceholderAvatar personId={personId} className="size-full" alt={name} />
      ) : (
        <div className="relative flex size-full items-center justify-center overflow-hidden rounded-full">
          {!(useImage && settled) && (
            <div className="flex size-full items-center justify-center rounded-full bg-gradient-to-br from-indigo-400 to-purple-500 text-xs font-bold text-white">
              {personAvatarInitials(name)}
            </div>
          )}
          {useImage && displaySrc && (
            <img
              src={displaySrc}
              alt={name}
              onLoad={() => {
                personAvatarLoadedSrcs.add(displaySrc);
                setSettled(true);
              }}
              onError={() => setImgError(true)}
              className="absolute inset-0 size-full object-cover"
            />
          )}
        </div>
      );

    return (
      <div className={cn('relative flex shrink-0 rounded-full', className)} onClick={onClick}>
        {circle}
        {contacted && (
          <span
            data-testid="contacted-avatar-check"
            aria-label="Contacted"
            className="absolute -bottom-0.5 -right-0.5 flex size-[40%] min-h-3 min-w-3 items-center justify-center rounded-full bg-emerald-500 ring-2 ring-surface-card"
          >
            <G.Check className="size-[60%] text-white" strokeWidth={3} />
          </span>
        )}
      </div>
    );
  }

  Object.assign(T, {
    UI: {
      avatarInitials,
      // populated below in a second pass; primitives registered first so
      // later files can extend.
    },
  });

  Object.assign(T.UI, {
    Slot,
    cva,
    Button,
    buttonVariants,
    Badge,
    badgeVariants,
    Input,
    searchFieldClassName,
    Checkbox,
    Skeleton,
    Card,
    CardHeader,
    CardFooter,
    CardTitle,
    CardAction,
    CardDescription,
    CardContent,
    Separator,
    Progress,
    Avatar,
    AvatarImage,
    AvatarFallback,
    StableAvatar,
    isLinkedInSilhouette,
    brandImageSrc,
    headshotSrc,
    isUploadedLogo,
    logoCandidates,
    tenantLogoSrc,
    LogoAvatar,
    CompanyLogo,
    fnv1a,
    PLACEHOLDER_AVATAR_COUNT,
    placeholderAvatarPath,
    placeholderAvatarUrl,
    PlaceholderAvatar,
    getInitials,
    UserAvatar,
    UnassignedUserAvatar,
    UserAvatarStack,
    PersonAvatar,
  });

  /* ======================================================================
   * Overlay primitives (Radix behavior shims)
   * ==================================================================== */

  /* ---------- dialog (components/ui/dialog.tsx) ---------- */
  const DialogContext = createContext(null);

  function useControllableOpen({ open, defaultOpen = false, onOpenChange }) {
    const [uncontrolled, setUncontrolled] = useState(defaultOpen);
    const isOpen = open !== undefined ? open : uncontrolled;
    const setOpen = useCallback(
      (next) => {
        if (open === undefined) setUncontrolled(next);
        if (onOpenChange) onOpenChange(next);
      },
      [open, onOpenChange],
    );
    return [isOpen, setOpen];
  }

  function Dialog({ open, defaultOpen, onOpenChange, children }) {
    const [isOpen, setOpen] = useControllableOpen({ open, defaultOpen, onOpenChange });
    const ctx = useMemo(() => ({ open: isOpen, setOpen, alert: false }), [isOpen, setOpen]);
    return <DialogContext.Provider value={ctx}>{children}</DialogContext.Provider>;
  }

  function DialogTrigger({ asChild, ...props }) {
    const ctx = useContext(DialogContext);
    const Comp = asChild ? Slot : 'button';
    return (
      <Comp
        data-slot="dialog-trigger"
        onClick={() => ctx.setOpen(true)}
        {...(asChild ? {} : { type: 'button' })}
        {...props}
      />
    );
  }

  function DialogPortal({ children }) {
    return <T.Portal>{children}</T.Portal>;
  }

  function DialogClose({ asChild, ...props }) {
    const ctx = useContext(DialogContext);
    const Comp = asChild ? Slot : 'button';
    return (
      <Comp
        data-slot="dialog-close"
        onClick={() => ctx.setOpen(false)}
        {...(asChild ? {} : { type: 'button' })}
        {...props}
      />
    );
  }

  function DialogOverlay({ className, ...props }) {
    return (
      <div
        data-slot="dialog-overlay"
        data-state="open"
        className={cn(
          'data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50',
          className,
        )}
        {...props}
      />
    );
  }

  const dialogSizeClasses = {
    small: 'sm:max-w-lg',
    medium: 'sm:max-w-3xl',
    large: 'sm:max-w-5xl',
    sm: 'sm:max-w-sm',
    md: 'sm:max-w-md',
    lg: 'sm:max-w-lg',
    xl: 'sm:max-w-xl',
    '2xl': 'sm:max-w-2xl',
    '3xl': 'sm:max-w-3xl',
    '4xl': 'sm:max-w-4xl',
    '5xl': 'sm:max-w-5xl',
    '6xl': 'sm:max-w-6xl',
    full: 'sm:max-w-[90vw]',
  };

  /* Shared modal-content behavior: Esc + overlay dismissal with the Radix
   * cancel hooks (onEscapeKeyDown/onPointerDownOutside/onInteractOutside). */
  function ModalContent({
    ctx,
    baseClassName,
    className,
    children,
    dismissOnOutside,
    onEscapeKeyDown,
    onPointerDownOutside,
    onInteractOutside,
    dataSlot,
    ...props
  }) {
    useBodyScrollLock(ctx.open);
    useEffect(() => {
      if (!ctx.open) return;
      const onKey = (e) => {
        if (e.key !== 'Escape') return;
        if (onEscapeKeyDown) onEscapeKeyDown(e);
        if (!e.defaultPrevented) ctx.setOpen(false);
      };
      document.addEventListener('keydown', onKey);
      return () => document.removeEventListener('keydown', onKey);
    }, [ctx.open, onEscapeKeyDown]);
    if (!ctx.open) return null;
    const handleOverlayPointerDown = (e) => {
      /* The content stops mousedown propagation, so anything reaching this
       * wrapper (the overlay included) is an outside interaction. */
      let prevented = false;
      const fake = { ...e, preventDefault: () => { prevented = true; e.preventDefault(); }, defaultPrevented: false };
      if (onPointerDownOutside) onPointerDownOutside(fake);
      if (onInteractOutside) onInteractOutside(fake);
      if (!prevented && dismissOnOutside) ctx.setOpen(false);
    };
    return (
      <DialogPortal>
        <div className="fixed inset-0 z-50" onMouseDown={handleOverlayPointerDown}>
          <DialogOverlay />
          <div
            role="dialog"
            aria-modal="true"
            data-slot={dataSlot}
            data-state="open"
            className={cn(baseClassName, className)}
            onMouseDown={(e) => e.stopPropagation()}
            {...props}
          >
            {children}
          </div>
        </div>
      </DialogPortal>
    );
  }

  function DialogContent({ className, children, showCloseButton = true, size = 'lg', ...props }) {
    const ctx = useContext(DialogContext);
    return (
      <ModalContent
        ctx={ctx}
        dataSlot="dialog-content"
        dismissOnOutside
        baseClassName={cn(
          'bg-surface-shell data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border border-border-subtle p-6 shadow-lg duration-200',
          dialogSizeClasses[size],
        )}
        className={className}
        {...props}
      >
        {children}
        {showCloseButton && (
          <button
            type="button"
            data-slot="dialog-close"
            onClick={() => ctx.setOpen(false)}
            className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute end-4 top-4 cursor-pointer rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
          >
            <G.XIcon />
            <span className="sr-only">Close</span>
          </button>
        )}
      </ModalContent>
    );
  }

  function DialogHeader({ className, ...props }) {
    return (
      <div
        data-slot="dialog-header"
        className={cn('flex flex-col gap-2 text-center sm:text-start', className)}
        {...props}
      />
    );
  }
  function DialogBody({ className, ...props }) {
    return (
      <div
        data-slot="dialog-body"
        className={cn('flex max-h-[60vh] flex-col gap-4 overflow-y-auto py-4', className)}
        {...props}
      />
    );
  }
  function DialogFooter({ className, ...props }) {
    return (
      <div
        data-slot="dialog-footer"
        className={cn('flex flex-col-reverse gap-2 sm:flex-row sm:justify-end', className)}
        {...props}
      />
    );
  }
  function DialogTitle({ className, asChild, ...props }) {
    const Comp = asChild ? Slot : 'h2';
    return <Comp data-slot="dialog-title" className={cn('text-card-title', className)} {...props} />;
  }
  function DialogDescription({ className, asChild, ...props }) {
    const Comp = asChild ? Slot : 'p';
    return (
      <Comp
        data-slot="dialog-description"
        className={cn('text-text-muted text-sm', className)}
        {...props}
      />
    );
  }

  /* ---------- alert-dialog (components/ui/alert-dialog.tsx) ---------- */
  function AlertDialog({ open, defaultOpen, onOpenChange, children }) {
    const [isOpen, setOpen] = useControllableOpen({ open, defaultOpen, onOpenChange });
    const ctx = useMemo(() => ({ open: isOpen, setOpen, alert: true }), [isOpen, setOpen]);
    return <DialogContext.Provider value={ctx}>{children}</DialogContext.Provider>;
  }
  const AlertDialogTrigger = (props) => <DialogTrigger data-slot="alert-dialog-trigger" {...props} />;
  const AlertDialogPortal = DialogPortal;
  function AlertDialogOverlay({ className, ...props }) {
    return (
      <div
        data-slot="alert-dialog-overlay"
        data-state="open"
        className={cn(
          'data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50',
          className,
        )}
        {...props}
      />
    );
  }
  function AlertDialogContent({ className, children, ...props }) {
    const ctx = useContext(DialogContext);
    return (
      <ModalContent
        ctx={ctx}
        dataSlot="alert-dialog-content"
        dismissOnOutside={false}
        baseClassName="bg-surface-shell data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border border-border-subtle p-6 shadow-lg duration-200 sm:max-w-lg"
        className={className}
        {...props}
      >
        {children}
      </ModalContent>
    );
  }
  function AlertDialogHeader({ className, ...props }) {
    return (
      <div
        data-slot="alert-dialog-header"
        className={cn('flex flex-col gap-2 text-center sm:text-start', className)}
        {...props}
      />
    );
  }
  function AlertDialogFooter({ className, ...props }) {
    return (
      <div
        data-slot="alert-dialog-footer"
        className={cn('flex flex-col-reverse gap-2 sm:flex-row sm:justify-end', className)}
        {...props}
      />
    );
  }
  function AlertDialogTitle({ className, asChild, ...props }) {
    const Comp = asChild ? Slot : 'h2';
    return (
      <Comp data-slot="alert-dialog-title" className={cn('text-card-title', className)} {...props} />
    );
  }
  function AlertDialogDescription({ className, asChild, ...props }) {
    const Comp = asChild ? Slot : 'p';
    return (
      <Comp
        data-slot="alert-dialog-description"
        className={cn('text-text-muted text-sm', className)}
        {...props}
      />
    );
  }
  function AlertDialogAction({ className, onClick, ...props }) {
    const ctx = useContext(DialogContext);
    return (
      <button
        type="button"
        className={cn(buttonVariants(), className)}
        onClick={(e) => {
          if (onClick) onClick(e);
          if (!e.defaultPrevented) ctx.setOpen(false);
        }}
        {...props}
      />
    );
  }
  function AlertDialogCancel({ className, onClick, ...props }) {
    const ctx = useContext(DialogContext);
    return (
      <button
        type="button"
        className={cn(buttonVariants({ variant: 'tertiary' }), className)}
        onClick={(e) => {
          if (onClick) onClick(e);
          if (!e.defaultPrevented) ctx.setOpen(false);
        }}
        {...props}
      />
    );
  }

  /* ---------- confirm-dialog (components/confirm-dialog) ---------- */
  function ConfirmDialog(props) {
    const {
      title,
      desc,
      children,
      className,
      confirmText,
      cancelBtnText,
      destructive,
      isLoading,
      disabled = false,
      handleConfirm,
      ...actions
    } = props;
    return (
      <AlertDialog {...actions}>
        <AlertDialogContent className={cn(className)}>
          <AlertDialogHeader className="text-start">
            <AlertDialogTitle>{title}</AlertDialogTitle>
            <AlertDialogDescription asChild>
              <div>{desc}</div>
            </AlertDialogDescription>
          </AlertDialogHeader>
          {children}
          <AlertDialogFooter>
            <AlertDialogCancel disabled={isLoading}>{cancelBtnText ?? 'Cancel'}</AlertDialogCancel>
            <Button
              variant={destructive ? 'destructive' : 'default'}
              onClick={handleConfirm}
              disabled={disabled || isLoading}
              loading={isLoading}
            >
              {confirmText ?? 'Continue'}
            </Button>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    );
  }

  /* ---------- tooltip (components/ui/tooltip.tsx) ---------- */
  const TooltipCtx = createContext(null);

  function TooltipProvider({ children }) {
    return <>{children}</>;
  }

  function Tooltip({ open, defaultOpen, onOpenChange, children, delayDuration = 0 }) {
    const [isOpen, setOpen] = useControllableOpen({ open, defaultOpen, onOpenChange });
    const triggerRef = useRef(null);
    const timer = useRef(null);
    const show = useCallback(() => {
      clearTimeout(timer.current);
      timer.current = setTimeout(() => setOpen(true), delayDuration);
    }, [delayDuration, setOpen]);
    const hide = useCallback(() => {
      clearTimeout(timer.current);
      setOpen(false);
    }, [setOpen]);
    useEffect(() => () => clearTimeout(timer.current), []);
    const ctx = useMemo(
      () => ({ open: isOpen, show, hide, triggerRef }),
      [isOpen, show, hide],
    );
    return <TooltipCtx.Provider value={ctx}>{children}</TooltipCtx.Provider>;
  }

  const TooltipTrigger = forwardRef(function TooltipTrigger({ asChild, ...props }, ref) {
    const ctx = useContext(TooltipCtx);
    const Comp = asChild ? Slot : 'button';
    return (
      <Comp
        ref={composeRefs(ref, ctx.triggerRef)}
        data-slot="tooltip-trigger"
        onMouseEnter={ctx.show}
        onMouseLeave={ctx.hide}
        onFocus={ctx.show}
        onBlur={ctx.hide}
        {...(asChild ? {} : { type: 'button' })}
        {...props}
      />
    );
  });

  function TooltipContent({
    className,
    side = 'bottom',
    sideOffset = 4,
    collisionPadding = 12,
    showArrow = false,
    children,
    ...props
  }) {
    const ctx = useContext(TooltipCtx);
    const contentRef = useRef(null);
    const pos = useLayerPosition(ctx.open, ctx.triggerRef, contentRef, {
      side,
      align: 'center',
      sideOffset,
    });
    if (!ctx.open) return null;
    const style = layerStyle(pos, 'tooltip');
    return (
      <T.Portal>
        <div
          ref={contentRef}
          data-slot="tooltip-content"
          data-state="delayed-open"
          data-side={pos ? pos.side : side}
          style={style}
          className={cn(
            'bg-surface-card text-text-primary border border-border-subtle shadow-card animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-[10px] px-2.5 py-1.5 text-left text-xs wrap-break-word',
            className,
          )}
          {...props}
        >
          {children}
          {showArrow ? (
            <span className="fill-surface-card z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px] border-r border-b border-border-subtle" />
          ) : null}
        </div>
      </T.Portal>
    );
  }

  /* ---------- popover (components/ui/popover.tsx) ---------- */
  const PopoverCtx = createContext(null);

  function Popover({ open, defaultOpen, onOpenChange, children }) {
    const [isOpen, setOpen] = useControllableOpen({ open, defaultOpen, onOpenChange });
    const triggerRef = useRef(null);
    const anchorRef = useRef(null);
    const contentRef = useRef(null);
    const ctx = useMemo(
      () => ({ open: isOpen, setOpen, triggerRef, anchorRef, contentRef }),
      [isOpen, setOpen],
    );
    return <PopoverCtx.Provider value={ctx}>{children}</PopoverCtx.Provider>;
  }

  const PopoverTrigger = forwardRef(function PopoverTrigger({ asChild, onClick, ...props }, ref) {
    const ctx = useContext(PopoverCtx);
    const Comp = asChild ? Slot : 'button';
    return (
      <Comp
        ref={composeRefs(ref, ctx.triggerRef)}
        data-slot="popover-trigger"
        data-state={ctx.open ? 'open' : 'closed'}
        aria-expanded={ctx.open}
        onClick={(e) => {
          if (onClick) onClick(e);
          if (!e.defaultPrevented) ctx.setOpen(!ctx.open);
        }}
        {...(asChild ? {} : { type: 'button' })}
        {...props}
      />
    );
  });

  const PopoverAnchor = forwardRef(function PopoverAnchor({ asChild, ...props }, ref) {
    const ctx = useContext(PopoverCtx);
    const Comp = asChild ? Slot : 'div';
    return <Comp ref={composeRefs(ref, ctx.anchorRef)} data-slot="popover-anchor" {...props} />;
  });

  function PopoverContent({
    className,
    align = 'center',
    side = 'bottom',
    sideOffset = 4,
    onWheel,
    onTouchMove,
    children,
    ...props
  }) {
    const ctx = useContext(PopoverCtx);
    const contentRef = ctx.contentRef;
    const anchor = ctx.anchorRef.current ? ctx.anchorRef : ctx.triggerRef;
    const pos = useLayerPosition(ctx.open, anchor, contentRef, { side, align, sideOffset });
    useDismissLayers(
      ctx.open,
      useCallback(() => ctx.setOpen(false), [ctx.setOpen]),
      [contentRef, ctx.triggerRef, ctx.anchorRef],
    );
    if (!ctx.open) return null;
    return (
      <T.Portal>
        <div
          ref={contentRef}
          role="dialog"
          data-slot="popover-content"
          data-state="open"
          data-side={pos ? pos.side : side}
          data-align={align}
          style={layerStyle(pos, 'popover')}
          onWheel={(e) => {
            e.stopPropagation();
            if (onWheel) onWheel(e);
          }}
          onTouchMove={(e) => {
            e.stopPropagation();
            if (onTouchMove) onTouchMove(e);
          }}
          className={cn(
            'bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border border-border p-4 shadow-md outline-hidden',
            className,
          )}
          {...props}
        >
          {children}
        </div>
      </T.Portal>
    );
  }

  /* ---------- dropdown-menu (components/ui/dropdown-menu.tsx) ---------- */
  const DropdownCtx = createContext(null);

  function DropdownMenu({ open, defaultOpen, onOpenChange, children }) {
    const [isOpen, setOpen] = useControllableOpen({ open, defaultOpen, onOpenChange });
    const triggerRef = useRef(null);
    const ctx = useMemo(() => ({ open: isOpen, setOpen, triggerRef }), [isOpen, setOpen]);
    return <DropdownCtx.Provider value={ctx}>{children}</DropdownCtx.Provider>;
  }

  const DropdownMenuTrigger = forwardRef(function DropdownMenuTrigger(
    { asChild, className, onClick, ...props },
    ref,
  ) {
    const ctx = useContext(DropdownCtx);
    const Comp = asChild ? Slot : 'button';
    return (
      <Comp
        ref={composeRefs(ref, ctx.triggerRef)}
        data-slot="dropdown-menu-trigger"
        data-state={ctx.open ? 'open' : 'closed'}
        aria-expanded={ctx.open}
        aria-haspopup="menu"
        className={cn('cursor-pointer', className)}
        onClick={(e) => {
          e.stopPropagation();
          if (onClick) onClick(e);
          if (!e.defaultPrevented) ctx.setOpen(!ctx.open);
        }}
        {...(asChild ? {} : { type: 'button' })}
        {...props}
      />
    );
  });

  function DropdownMenuPortal({ children }) {
    return <T.Portal>{children}</T.Portal>;
  }

  function DropdownMenuContent({
    className,
    sideOffset = 4,
    side = 'bottom',
    align = 'start',
    onCloseAutoFocus,
    children,
    ...props
  }) {
    const ctx = useContext(DropdownCtx);
    const contentRef = useRef(null);
    const pos = useLayerPosition(ctx.open, ctx.triggerRef, contentRef, {
      side,
      align,
      sideOffset,
    });
    useDismissLayers(
      ctx.open,
      useCallback(() => ctx.setOpen(false), [ctx.setOpen]),
      [contentRef, ctx.triggerRef],
    );
    if (!ctx.open) return null;
    return (
      <T.Portal>
        <div
          ref={contentRef}
          role="menu"
          data-slot="dropdown-menu-content"
          data-state="open"
          data-side={pos ? pos.side : side}
          data-align={align}
          style={layerStyle(pos, 'dropdown-menu')}
          className={cn(
            'bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border border-border p-1 shadow-md',
            className,
          )}
          {...props}
        >
          {children}
        </div>
      </T.Portal>
    );
  }

  function DropdownMenuGroup(props) {
    return <div role="group" data-slot="dropdown-menu-group" {...props} />;
  }

  /* Shared hover-highlight + select-to-close behavior for menu rows. */
  function useMenuItemProps({ disabled, onSelect, onClick }, ctx) {
    const [highlighted, setHighlighted] = useState(false);
    return {
      'data-highlighted': highlighted ? '' : undefined,
      'data-disabled': disabled ? '' : undefined,
      onMouseEnter: () => setHighlighted(true),
      onMouseLeave: () => setHighlighted(false),
      onClick: (e) => {
        if (disabled) return;
        if (onClick) onClick(e);
        if (onSelect) onSelect(e);
        if (!e.defaultPrevented) ctx.setOpen(false);
      },
    };
  }

  function DropdownMenuItem({
    className,
    inset,
    variant = 'default',
    disabled,
    onSelect,
    onClick,
    ...props
  }) {
    const ctx = useContext(DropdownCtx);
    const itemProps = useMenuItemProps({ disabled, onSelect, onClick }, ctx);
    return (
      <div
        role="menuitem"
        tabIndex={-1}
        data-slot="dropdown-menu-item"
        data-inset={inset}
        data-variant={variant}
        {...itemProps}
        className={cn(
          "data-[highlighted]:bg-accent focus:bg-accent data-[variant=destructive]:text-destructive data-[variant=destructive]:data-[highlighted]:bg-destructive/10 data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:data-[highlighted]:bg-destructive/20 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-pointer items-center gap-2 rounded-sm px-2 py-1.75 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50 data-[inset]:ps-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
          className,
        )}
        {...props}
      />
    );
  }

  function DropdownMenuCheckboxItem({
    className,
    children,
    checked,
    onCheckedChange,
    disabled,
    onSelect,
    ...props
  }) {
    const ctx = useContext(DropdownCtx);
    const itemProps = useMenuItemProps(
      {
        disabled,
        onSelect: (e) => {
          e.preventDefault(); // checkbox items keep the menu open, like Radix's default? (Radix closes; keep close semantics)
          if (onCheckedChange) onCheckedChange(!checked);
          if (onSelect) onSelect(e);
          ctx.setOpen(false);
        },
      },
      ctx,
    );
    return (
      <div
        role="menuitemcheckbox"
        aria-checked={!!checked}
        data-slot="dropdown-menu-checkbox-item"
        data-state={checked ? 'checked' : 'unchecked'}
        {...itemProps}
        className={cn(
          "data-[highlighted]:bg-accent focus:bg-accent relative flex cursor-pointer items-center gap-2 rounded-sm py-1.75 ps-8 pe-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
          className,
        )}
        {...props}
      >
        <span className="pointer-events-none absolute start-2 flex size-3.5 items-center justify-center">
          {checked ? <G.CheckIcon /> : null}
        </span>
        {children}
      </div>
    );
  }

  const DropdownRadioCtx = createContext(null);
  function DropdownMenuRadioGroup({ value, onValueChange, ...props }) {
    const ctx = useMemo(() => ({ value, onValueChange }), [value, onValueChange]);
    return (
      <DropdownRadioCtx.Provider value={ctx}>
        <div role="group" data-slot="dropdown-menu-radio-group" {...props} />
      </DropdownRadioCtx.Provider>
    );
  }
  function DropdownMenuRadioItem({ className, children, value, disabled, onSelect, ...props }) {
    const ctx = useContext(DropdownCtx);
    const radio = useContext(DropdownRadioCtx);
    const checked = radio && radio.value === value;
    const itemProps = useMenuItemProps(
      {
        disabled,
        onSelect: (e) => {
          if (radio && radio.onValueChange) radio.onValueChange(value);
          if (onSelect) onSelect(e);
        },
      },
      ctx,
    );
    return (
      <div
        role="menuitemradio"
        aria-checked={!!checked}
        data-slot="dropdown-menu-radio-item"
        data-state={checked ? 'checked' : 'unchecked'}
        {...itemProps}
        className={cn(
          "data-[highlighted]:bg-accent focus:bg-accent relative flex cursor-pointer items-center gap-2 rounded-sm py-1.75 ps-8 pe-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
          className,
        )}
        {...props}
      >
        <span className="pointer-events-none absolute start-2 flex size-3.5 items-center justify-center">
          {checked ? <G.CircleIcon size={8} className="fill-current" /> : null}
        </span>
        {children}
      </div>
    );
  }

  function DropdownMenuLabel({ className, inset, ...props }) {
    return (
      <div
        data-slot="dropdown-menu-label"
        data-inset={inset}
        className={cn('px-2 py-1.5 text-sm font-medium data-[inset]:ps-8', className)}
        {...props}
      />
    );
  }
  function DropdownMenuSeparator({ className, ...props }) {
    return (
      <div
        role="separator"
        data-slot="dropdown-menu-separator"
        className={cn('bg-border -mx-1 my-1 h-px', className)}
        {...props}
      />
    );
  }
  function DropdownMenuShortcut({ className, ...props }) {
    return (
      <span
        data-slot="dropdown-menu-shortcut"
        className={cn('text-muted-foreground ms-auto text-xs tracking-widest', className)}
        {...props}
      />
    );
  }

  /* Sub-menus: minimal shim — hover opens a right-side layer. */
  const DropdownSubCtx = createContext(null);
  function DropdownMenuSub({ children }) {
    const [open, setOpen] = useState(false);
    const triggerRef = useRef(null);
    const ctx = useMemo(() => ({ open, setOpen, triggerRef }), [open]);
    return <DropdownSubCtx.Provider value={ctx}>{children}</DropdownSubCtx.Provider>;
  }
  function DropdownMenuSubTrigger({ className, inset, children, ...props }) {
    const sub = useContext(DropdownSubCtx);
    return (
      <div
        ref={sub.triggerRef}
        role="menuitem"
        data-slot="dropdown-menu-sub-trigger"
        data-inset={inset}
        data-state={sub.open ? 'open' : 'closed'}
        onMouseEnter={() => sub.setOpen(true)}
        onMouseLeave={() => sub.setOpen(false)}
        className={cn(
          'data-[highlighted]:bg-accent focus:bg-accent data-[state=open]:bg-accent flex cursor-pointer items-center rounded-sm px-2 py-1.75 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50 data-[inset]:ps-8',
          className,
        )}
        {...props}
      >
        {children}
        <G.ChevronRightIcon className="ms-auto" />
      </div>
    );
  }
  function DropdownMenuSubContent({ className, children, ...props }) {
    const sub = useContext(DropdownSubCtx);
    const contentRef = useRef(null);
    const pos = useLayerPosition(sub.open, sub.triggerRef, contentRef, {
      side: 'right',
      align: 'start',
      sideOffset: 2,
    });
    if (!sub.open) return null;
    return (
      <T.Portal>
        <div
          ref={contentRef}
          role="menu"
          data-slot="dropdown-menu-sub-content"
          data-state="open"
          data-side={pos ? pos.side : 'right'}
          style={layerStyle(pos, 'dropdown-menu')}
          onMouseEnter={() => sub.setOpen(true)}
          onMouseLeave={() => sub.setOpen(false)}
          className={cn(
            'bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border border-border p-1 shadow-lg',
            className,
          )}
          {...props}
        >
          {children}
        </div>
      </T.Portal>
    );
  }

  Object.assign(T.UI, {
    Dialog,
    DialogBody,
    DialogClose,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogOverlay,
    DialogPortal,
    DialogTitle,
    DialogTrigger,
    dialogSizeClasses,
    AlertDialog,
    AlertDialogPortal,
    AlertDialogOverlay,
    AlertDialogTrigger,
    AlertDialogContent,
    AlertDialogHeader,
    AlertDialogFooter,
    AlertDialogTitle,
    AlertDialogDescription,
    AlertDialogAction,
    AlertDialogCancel,
    ConfirmDialog,
    Tooltip,
    TooltipTrigger,
    TooltipContent,
    TooltipProvider,
    Popover,
    PopoverTrigger,
    PopoverContent,
    PopoverAnchor,
    DropdownMenu,
    DropdownMenuPortal,
    DropdownMenuTrigger,
    DropdownMenuContent,
    DropdownMenuGroup,
    DropdownMenuLabel,
    DropdownMenuItem,
    DropdownMenuCheckboxItem,
    DropdownMenuRadioGroup,
    DropdownMenuRadioItem,
    DropdownMenuSeparator,
    DropdownMenuShortcut,
    DropdownMenuSub,
    DropdownMenuSubTrigger,
    DropdownMenuSubContent,
  });

  /* ---------- control pill (components/ui/control-pill.ts) ---------- */
  const controlPillShell =
    'flex h-8 w-auto items-center gap-2 rounded-full border bg-surface-card px-3.5 text-xs font-semibold whitespace-nowrap transition-all hover:border-border-strong hover:bg-surface-well';
  const controlPillFormSize = 'h-9 text-sm font-normal';
  const controlPillActive = 'border-border-strong shadow-sm';
  const controlPillIdle = 'border-border-subtle';

  /* ---------- select (components/ui/select.tsx, Radix shim) ---------- */
  const SelectCtx = createContext(null);

  function Select({ open, defaultOpen, onOpenChange, value, defaultValue, onValueChange, disabled, children }) {
    const [isOpen, setOpen] = useControllableOpen({ open, defaultOpen, onOpenChange });
    const [uncontrolledValue, setUncontrolledValue] = useState(defaultValue);
    const selectedValue = value !== undefined ? value : uncontrolledValue;
    const setValue = useCallback(
      (next) => {
        if (value === undefined) setUncontrolledValue(next);
        if (onValueChange) onValueChange(next);
      },
      [value, onValueChange],
    );
    const triggerRef = useRef(null);
    const [labels, setLabels] = useState(() => new Map());
    const registerItem = useCallback((v, label) => {
      setLabels((prev) => {
        if (prev.get(v) === label) return prev;
        const next = new Map(prev);
        next.set(v, label);
        return next;
      });
    }, []);
    const ctx = useMemo(
      () => ({
        open: isOpen,
        setOpen,
        value: selectedValue,
        setValue,
        triggerRef,
        labels,
        registerItem,
        disabled,
      }),
      [isOpen, setOpen, selectedValue, setValue, labels, registerItem, disabled],
    );
    return <SelectCtx.Provider value={ctx}>{children}</SelectCtx.Provider>;
  }

  function SelectGroup(props) {
    return <div role="group" data-slot="select-group" {...props} />;
  }

  function SelectValue({ placeholder, ...props }) {
    const ctx = useContext(SelectCtx);
    const label = ctx.value != null ? (ctx.labels.get(ctx.value) ?? ctx.value) : null;
    return (
      <span data-slot="select-value" {...props}>
        {label != null ? label : placeholder}
      </span>
    );
  }

  const SelectTrigger = forwardRef(function SelectTrigger(
    { className, size = 'default', children, icon, disabled, ...props },
    ref,
  ) {
    const ctx = useContext(SelectCtx);
    return (
      <button
        ref={composeRefs(ref, ctx.triggerRef)}
        type="button"
        role="combobox"
        aria-expanded={ctx.open}
        disabled={disabled || ctx.disabled}
        data-slot="select-trigger"
        data-size={size}
        data-state={ctx.open ? 'open' : 'closed'}
        data-placeholder={ctx.value == null ? '' : undefined}
        onClick={() => ctx.setOpen(!ctx.open)}
        className={cn(
          controlPillShell,
          controlPillIdle,
          "data-[size=default]:h-9 data-[size=default]:text-sm data-[size=default]:font-normal data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive w-fit justify-between py-2 outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
          className,
        )}
        {...props}
      >
        {children}
        {icon !== undefined ? icon : <G.ChevronDownIcon className="opacity-50" />}
      </button>
    );
  });

  function SelectContent({ className, children, position = 'popper', ...props }) {
    const ctx = useContext(SelectCtx);
    const contentRef = useRef(null);
    const pos = useLayerPosition(ctx.open, ctx.triggerRef, contentRef, {
      side: 'bottom',
      align: 'start',
      sideOffset: 0,
    });
    useDismissLayers(
      ctx.open,
      useCallback(() => ctx.setOpen(false), [ctx.setOpen]),
      [contentRef, ctx.triggerRef],
    );
    if (!ctx.open) return null;
    return (
      <T.Portal>
        <div
          ref={contentRef}
          role="listbox"
          data-slot="select-content"
          data-state="open"
          data-side={pos ? pos.side : 'bottom'}
          style={layerStyle(pos, 'select')}
          className={cn(
            'bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border border-border shadow-md',
            position === 'popper' &&
              'data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1',
            className,
          )}
          {...props}
        >
          <div
            className={cn(
              'p-1',
              position === 'popper' && 'w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1',
            )}
          >
            {children}
          </div>
        </div>
      </T.Portal>
    );
  }

  function SelectLabel({ className, ...props }) {
    return (
      <div
        data-slot="select-label"
        className={cn('text-muted-foreground px-2 py-1.5 text-xs', className)}
        {...props}
      />
    );
  }

  function SelectItem({ className, children, value, disabled, textValue, ...props }) {
    const ctx = useContext(SelectCtx);
    const [highlighted, setHighlighted] = useState(false);
    const selected = ctx.value === value;
    const labelRef = useRef(null);
    useEffect(() => {
      const text =
        textValue ??
        (typeof children === 'string'
          ? children
          : labelRef.current
            ? labelRef.current.textContent
            : String(value));
      ctx.registerItem(value, text);
    }, [value, children, textValue]);
    return (
      <div
        role="option"
        aria-selected={selected}
        data-slot="select-item"
        data-state={selected ? 'checked' : 'unchecked'}
        data-highlighted={highlighted ? '' : undefined}
        data-disabled={disabled ? '' : undefined}
        onMouseEnter={() => setHighlighted(true)}
        onMouseLeave={() => setHighlighted(false)}
        onClick={() => {
          if (disabled) return;
          ctx.setValue(value);
          ctx.setOpen(false);
        }}
        className={cn(
          "data-[highlighted]:bg-accent focus:bg-accent [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-pointer items-center gap-2 rounded-sm py-1.75 ps-2 pe-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
          className,
        )}
        {...props}
      >
        <span className="absolute end-2 flex size-3.5 items-center justify-center">
          {selected ? <G.CheckIcon /> : null}
        </span>
        <span ref={labelRef}>{children}</span>
      </div>
    );
  }

  function SelectSeparator({ className, ...props }) {
    return (
      <div
        data-slot="select-separator"
        className={cn('bg-border pointer-events-none -mx-1 my-1 h-px', className)}
        {...props}
      />
    );
  }

  /* ---------- tabs (components/ui/tabs.tsx, Radix shim) ---------- */
  const TabsCtx = createContext(null);

  function Tabs({ className, value, defaultValue, onValueChange, children, ...props }) {
    const [uncontrolled, setUncontrolled] = useState(defaultValue);
    const active = value !== undefined ? value : uncontrolled;
    const setValue = useCallback(
      (next) => {
        if (value === undefined) setUncontrolled(next);
        if (onValueChange) onValueChange(next);
      },
      [value, onValueChange],
    );
    const ctx = useMemo(() => ({ value: active, setValue }), [active, setValue]);
    return (
      <TabsCtx.Provider value={ctx}>
        <div data-slot="tabs" className={cn('flex flex-col gap-2', className)} {...props}>
          {children}
        </div>
      </TabsCtx.Provider>
    );
  }

  function TabsList({ className, ...props }) {
    const classNameStr = typeof className === 'string' ? className : '';
    const hasGrid = classNameStr.includes('grid');
    return (
      <div
        role="tablist"
        data-slot="tabs-list"
        className={cn(
          'bg-muted text-muted-foreground inline-flex h-11 w-fit items-center justify-center rounded-lg border border-border p-1',
          hasGrid && '!grid !w-full',
          className,
        )}
        {...props}
      />
    );
  }

  function TabsTrigger({ className, value, disabled, onClick, ...props }) {
    const ctx = useContext(TabsCtx);
    const active = ctx.value === value;
    return (
      <button
        type="button"
        role="tab"
        aria-selected={active}
        disabled={disabled}
        data-slot="tabs-trigger"
        data-state={active ? 'active' : 'inactive'}
        onClick={(e) => {
          if (onClick) onClick(e);
          if (!e.defaultPrevented) ctx.setValue(value);
        }}
        className={cn(
          "data-[state=active]:bg-background dark:data-[state=active]:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 cursor-pointer items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:shadow-sm [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
          className,
        )}
        {...props}
      />
    );
  }

  function TabsContent({ className, value, children, ...props }) {
    const ctx = useContext(TabsCtx);
    if (ctx.value !== value) return null;
    return (
      <div
        role="tabpanel"
        data-slot="tabs-content"
        data-state="active"
        className={cn('flex-1 outline-none', className)}
        {...props}
      >
        {children}
      </div>
    );
  }

  /* ---------- command (components/ui/command.tsx, cmdk shim) ---------- */
  const CommandCtx = createContext(null);

  function Command({ className, shouldFilter = true, filter, value, onValueChange, children, ...props }) {
    const [search, setSearch] = useState('');
    const [matchTick, setMatchTick] = useState(0);
    const matchesRef = useRef(new Map());
    const report = useCallback((id, matched) => {
      const map = matchesRef.current;
      if (matched === null) map.delete(id);
      else if (map.get(id) !== matched) map.set(id, matched);
      else return;
      setMatchTick((t) => t + 1);
    }, []);
    const filterFn = useMemo(() => {
      if (filter) return filter;
      return (v, term) => (v.toLowerCase().includes(term.toLowerCase()) ? 1 : 0);
    }, [filter]);
    const anyMatch = Array.from(matchesRef.current.values()).some(Boolean);
    const hasItems = matchesRef.current.size > 0;
    const ctx = useMemo(
      () => ({ search, setSearch, shouldFilter, filterFn, report, anyMatch, hasItems }),
      [search, shouldFilter, filterFn, report, anyMatch, hasItems, matchTick],
    );
    return (
      <CommandCtx.Provider value={ctx}>
        <div
          data-slot="command"
          className={cn(
            'bg-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-md',
            className,
          )}
          {...props}
        >
          {children}
        </div>
      </CommandCtx.Provider>
    );
  }

  function CommandInput({ className, value, onValueChange, ...props }) {
    const ctx = useContext(CommandCtx);
    const controlled = value !== undefined && onValueChange !== undefined;
    const current = controlled ? value : ctx.search;
    return (
      <div
        data-slot="command-input-wrapper"
        className="flex h-9 items-center gap-2 border-b border-border px-3"
      >
        <G.SearchIcon className="shrink-0 opacity-50" />
        <input
          data-slot="command-input"
          cmdk-input=""
          autoComplete="off"
          value={current}
          onChange={(e) => {
            ctx.setSearch(e.target.value);
            if (onValueChange) onValueChange(e.target.value);
          }}
          className={cn(
            'placeholder:text-muted-foreground flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden disabled:cursor-not-allowed disabled:opacity-50',
            className,
          )}
          {...props}
        />
      </div>
    );
  }

  function CommandList({ className, ...props }) {
    return (
      <div
        data-slot="command-list"
        cmdk-list=""
        role="listbox"
        className={cn('max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto', className)}
        {...props}
      />
    );
  }

  function CommandEmpty({ ...props }) {
    const ctx = useContext(CommandCtx);
    if (ctx.anyMatch || !ctx.hasItems) return null;
    return <div data-slot="command-empty" cmdk-empty="" className="py-6 text-center text-sm" {...props} />;
  }

  function CommandGroup({ className, heading, children, ...props }) {
    return (
      <div
        data-slot="command-group"
        cmdk-group=""
        className={cn(
          'text-foreground [&_[cmdk-group-heading]]:text-muted-foreground overflow-hidden p-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium',
          className,
        )}
        {...props}
      >
        {heading != null && <div cmdk-group-heading="">{heading}</div>}
        {children}
      </div>
    );
  }

  function CommandSeparator({ className, ...props }) {
    return (
      <div data-slot="command-separator" cmdk-separator="" className={cn('bg-border -mx-1 h-px', className)} {...props} />
    );
  }

  let commandItemSeq = 0;
  function CommandItem({ className, value, onSelect, disabled, children, ...props }) {
    const ctx = useContext(CommandCtx);
    const idRef = useRef(null);
    if (idRef.current === null) idRef.current = `ci-${++commandItemSeq}`;
    const [highlighted, setHighlighted] = useState(false);
    const searchable = value != null ? String(value) : null;
    const matched =
      ctx.shouldFilter === false || !ctx.search || searchable == null
        ? true
        : ctx.filterFn(searchable, ctx.search) > 0;
    useEffect(() => {
      ctx.report(idRef.current, matched);
      return () => ctx.report(idRef.current, null);
    }, [matched]);
    if (!matched) return null;
    return (
      <div
        role="option"
        cmdk-item=""
        data-slot="command-item"
        data-value={searchable}
        data-selected={highlighted ? 'true' : 'false'}
        data-highlighted={highlighted ? '' : undefined}
        data-disabled={disabled ? 'true' : undefined}
        aria-selected={highlighted}
        onMouseEnter={() => setHighlighted(true)}
        onMouseLeave={() => setHighlighted(false)}
        onClick={() => {
          if (disabled) return;
          if (onSelect) onSelect(searchable);
        }}
        className={cn(
          "data-[highlighted]:bg-accent data-[selected=true]:bg-accent [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-pointer items-center gap-2 rounded-sm px-2 py-1.75 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:cursor-not-allowed data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
          className,
        )}
        {...props}
      >
        {children}
      </div>
    );
  }

  function CommandShortcut({ className, ...props }) {
    return (
      <span
        data-slot="command-shortcut"
        className={cn('text-muted-foreground ms-auto text-xs tracking-widest', className)}
        {...props}
      />
    );
  }

  Object.assign(T.UI, {
    controlPillShell,
    controlPillFormSize,
    controlPillActive,
    controlPillIdle,
    Select,
    SelectContent,
    SelectGroup,
    SelectItem,
    SelectLabel,
    SelectSeparator,
    SelectTrigger,
    SelectValue,
    Tabs,
    TabsList,
    TabsTrigger,
    TabsContent,
    Command,
    CommandInput,
    CommandList,
    CommandEmpty,
    CommandGroup,
    CommandItem,
    CommandShortcut,
    CommandSeparator,
  });

  /* ======================================================================
   * Tables (components/ui/table.tsx, table-scroll-region, use-hidden-columns,
   * data-table, table-chrome)
   * ==================================================================== */

  function computeHiddenCounts(cols, scrollLeft, clientWidth, epsilon = 1) {
    const viewportRight = scrollLeft + clientWidth;
    let leftCount = 0;
    let rightCount = 0;
    for (const c of cols) {
      if (c.offsetLeft + c.offsetWidth > viewportRight + epsilon) rightCount++;
      else if (c.offsetLeft < scrollLeft - epsilon) leftCount++;
    }
    return { leftCount, rightCount };
  }

  const ZERO_COUNTS = { leftCount: 0, rightCount: 0 };

  function useHiddenColumns(scrollRef) {
    const [counts, setCounts] = useState(ZERO_COUNTS);
    const [headerHeight, setHeaderHeight] = useState(0);
    const lastX = useRef({ scrollLeft: -1, clientWidth: -1 });

    const recompute = useCallback(() => {
      const el = scrollRef.current;
      if (!el) return;
      lastX.current = { scrollLeft: el.scrollLeft, clientWidth: el.clientWidth };
      const cols = Array.from(el.querySelectorAll('thead th')).map((th) => ({
        offsetLeft: th.offsetLeft,
        offsetWidth: th.offsetWidth,
      }));
      const next = computeHiddenCounts(cols, el.scrollLeft, el.clientWidth);
      setCounts((prev) =>
        prev.leftCount === next.leftCount && prev.rightCount === next.rightCount ? prev : next,
      );
      const thead = el.querySelector('thead');
      setHeaderHeight(thead ? thead.getBoundingClientRect().height : 0);
    }, [scrollRef]);

    const onScroll = useCallback(() => {
      const el = scrollRef.current;
      if (!el) return;
      if (
        lastX.current.scrollLeft === el.scrollLeft &&
        lastX.current.clientWidth === el.clientWidth
      ) {
        return;
      }
      recompute();
    }, [recompute, scrollRef]);

    useEffect(() => {
      const el = scrollRef.current;
      if (!el) return;
      el.addEventListener('scroll', onScroll, { passive: true });
      const ro = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(recompute) : null;
      if (ro) ro.observe(el);
      const mo = typeof MutationObserver !== 'undefined' ? new MutationObserver(recompute) : null;
      if (mo) mo.observe(el, { childList: true });
      const raf = requestAnimationFrame(recompute);
      return () => {
        el.removeEventListener('scroll', onScroll);
        if (ro) ro.disconnect();
        if (mo) mo.disconnect();
        cancelAnimationFrame(raf);
      };
    }, [scrollRef, recompute, onScroll]);

    const scrollBySide = useCallback(
      (side) => {
        const el = scrollRef.current;
        if (!el) return;
        const reduce =
          typeof window !== 'undefined' &&
          window.matchMedia &&
          window.matchMedia('(prefers-reduced-motion: reduce)').matches;
        const delta = el.clientWidth * 0.8 * (side === 'right' ? 1 : -1);
        el.scrollBy({ left: delta, behavior: reduce ? 'auto' : 'smooth' });
      },
      [scrollRef],
    );

    return {
      leftCount: counts.leftCount,
      rightCount: counts.rightCount,
      headerHeight,
      scrollBySide,
    };
  }

  function TableOverflowAffordance({ side, count, headerHeight, onReveal }) {
    if (count <= 0) return null;
    const isRight = side === 'right';
    const fadeCls = isRight
      ? 'right-0 bg-gradient-to-l from-surface-card to-transparent'
      : 'left-0 bg-gradient-to-r from-surface-card to-transparent';
    const badgeCls = isRight ? 'right-2' : 'left-2';
    const badgeStyle = headerHeight > 0 ? { top: headerHeight / 2 - 12 } : undefined;
    return (
      <>
        <div
          aria-hidden
          className={cn('pointer-events-none absolute inset-y-0 w-12 transition-opacity', fadeCls)}
        />
        <Button
          type="button"
          variant="tertiary"
          size="sm"
          onClick={onReveal}
          data-testid={isRight ? 'table-overflow-badge-right' : 'table-overflow-badge-left'}
          style={badgeStyle}
          className={cn(
            'absolute top-2 z-30 h-6 gap-1 bg-surface-card text-xs font-bold shadow-sm transition-colors',
            badgeCls,
          )}
        >
          {isRight ? (
            <>
              {count} more <G.ArrowRight />
            </>
          ) : (
            <>
              <G.ArrowLeft /> {count} more
            </>
          )}
        </Button>
      </>
    );
  }

  function TableScrollRegion({
    className,
    rootClassName,
    hideOverflowBadge = false,
    ariaLabel = 'Table, scrollable',
    onScrollerChange,
    children,
    ...props
  }) {
    const scrollRef = useRef(null);
    const onScrollerChangeRef = useRef(onScrollerChange);
    onScrollerChangeRef.current = onScrollerChange;
    const setScrollRef = useCallback((node) => {
      scrollRef.current = node;
      if (onScrollerChangeRef.current) onScrollerChangeRef.current(node);
    }, []);
    const { leftCount, rightCount, headerHeight, scrollBySide } = useHiddenColumns(scrollRef);
    const isOverflowing = leftCount > 0 || rightCount > 0;
    return (
      <div data-slot="table-scroll-region" className={cn('relative', rootClassName)}>
        <div
          ref={setScrollRef}
          data-slot="table-container"
          className={cn('w-full overflow-x-auto', className)}
          tabIndex={isOverflowing ? 0 : undefined}
          role={isOverflowing ? 'region' : undefined}
          aria-label={isOverflowing ? ariaLabel : undefined}
          {...props}
        >
          {children}
        </div>
        {!hideOverflowBadge && (
          <>
            <TableOverflowAffordance
              side="left"
              count={leftCount}
              headerHeight={headerHeight}
              onReveal={() => scrollBySide('left')}
            />
            <TableOverflowAffordance
              side="right"
              count={rightCount}
              headerHeight={headerHeight}
              onReveal={() => scrollBySide('right')}
            />
          </>
        )}
      </div>
    );
  }

  function Table({ className, hideOverflowBadge = false, ...props }) {
    return (
      <TableScrollRegion rootClassName="w-full" hideOverflowBadge={hideOverflowBadge}>
        <table
          data-slot="table"
          className={cn('w-full caption-bottom text-sm', className)}
          {...props}
        />
      </TableScrollRegion>
    );
  }
  function TableHeader({ className, ...props }) {
    return (
      <thead
        data-slot="table-header"
        className={cn('[&_tr]:border-b [&_tr]:border-border', className)}
        {...props}
      />
    );
  }
  function TableBody({ className, ...props }) {
    return (
      <tbody
        data-slot="table-body"
        className={cn('[&_tr:last-child]:border-0', className)}
        {...props}
      />
    );
  }
  function TableFooter({ className, ...props }) {
    return (
      <tfoot
        data-slot="table-footer"
        className={cn('bg-muted/50 border-t border-border font-medium [&>tr]:last:border-b-0', className)}
        {...props}
      />
    );
  }
  function TableRow({ className, ...props }) {
    return (
      <tr
        data-slot="table-row"
        className={cn(
          'hover:bg-muted/50 data-[state=selected]:bg-muted border-b border-border transition-colors',
          className,
        )}
        {...props}
      />
    );
  }
  function TableHead({ className, ...props }) {
    return (
      <th
        data-slot="table-head"
        className={cn(
          'text-foreground bg-surface-card h-10 px-2 text-start align-middle font-medium whitespace-nowrap [&>[role=checkbox]]:translate-y-[2px]',
          className,
        )}
        {...props}
      />
    );
  }
  function TableCell({ className, ...props }) {
    return (
      <td
        data-slot="table-cell"
        className={cn(
          'px-2 py-2 align-middle whitespace-nowrap [&>[role=checkbox]]:translate-y-[2px]',
          className,
        )}
        {...props}
      />
    );
  }
  function TableCaption({ className, ...props }) {
    return (
      <caption
        data-slot="table-caption"
        className={cn('text-muted-foreground mt-4 text-sm', className)}
        {...props}
      />
    );
  }

  /* ---------- data-table (components/data-table) ---------- */
  function DataTableSkeletonRow({ columns, hasSelection = false }) {
    return (
      <TableRow aria-hidden className="transition-none hover:bg-transparent">
        {hasSelection && (
          <TableCell className="h-11 w-10 py-0">
            <Skeleton className="size-4 rounded bg-surface-well" />
          </TableCell>
        )}
        {columns.map((c) => (
          <TableCell key={c.id} className={cn('h-11 px-2.5 py-0', c.className)}>
            <Skeleton
              className={cn(
                'h-4 w-full max-w-[140px] bg-surface-well',
                c.align === 'right' && 'ml-auto',
                c.align === 'center' && 'mx-auto',
              )}
            />
          </TableCell>
        ))}
      </TableRow>
    );
  }

  function DataTable({
    columns,
    rows,
    getRowKey,
    empty,
    onRowClick,
    sort,
    onSortChange,
    selection,
    renderSubRow,
    rowClassName,
    layout = 'auto',
    tableClassName,
    loading = false,
    skeletonRows = 8,
    count,
  }) {
    if (!loading && rows.length === 0 && empty) return <>{empty}</>;
    const showSkeletons = loading && rows.length === 0;
    const totalColumnCount = columns.length + (selection ? 1 : 0);
    const alignClass = (align) =>
      align === 'right' ? 'text-right' : align === 'center' ? 'text-center' : undefined;

    const pageKeys = rows.map(getRowKey);
    const selectableKeys = pageKeys.filter((k) =>
      selection && selection.isRowSelectable ? selection.isRowSelectable(k) : true,
    );
    const selectedOnPage = selectableKeys.filter(
      (k) => selection && selection.selectedKeys.has(k),
    ).length;
    const allPageSelected = selectableKeys.length > 0 && selectedOnPage === selectableKeys.length;
    const headerCheckedState = allPageSelected
      ? true
      : selectedOnPage > 0
        ? 'indeterminate'
        : false;

    const renderHeader = (c, countNode) => {
      const isSortable = c.sortable && onSortChange;
      if (!isSortable) {
        if (!countNode) return <span className="block truncate">{c.header}</span>;
        return (
          <span className="flex min-w-0 items-center gap-2">
            <span className="truncate">{c.header}</span>
            {countNode}
          </span>
        );
      }
      const active = sort && sort.key === c.id;
      return (
        <button
          type="button"
          onClick={() =>
            onSortChange({
              key: c.id,
              dir: active && sort && sort.dir === 'asc' ? 'desc' : 'asc',
            })
          }
          className={cn(
            'group inline-flex max-w-full cursor-pointer items-center gap-1 uppercase outline-none transition-colors hover:text-accent-text focus-visible:text-accent-text',
            c.align === 'right' && 'flex-row-reverse',
            active ? 'text-accent-text' : 'text-text-muted',
          )}
        >
          <span className="truncate">{c.header}</span>
          {countNode}
          <G.ChevronDown
            aria-hidden
            className={cn(
              'size-3.5 shrink-0 transition-[opacity,transform]',
              active
                ? 'text-accent-text opacity-100'
                : 'opacity-0 group-hover:opacity-50 group-focus-visible:opacity-50',
              active && sort && sort.dir === 'asc' && 'rotate-180',
            )}
          />
        </button>
      );
    };

    const ariaSort = (c) => {
      if (!c.sortable || !sort || sort.key !== c.id) return undefined;
      return sort.dir === 'asc' ? 'ascending' : 'descending';
    };

    return (
      <Table
        className={cn(
          '[&_tr>:first-child]:pl-4',
          layout === 'fixed' && 'table-fixed',
          tableClassName,
        )}
      >
        <TableHeader>
          <TableRow>
            {selection && (
              <TableHead className="h-[38px] w-10 bg-surface-well">
                <Checkbox
                  aria-label="Select all"
                  checked={headerCheckedState}
                  onCheckedChange={(value) => selection.onToggleAllPage(value === true)}
                  disabled={showSkeletons}
                  className="translate-y-[2px]"
                />
              </TableHead>
            )}
            {columns.map((c, colIndex) => (
              <TableHead
                key={c.id}
                className={cn(
                  'h-[38px] bg-surface-well px-2.5 text-caption font-bold uppercase tracking-wider text-text-muted',
                  alignClass(c.align),
                  c.className,
                )}
                style={c.width ? { width: c.width } : undefined}
                aria-sort={ariaSort(c)}
              >
                {renderHeader(
                  c,
                  colIndex === 0 && count != null && count > 0 ? (
                    <Badge
                      variant="count"
                      data-testid="data-table-count"
                      className={cn(
                        'rounded-md border-transparent bg-surface-card text-text-secondary',
                        'group-hover:bg-accent-soft group-hover:text-accent-text',
                        'group-focus-visible:bg-accent-soft group-focus-visible:text-accent-text',
                        sort && sort.key === c.id && 'bg-accent-soft text-accent-text',
                      )}
                    >
                      {count.toLocaleString()}
                    </Badge>
                  ) : undefined,
                )}
              </TableHead>
            ))}
          </TableRow>
        </TableHeader>
        <TableBody>
          {showSkeletons
            ? Array.from({ length: skeletonRows }, (_, i) => (
                <DataTableSkeletonRow
                  key={`skeleton-${i}`}
                  columns={columns}
                  hasSelection={!!selection}
                />
              ))
            : rows.map((row) => {
                const key = getRowKey(row);
                const isSelected = selection ? selection.selectedKeys.has(key) : false;
                const subRow = renderSubRow ? renderSubRow(row) : null;
                return (
                  <Fragment key={key}>
                    <TableRow
                      data-state={isSelected ? 'selected' : undefined}
                      onClick={onRowClick ? () => onRowClick(row) : undefined}
                      onKeyDown={
                        onRowClick
                          ? (e) => {
                              if (e.key === 'Enter' || e.key === ' ') {
                                e.preventDefault();
                                onRowClick(row);
                              }
                            }
                          : undefined
                      }
                      tabIndex={onRowClick ? 0 : undefined}
                      className={cn(
                        'hover:bg-surface-well',
                        'transition-none',
                        onRowClick && 'cursor-pointer',
                        isSelected && 'data-[state=selected]:bg-accent-soft',
                        subRow != null && 'border-b-0',
                        rowClassName ? rowClassName(row) : undefined,
                      )}
                    >
                      {selection && (
                        <TableCell
                          className="h-11 w-10 py-0"
                          onClick={(e) => e.stopPropagation()}
                        >
                          {(selection.isRowSelectable ? selection.isRowSelectable(key) : true) && (
                            <Checkbox
                              aria-label="Select row"
                              checked={isSelected}
                              onCheckedChange={(value) => selection.onToggleRow(key, value === true)}
                              className="translate-y-[2px]"
                            />
                          )}
                        </TableCell>
                      )}
                      {columns.map((c, colIndex) => (
                        <TableCell
                          key={c.id}
                          className={cn(
                            'h-11 px-2.5 py-0 text-body-sm',
                            colIndex === 0 ? 'text-text-primary' : 'text-text-muted',
                            alignClass(c.align),
                            c.className,
                          )}
                        >
                          {c.accessor(row)}
                        </TableCell>
                      ))}
                    </TableRow>
                    {subRow != null && (
                      <TableRow
                        data-state={isSelected ? 'selected' : undefined}
                        className={cn(isSelected && 'bg-accent-soft')}
                      >
                        <TableCell colSpan={totalColumnCount} className="pt-0">
                          {subRow}
                        </TableCell>
                      </TableRow>
                    )}
                  </Fragment>
                );
              })}
        </TableBody>
      </Table>
    );
  }

  /* ---------- table-chrome (components/table-chrome) ---------- */
  const PAGER_BTN = cn(
    'inline-grid size-7 place-items-center rounded-full border border-border-strong',
    'bg-surface-well text-text-secondary transition-colors dark:bg-surface-shell',
    'hover:border-border-strong hover:bg-surface-row hover:text-text-primary',
    'disabled:cursor-default disabled:opacity-40 disabled:hover:border-border-strong disabled:hover:text-text-secondary',
    'disabled:hover:bg-surface-well dark:disabled:hover:bg-surface-shell',
  );

  function TablePager({ total, page, pageSize, onPageChange, testIdPrefix, position, className }) {
    const pages = Math.max(1, Math.ceil(total / pageSize));
    const from = total === 0 ? 0 : (page - 1) * pageSize + 1;
    const to = Math.min(total, page * pageSize);
    return (
      <div
        data-testid={`${testIdPrefix}-${position}`}
        className={cn('inline-flex items-center gap-4', className)}
      >
        <span
          data-testid={`${testIdPrefix}-range`}
          className="text-body-sm whitespace-nowrap text-text-muted tabular-nums"
        >
          {from}–{to} of <span className="text-text-primary">{total.toLocaleString()}</span>
        </span>
        <div className="inline-flex items-center gap-2">
          <button
            type="button"
            aria-label="Previous page"
            disabled={page <= 1}
            onClick={() => onPageChange(page - 1)}
            className={PAGER_BTN}
          >
            <G.ChevronLeft size={14} aria-hidden />
          </button>
          <button
            type="button"
            aria-label="Next page"
            disabled={page >= pages}
            onClick={() => onPageChange(page + 1)}
            className={PAGER_BTN}
          >
            <G.ChevronRight size={14} aria-hidden />
          </button>
        </div>
      </div>
    );
  }

  const TABLE_UPDATING_MIN_VISIBLE_MS = 1200;

  function useMinVisible(active, ms) {
    const [visible, setVisible] = useState(active);
    const shownAtRef = useRef(active ? Date.now() : null);
    useEffect(() => {
      if (active) {
        if (shownAtRef.current == null) shownAtRef.current = Date.now();
        setVisible(true);
        return;
      }
      if (shownAtRef.current == null) return;
      const remaining = ms - (Date.now() - shownAtRef.current);
      if (remaining <= 0) {
        shownAtRef.current = null;
        setVisible(false);
        return;
      }
      const timer = setTimeout(() => {
        shownAtRef.current = null;
        setVisible(false);
      }, remaining);
      return () => clearTimeout(timer);
    }, [active, ms]);
    return active || visible;
  }

  function TableChrome({
    total,
    page,
    pageSize,
    onPageChange,
    search,
    filters,
    children,
    className,
    bare = false,
    updating = false,
  }) {
    const pager = (position) => (
      <TablePager
        position={position}
        testIdPrefix="table-chrome"
        page={page}
        total={total}
        pageSize={pageSize}
        onPageChange={onPageChange}
      />
    );
    const showUpdating = useMinVisible(updating, TABLE_UPDATING_MIN_VISIBLE_MS);
    const updatingStatus = (
      <span role="status" aria-live="polite" className="sr-only">
        {showUpdating ? 'Updating results…' : ''}
      </span>
    );
    const updatingSweep = showUpdating ? (
      <div
        aria-hidden
        className="pointer-events-none absolute inset-x-0 top-0 z-10 h-px overflow-hidden"
      >
        <span className="animate-table-updating" />
      </div>
    ) : null;
    if (bare) {
      return (
        <div
          data-updating={showUpdating || undefined}
          className={cn(
            'relative overflow-clip rounded-2xl border border-border-subtle bg-surface-card',
            className,
          )}
        >
          {updatingStatus}
          {updatingSweep}
          {children}
        </div>
      );
    }
    return (
      <div
        data-updating={showUpdating || undefined}
        className={cn('rounded-2xl border border-border-subtle bg-surface-card', className)}
      >
        {updatingStatus}
        <div className="flex flex-wrap items-center gap-2 border-b border-border-subtle px-4 py-[11px]">
          <div className="flex min-w-0 flex-wrap items-center gap-2">
            {search}
            {filters}
          </div>
          <div className="ml-auto">{pager('top')}</div>
        </div>
        <div className="relative overflow-clip">
          {updatingSweep}
          {children}
        </div>
        <div className="flex items-center justify-end border-t border-border-subtle px-4 py-[11px]">
          {pager('bottom')}
        </div>
      </div>
    );
  }

  /* ---------- page-container (components/page-container) ---------- */
  function PageContainer({ width = 'page', publishColumn = true, className, children, ...rest }) {
    const ref = useRef(null);
    useLayoutEffect(() => {
      if (!publishColumn || !ref.current) return;
      const max = getComputedStyle(ref.current).maxWidth;
      if (!max || max === 'none') return;
      const root = document.documentElement;
      root.style.setProperty('--page-column', max);
      return () => {
        root.style.removeProperty('--page-column');
      };
    }, [publishColumn, width, className]);
    return (
      <div
        ref={ref}
        className={cn(
          'mx-auto w-full',
          width === 'feed' ? 'max-w-feed' : width === 'page' ? 'max-w-page' : '',
          className,
        )}
        {...rest}
      >
        {children}
      </div>
    );
  }

  /* ---------- page-header (components/page-header) ---------- */
  function PageHeader({ title, subtitle, back, actions, className, children, ...rest }) {
    const openSidebar = useSidebarTrigger();
    return (
      <header
        className={cn('mb-6 flex flex-wrap items-start justify-between gap-3 px-2 md:px-0', className)}
        {...rest}
      >
        <div className="flex min-w-0 flex-wrap items-baseline gap-3">
          {openSidebar && <SidebarTrigger onClick={openSidebar} className="-my-1 self-center" />}
          <h2 className="text-page-title text-text-primary">{title}</h2>
          {subtitle != null && <p className="text-body text-text-secondary">{subtitle}</p>}
          {back}
        </div>
        {actions != null && <div className="flex flex-shrink-0 items-center gap-2">{actions}</div>}
        {children}
      </header>
    );
  }

  function PageHeaderBackLink({ asChild, className, ...props }) {
    const Comp = asChild ? Slot : 'a';
    return (
      <Comp
        className={cn(
          'inline-flex items-center gap-1 text-sm text-text-muted transition-colors hover:text-text-secondary',
          className,
        )}
        {...props}
      />
    );
  }

  /* ---------- overflow-menu (components/overflow-menu) ---------- */
  function OverflowMenu({ children, label = 'Open menu', align = 'end', contentClassName, size = 'icon-sm' }) {
    return (
      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <Button
            variant="tertiary"
            size={size}
            aria-label={label}
            className="border-0 hover:bg-accent-soft hover:text-accent-text"
          >
            <G.MoreHorizontal className="size-5" />
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent
          align={align}
          className={contentClassName}
          onCloseAutoFocus={(e) => e.preventDefault()}
        >
          {children}
        </DropdownMenuContent>
      </DropdownMenu>
    );
  }
  const OverflowMenuItem = DropdownMenuItem;
  const OverflowMenuSeparator = DropdownMenuSeparator;

  /* ---------- segmented-switch (components/segmented-switch) ---------- */
  function SegmentedSwitch({
    value,
    onChange,
    options,
    className,
    fullWidth = false,
    'aria-label': ariaLabel,
  }) {
    return (
      <div
        role="group"
        aria-label={ariaLabel}
        className={cn(
          'inline-flex gap-0.5 rounded-[9px] border border-border-subtle bg-surface-well p-0.75',
          fullWidth && 'flex w-full',
          className,
        )}
      >
        {options.map((o) => {
          const active = o.value === value;
          const cls = cn(
            'inline-flex items-center rounded-[5px] px-[11px] py-1.5 text-meta font-semibold whitespace-nowrap transition',
            fullWidth && 'flex-1 justify-center',
            active
              ? 'bg-surface-card text-text-primary shadow-sm'
              : 'text-text-secondary hover:text-text-primary',
          );
          return o.href ? (
            <a key={o.value} href={o.href} className={cls} data-testid={o.testId}>
              {o.label}
            </a>
          ) : (
            <button
              key={o.value}
              type="button"
              aria-pressed={active}
              className={cn(cls, 'cursor-pointer')}
              data-testid={o.testId}
              onClick={() => onChange(o.value)}
            >
              {o.label}
            </button>
          );
        })}
      </div>
    );
  }

  /* ---------- type-chip (components/type-chip) ---------- */
  const TYPE_CHIP_DOT = {
    public: 'bg-dot-career',
    private: 'bg-dot-job',
  };
  function TypeChip({ type, className }) {
    return (
      <span
        className={cn(
          'inline-flex items-center gap-1.5 align-middle text-body-sm capitalize leading-none text-text-muted',
          className,
        )}
      >
        <span
          className={cn(
            'h-1.5 w-1.5 shrink-0 rounded-full',
            TYPE_CHIP_DOT[type.toLowerCase()] ?? 'bg-text-muted',
          )}
        />
        {type}
      </span>
    );
  }

  /* ---------- signal-types registry (lib/signal-types.tsx) ---------- */
  const SIGNAL_TYPES = {
    news: {
      label: 'News',
      get icon() {
        return (T.Icons || {}).NewsIcon || G.NewsIcon;
      },
      colorClass: 'text-dot-news',
      hueVar: 'var(--dot-news)',
    },
    job_listing: {
      label: 'Job listing',
      get icon() {
        return (T.Icons || {}).JobListingIcon || G.JobListingIcon;
      },
      colorClass: 'text-dot-job',
      hueVar: 'var(--dot-job)',
    },
    career_change: {
      label: 'Career',
      get icon() {
        return (T.Icons || {}).CareerIcon || G.CareerIcon;
      },
      colorClass: 'text-dot-career',
      hueVar: 'var(--dot-career)',
    },
  };

  /* components/event-card/to-signal-type.ts */
  function toSignalType(serverType) {
    switch (serverType) {
      case 'job_change':
        return 'career_change';
      case 'jobs':
        return 'job_listing';
      case 'career_change':
      case 'job_listing':
        return serverType;
      default:
        return 'news';
    }
  }

  /* ---------- filter-popover suite (components/filter-popover) ---------- */
  function FilterCheckbox({ checked, indeterminate = false, className }) {
    const filled = checked || indeterminate;
    return (
      <span
        className={cn(
          'flex size-4 shrink-0 items-center justify-center rounded-[3px] border',
          filled ? 'border-accent-brand bg-accent-brand' : 'border-border-strong',
          className,
        )}
      >
        {indeterminate ? (
          <G.Minus size={12} className="text-white" strokeWidth={3} />
        ) : checked ? (
          <G.Check size={12} className="text-white" strokeWidth={3} />
        ) : null}
      </span>
    );
  }

  function SearchableFilterPopover({
    open,
    onOpenChange,
    active,
    triggerContent,
    onClear,
    placeholder,
    heading,
    emptyText,
    children,
    showSearch = true,
    footer,
    contentClassName,
    search,
    onSearchChange,
    shouldFilter,
    ariaLabel,
    triggerAriaLabel,
    triggerClassName,
  }) {
    return (
      <Popover open={open} onOpenChange={onOpenChange}>
        <PopoverAnchor asChild>
          <div
            className={cn(
              controlPillShell,
              active ? controlPillActive : controlPillIdle,
              triggerClassName,
            )}
          >
            <PopoverTrigger
              aria-label={triggerAriaLabel}
              className="flex flex-1 min-w-0 items-center justify-between gap-2 outline-none cursor-pointer"
            >
              {triggerContent}
              {!active && <G.ChevronDownIcon size={16} className="opacity-50 shrink-0" />}
            </PopoverTrigger>
            {active && (
              <button
                type="button"
                aria-label="Clear filter"
                className="flex size-4 shrink-0 items-center justify-center rounded-sm opacity-50 outline-none hover:opacity-100 focus-visible:ring-1 focus-visible:ring-ring"
                onClick={(e) => {
                  e.stopPropagation();
                  onClear(e);
                }}
                onKeyDown={(e) => {
                  if (e.key === 'Enter' || e.key === ' ') {
                    e.preventDefault();
                    e.stopPropagation();
                    onClear(e);
                  }
                }}
              >
                <G.X size={12} aria-hidden="true" />
              </button>
            )}
          </div>
        </PopoverAnchor>
        <PopoverContent
          className={cn('w-auto min-w-[200px] p-0', contentClassName)}
          align="start"
          aria-label={ariaLabel ?? placeholder}
        >
          <Command
            shouldFilter={shouldFilter}
            filter={(value, term) => (value.toLowerCase().includes(term.toLowerCase()) ? 1 : 0)}
          >
            {showSearch && (
              <CommandInput placeholder={placeholder} value={search} onValueChange={onSearchChange} />
            )}
            <CommandList>
              <CommandEmpty>{emptyText}</CommandEmpty>
              {heading ? <CommandGroup heading={heading}>{children}</CommandGroup> : children}
              {footer ? <div className="bg-popover sticky bottom-0">{footer}</div> : null}
            </CommandList>
          </Command>
        </PopoverContent>
      </Popover>
    );
  }

  /* use-load-more-sentinel */
  function useLoadMoreSentinel({ enabled, onLoadMore }) {
    const [sentinelEl, setSentinelEl] = useState(null);
    useEffect(() => {
      if (!enabled || !sentinelEl) return;
      const sentinel = sentinelEl;
      const findScrollParent = (el) => {
        let node = el.parentElement;
        while (node && node !== document.body) {
          const overflowY = getComputedStyle(node).overflowY;
          if (overflowY === 'auto' || overflowY === 'scroll') return node;
          node = node.parentElement;
        }
        return null;
      };
      const listEl = findScrollParent(sentinel);
      if (!listEl) return;
      const check = () => {
        const remaining = listEl.scrollHeight - listEl.scrollTop - listEl.clientHeight;
        if (remaining > 200) return;
        onLoadMore();
      };
      check();
      listEl.addEventListener('scroll', check, { passive: true });
      return () => listEl.removeEventListener('scroll', check);
    }, [enabled, sentinelEl, onLoadMore]);
    return setSentinelEl;
  }

  const ACCOUNT_FILTER_INITIAL_VISIBLE = 50;
  const ACCOUNT_FILTER_LOAD_MORE_STEP = 50;

  function AccountMultiSelectLogo({ account }) {
    return (
      <LogoAvatar
        domain={account.url}
        src={account.logoUrl}
        alt={account.name}
        fallbackText={account.name.charAt(0).toUpperCase()}
        className="size-5 rounded-sm text-2xs"
        fallbackClassName="bg-gradient-to-br from-yellow-400 to-pink-500 text-white rounded-sm"
      />
    );
  }

  function AccountMultiSelect({
    accounts,
    selected,
    onChange,
    placeholder = 'All Accounts',
    eventCounts,
    onSearchChange,
    onLoadMore,
    hasMore: serverHasMore,
    loading: serverLoading,
  }) {
    const serverMode = !!onLoadMore;
    const [open, setOpen] = useState(false);
    const [search, setSearch] = useState('');
    const [visibleCount, setVisibleCount] = useState(ACCOUNT_FILTER_INITIAL_VISIBLE);
    const selectedSet = useMemo(() => new Set(selected), [selected]);

    const sortedAccounts = useMemo(() => {
      if (serverMode) return accounts;
      if (!eventCounts) return accounts;
      return [...accounts].sort((a, b) => {
        const countA = eventCounts.get(a.id) ?? 0;
        const countB = eventCounts.get(b.id) ?? 0;
        if (countA !== countB) return countB - countA;
        return a.name.localeCompare(b.name);
      });
    }, [accounts, eventCounts, serverMode]);

    const filteredAccounts = useMemo(() => {
      if (serverMode) return sortedAccounts;
      const hideZero = (a) =>
        !eventCounts || (eventCounts.get(a.id) ?? 0) > 0 || selectedSet.has(a.id);
      const base = sortedAccounts.filter(hideZero);
      const q = search.trim().toLowerCase();
      if (!q) return base;
      return base.filter((a) => a.name.toLowerCase().includes(q));
    }, [sortedAccounts, search, serverMode, eventCounts, selectedSet]);

    const visibleAccounts = serverMode
      ? filteredAccounts
      : search
        ? filteredAccounts
        : filteredAccounts.slice(0, visibleCount);

    const hasMore = serverMode ? !!serverHasMore : !search && visibleCount < filteredAccounts.length;

    const handleSearchChange = (value) => {
      setSearch(value);
      if (onSearchChange) onSearchChange(value);
    };

    const handleOpenChange = (next) => {
      setOpen(next);
      if (!next) {
        handleSearchChange('');
        setVisibleCount(ACCOUNT_FILTER_INITIAL_VISIBLE);
      }
    };

    const setSentinelEl = useLoadMoreSentinel({
      enabled: open && hasMore,
      onLoadMore: () => {
        if (serverMode) {
          if (onLoadMore) onLoadMore();
        } else {
          setVisibleCount((c) => c + ACCOUNT_FILTER_LOAD_MORE_STEP);
        }
      },
    });

    const toggleAccount = (id) => {
      const next = new Set(selectedSet);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      onChange(Array.from(next));
    };

    const clearAll = () => {
      onChange([]);
    };

    const selectedAccounts = accounts.filter((a) => selectedSet.has(a.id));

    let triggerContent;
    if (selected.length === 0) {
      triggerContent = (
        <div className="flex items-center gap-1.5 overflow-hidden">
          <G.ListFilter size={14} className="shrink-0 text-muted-foreground" />
          <span className="truncate text-xs font-normal text-muted-foreground">{placeholder}</span>
        </div>
      );
    } else if (selected.length === 1) {
      const account = selectedAccounts[0];
      triggerContent = account ? (
        <div className="flex items-center gap-1.5 overflow-hidden">
          <AccountMultiSelectLogo account={account} />
          <span className="truncate text-xs">{account.name}</span>
        </div>
      ) : (
        <span className="text-muted-foreground text-xs font-normal">{placeholder}</span>
      );
    } else if (selected.length === 2) {
      triggerContent = (
        <div className="flex items-center gap-1 overflow-hidden">
          {selectedAccounts.map((a) => (
            <AccountMultiSelectLogo key={a.id} account={a} />
          ))}
          <span className="truncate text-xs">{selectedAccounts.map((a) => a.name).join(', ')}</span>
        </div>
      );
    } else {
      triggerContent = (
        <div className="flex items-center gap-1.5 overflow-hidden">
          <span className="truncate text-xs">{`${selected.length} accounts`}</span>
        </div>
      );
    }

    return (
      <SearchableFilterPopover
        open={open}
        onOpenChange={handleOpenChange}
        active={selected.length > 0}
        triggerContent={triggerContent}
        onClear={(e) => {
          e.stopPropagation();
          clearAll();
        }}
        placeholder="Search accounts..."
        emptyText="No accounts found."
        contentClassName="w-[280px]"
        search={search}
        onSearchChange={handleSearchChange}
        shouldFilter={false}
        footer={
          selected.length > 0 ? (
            <>
              <CommandSeparator />
              <CommandGroup>
                <CommandItem
                  onSelect={clearAll}
                  className="text-muted-foreground justify-center text-center"
                >
                  Clear selection
                </CommandItem>
              </CommandGroup>
            </>
          ) : null
        }
      >
        <CommandGroup>
          {visibleAccounts.map((account) => {
            const isSelected = selectedSet.has(account.id);
            const count = eventCounts ? (eventCounts.get(account.id) ?? 0) : 0;
            return (
              <CommandItem
                key={account.id}
                value={account.id}
                onSelect={() => toggleAccount(account.id)}
              >
                <FilterCheckbox checked={isSelected} />
                <AccountMultiSelectLogo account={account} />
                <span className="flex-1 truncate">{account.name}</span>
                {eventCounts && (
                  <span className="text-muted-foreground/60 ml-1 text-2xs tabular-nums">{count}</span>
                )}
              </CommandItem>
            );
          })}
          {hasMore && <div ref={setSentinelEl} aria-hidden className="h-px" />}
          {serverMode && serverLoading && (
            <div className="flex items-center justify-center py-2 text-muted-foreground text-xs">
              <G.Loader2 size={12} className="animate-spin" />
            </div>
          )}
        </CommandGroup>
      </SearchableFilterPopover>
    );
  }

  /* ---------- signal-filter (components/signal-filter) ---------- */
  function SignalFilter({ signals, selected, onToggle, onClear, className }) {
    const [open, setOpen] = useState(false);
    const sel = new Set(selected);
    const label =
      selected.length === 0
        ? 'All Signals'
        : selected.length === 1
          ? selected[0]
          : `${selected.length} signals`;
    const first = signals.find((s) => sel.has(s.name));
    const firstMeta = first && first.type ? SIGNAL_TYPES[first.type] : null;

    return (
      <div className={cn('flex items-center gap-2', className)}>
        <SearchableFilterPopover
          open={open}
          onOpenChange={setOpen}
          active={selected.length > 0}
          ariaLabel="Filter by signals"
          placeholder="Search signals..."
          emptyText="No signals found."
          contentClassName="w-[340px]"
          onClear={(e) => {
            e.stopPropagation();
            onClear();
          }}
          triggerContent={
            <span className="flex min-w-0 items-center gap-1.5">
              {first && first.icon ? (
                <span className="shrink-0">{first.icon}</span>
              ) : firstMeta ? (
                <firstMeta.icon className={cn('size-3.5 shrink-0', firstMeta.colorClass)} />
              ) : (
                <G.Zap size={14} className="shrink-0 text-text-muted" />
              )}
              <span
                className={cn(
                  'truncate text-xs',
                  selected.length === 0 ? 'font-normal text-text-muted' : 'text-text-secondary',
                )}
              >
                {label}
              </span>
            </span>
          }
        >
          {signals.map((s) => {
            const checked = sel.has(s.name);
            const meta = s.type ? SIGNAL_TYPES[s.type] : null;
            return (
              <CommandItem
                key={s.name}
                value={s.name}
                onSelect={() => onToggle(s.name)}
                className="gap-2 pr-4"
              >
                <FilterCheckbox checked={checked} />
                {s.labelNode ? (
                  <span className="flex min-w-0 flex-1">{s.labelNode}</span>
                ) : (
                  <>
                    {s.icon ? (
                      <span className="shrink-0">{s.icon}</span>
                    ) : (
                      meta && <meta.icon className={cn('size-3.5 shrink-0', meta.colorClass)} />
                    )}
                    <span className="flex-1 truncate">{s.name}</span>
                  </>
                )}
                <span className="shrink-0 tabular-nums text-meta text-text-muted">{s.count}</span>
              </CommandItem>
            );
          })}
        </SearchableFilterPopover>
      </div>
    );
  }

  /* ---------- hooks/use-account-filter-options (mock hydrator) ---------- */
  const ACCOUNT_FILTER_PAGE_SIZE = 50;
  function useAccountFilterOptions(enabled, args) {
    const { ids, selectedIds } = args;
    const [visibleCount, setVisibleCount] = useState(ACCOUNT_FILTER_PAGE_SIZE);
    const idsKey = ids.join(',');
    useEffect(() => {
      setVisibleCount(ACCOUNT_FILTER_PAGE_SIZE);
    }, [idsKey]);
    const [search, setSearch] = useState('');
    const resolve = useCallback((idList) => {
      const fn = T.Data && T.Data.getAccountsByIds;
      return fn ? fn(idList) : [];
    }, []);
    const accounts = useMemo(() => {
      if (!enabled) return [];
      const sliced = ids.slice(0, visibleCount);
      const base = resolve(sliced);
      const extraIds = (selectedIds ?? []).filter((id) => !sliced.includes(id));
      const extras = resolve(extraIds);
      const all = [...base, ...extras];
      const q = search.trim().toLowerCase();
      if (!q) return all;
      return all.filter((a) => a.name.toLowerCase().includes(q));
    }, [enabled, idsKey, visibleCount, selectedIds && selectedIds.join(','), search, resolve]);
    return {
      accounts,
      loading: false,
      hasMore: visibleCount < ids.length,
      loadMore: () => setVisibleCount((c) => c + ACCOUNT_FILTER_PAGE_SIZE),
      onSearchChange: setSearch,
    };
  }

  Object.assign(T.UI, {
    computeHiddenCounts,
    useHiddenColumns,
    TableScrollRegion,
    Table,
    TableHeader,
    TableBody,
    TableFooter,
    TableHead,
    TableRow,
    TableCell,
    TableCaption,
    DataTable,
    DataTableSkeletonRow,
    TableChrome,
    TablePager,
    TABLE_UPDATING_MIN_VISIBLE_MS,
    PageContainer,
    PageHeader,
    PageHeaderBackLink,
    OverflowMenu,
    OverflowMenuItem,
    OverflowMenuSeparator,
    SegmentedSwitch,
    TypeChip,
    SIGNAL_TYPES,
    toSignalType,
    FilterCheckbox,
    SearchableFilterPopover,
    useLoadMoreSentinel,
    AccountMultiSelect,
    SignalFilter,
    useAccountFilterOptions,
  });

  /* ======================================================================
   * Logos + app sidebar (components/Logo.tsx, components/app-sidebar/*)
   * ==================================================================== */

  function TrayoWordmark({ className = 'h-8 w-auto', ...props }) {
    return (
      <svg
        viewBox="0 0 698 216"
        xmlns="http://www.w3.org/2000/svg"
        fill="none"
        role="img"
        aria-label="trayo.ai"
        className={className}
        {...props}
      >
        <path
          fill="currentColor"
          d="M211.618 139.166V31.533h28.87v30.783h29.745v25.108h-29.745v47.813c0 6.549 3.5 10.042 10.061 10.042h19.684v26.199H243.55c-20.559 0-31.932-11.789-31.932-32.312M279.856 171.478V62.316h27.777v25.677c0 .77.625 1.396 1.396 1.396.603 0 1.136-.39 1.336-.958 5.654-16.07 18.722-26.992 41.886-27.206V91.79h-9.842c-22.528 0-33.901 9.825-33.901 36.897v42.791zM353.63 116.897c0-32.093 19.903-55.672 45.711-55.672 17.429 0 30.623 7.757 37.502 24.222a1.33 1.33 0 0 0 1.22.823c.719 0 1.303-.584 1.303-1.304v-22.65h27.777v109.162h-27.777v-23.019a.934.934 0 0 0-.934-.934h-.62a.95.95 0 0 0-.873.591c-6.851 16.624-20.088 24.454-37.598 24.454-25.808 0-45.711-23.579-45.711-55.673m28.87 0c0 17.466 10.717 31.657 27.777 31.657 16.841 0 27.995-13.972 27.995-31.657 0-17.684-11.154-31.657-27.995-31.657-17.06 0-27.777 14.192-27.777 31.657M510.42 215.798l13.23-41.89a1.868 1.868 0 0 0-1.781-2.43h-14.073L473.458 62.316h28.87l26.213 83.407c.548 1.744 3.016 1.744 3.564 0l26.213-83.407h29.089l-47.898 153.482zM581.637 116.897c0-32.748 24.276-58.074 57.739-58.074 33.682 0 57.959 25.326 57.959 58.074 0 32.749-24.277 57.856-57.959 57.856-33.463 0-57.739-25.107-57.739-57.856m27.994 0c0 18.34 12.685 31.439 29.745 31.439 17.059 0 29.745-13.099 29.745-31.439 0-18.557-12.686-31.657-29.745-31.657s-29.745 13.1-29.745 31.657M171.479 171.479h-59.504s-12.43-32.426-17.543-65.366c-10.226-66.396 77.047-39.117 77.047-39.117v49.496s-73.873-48.123-57.3-12.867c1.322 2.831 2.997 5.49 4.848 7.978 22.215 29.852 52.452 59.876 52.452 59.876M0 171.479h59.504s12.43-32.426 17.543-65.366C87.273 39.717 0 66.996 0 66.996v49.496s73.873-48.124 57.3-12.867c-1.322 2.831-2.997 5.49-4.848 7.978C30.237 141.455 0 171.479 0 171.479M119.255 32.865 85.541 0 51.827 32.865l33.714 32.864z"
        />
      </svg>
    );
  }

  function TrayoLogoMark({ className = 'h-6 w-auto', ...props }) {
    return (
      <svg
        viewBox="0 0 172 216"
        xmlns="http://www.w3.org/2000/svg"
        fill="none"
        role="img"
        aria-label="trayo.ai logomark"
        className={className}
        {...props}
      >
        <path
          fill="currentColor"
          d="M171.479 171.479h-59.504s-12.43-32.426-17.543-65.366c-10.226-66.396 77.047-39.117 77.047-39.117v49.496s-73.873-48.123-57.3-12.867c1.322 2.831 2.997 5.49 4.848 7.978 22.215 29.852 52.452 59.876 52.452 59.876M0 171.479h59.504s12.43-32.426 17.543-65.366C87.273 39.717 0 66.996 0 66.996v49.496s73.873-48.124 57.3-12.867c-1.322 2.831-2.997 5.49-4.848 7.978C30.237 141.455 0 171.479 0 171.479M119.255 32.865 85.541 0 51.827 32.865l33.714 32.864z"
        />
      </svg>
    );
  }

  function Logo({ className = 'size-6', ...props }) {
    return (
      <svg
        id="trayo-admin-logo"
        viewBox="0 0 24 24"
        xmlns="http://www.w3.org/2000/svg"
        height="24"
        width="24"
        fill="none"
        stroke="currentColor"
        strokeWidth="2"
        strokeLinecap="round"
        strokeLinejoin="round"
        className={className}
        {...props}
      >
        <title>Trayo Admin</title>
        <path d="M15 6v12a3 3 0 1 0 3-3H6a3 3 0 1 0 3 3V6a3 3 0 1 0-3 3h12a3 3 0 1 0-3-3" />
      </svg>
    );
  }

  /* sidebar-collapsed-context */
  const SidebarCollapsedContext = createContext(false);
  function useSidebarCollapsed() {
    return useContext(SidebarCollapsedContext);
  }

  /* use-sidebar-mobile */
  const SIDEBAR_MOBILE_MEDIA = '(max-width: 1023px)';
  function useSidebarMobile() {
    const [isMobile, setIsMobile] = useState(
      () => typeof window !== 'undefined' && window.matchMedia(SIDEBAR_MOBILE_MEDIA).matches,
    );
    useEffect(() => {
      if (typeof window === 'undefined') return;
      const mq = window.matchMedia(SIDEBAR_MOBILE_MEDIA);
      setIsMobile(mq.matches);
      const handler = (e) => setIsMobile(e.matches);
      mq.addEventListener('change', handler);
      return () => mq.removeEventListener('change', handler);
    }, []);
    return isMobile;
  }

  /* sidebar-trigger */
  function SidebarTrigger({ onClick, className }) {
    return (
      <button
        type="button"
        onClick={onClick}
        aria-label="Open menu"
        className={cn(
          'group/burger inline-flex h-[38px] w-[38px] items-center justify-center rounded-lg border border-border-subtle bg-surface-shell text-text-primary transition-all duration-150 ease-out hover:bg-surface-well active:scale-90 lg:hidden',
          className,
        )}
      >
        <G.Menu
          size={20}
          className="transition-transform duration-200 ease-out group-active/burger:rotate-90"
        />
      </button>
    );
  }

  /* sidebar-trigger-context */
  const SidebarTriggerContext = createContext(null);
  const SidebarTriggerProvider = SidebarTriggerContext.Provider;
  function useSidebarTrigger() {
    return useContext(SidebarTriggerContext);
  }
  function MobileSidebarTrigger({ className }) {
    const openSidebar = useSidebarTrigger();
    if (!openSidebar) return null;
    return <SidebarTrigger onClick={openSidebar} className={cn(className)} />;
  }

  /* nav-item */
  function NavItem({ item, renderLink, collapsed }) {
    const active = Boolean(item.active);
    const pillClassName = cn(
      'flex w-full items-center gap-1.5 rounded-full py-[7px] pl-3.5 pr-[9px] text-sm font-medium',
      'hover:bg-surface-well',
      !active && 'text-inherit',
      active &&
        'bg-accent-soft font-semibold text-accent-text hover:bg-accent-soft hover:text-accent-text',
    );
    const circleClassName = cn(
      'flex h-8 w-8 items-center justify-center rounded-full text-sm font-medium',
      'hover:bg-surface-well',
      !active && 'text-inherit',
      active &&
        'bg-accent-soft font-semibold text-accent-text hover:bg-accent-soft hover:text-accent-text',
    );
    return (
      <span
        data-slot="sidebar-menu-button"
        data-active={active ? 'true' : undefined}
        className={cn('block text-text-secondary', !active && 'hover:text-text-primary')}
      >
        <span className={cn(collapsed && 'lg:hidden')}>
          {renderLink({
            href: item.href,
            active,
            className: pillClassName,
            children: (
              <>
                {item.icon && <span className="inline-flex shrink-0">{item.icon}</span>}
                <span className="min-w-0 flex-1 truncate text-left">{item.label}</span>
                {item.badge && <span className="shrink-0">{item.badge}</span>}
              </>
            ),
          })}
        </span>
        {collapsed && (
          <span className="hidden lg:flex lg:justify-center">
            <Tooltip>
              <TooltipTrigger asChild>
                {renderLink({
                  href: item.href,
                  active,
                  className: circleClassName,
                  children: item.icon ? (
                    <span className="inline-flex shrink-0">{item.icon}</span>
                  ) : (
                    <span className="text-xs">{item.label.slice(0, 1)}</span>
                  ),
                })}
              </TooltipTrigger>
              <TooltipContent side="right">{item.label}</TooltipContent>
            </Tooltip>
          </span>
        )}
      </span>
    );
  }

  /* nav-section */
  function NavSection({ section, renderLink, collapsed }) {
    const collapsible = Boolean(section.collapsible);
    const [open, setOpen] = useState(section.defaultOpen ?? true);
    const showItems = !collapsible || open || Boolean(collapsed);
    return (
      <div className={cn('flex flex-col gap-px', section.className)}>
        {section.label &&
          !collapsed &&
          (collapsible ? (
            <button
              type="button"
              onClick={() => setOpen((o) => !o)}
              aria-expanded={open}
              data-slot="sidebar-group-label"
              className="mb-1 flex w-full cursor-pointer items-center px-[9px] py-1.5 text-caption font-bold uppercase tracking-wider text-text-muted hover:text-text-primary"
            >
              <span className="min-w-0 flex-1 text-left">{section.label}</span>
              <G.ChevronDown
                size={14}
                className={cn('shrink-0 text-text-muted transition-transform', open && 'rotate-180')}
              />
            </button>
          ) : (
            <div
              data-slot="sidebar-group-label"
              className="mb-1 px-[9px] py-1.5 text-caption font-bold uppercase tracking-wider text-text-muted"
            >
              {section.label}
            </div>
          ))}
        {showItems && (
          <div className="flex flex-col gap-px">
            {section.items.map((item, i) => (
              <NavItem
                key={`${item.href}:${i}`}
                item={item}
                renderLink={renderLink}
                collapsed={collapsed}
              />
            ))}
          </div>
        )}
      </div>
    );
  }

  /* app-sidebar */
  function AppSidebar({
    nav,
    renderLink,
    logo,
    logoMark,
    logoClassName,
    accountSwitcher,
    userMenu,
    open = false,
    onOpenChange,
    collapsed = false,
    onCollapsedChange,
    className,
  }) {
    const isMobile = useSidebarMobile();
    const navRef = useRef(null);
    const [showGradient, setShowGradient] = useState(false);

    const updateGradient = useCallback(() => {
      const el = navRef.current;
      if (!el) return;
      const canScroll = el.scrollHeight > el.clientHeight;
      const atBottom = el.scrollTop + el.clientHeight >= el.scrollHeight - 4;
      setShowGradient(canScroll && !atBottom);
    }, []);

    useEffect(() => {
      updateGradient();
      const el = navRef.current;
      if (!el) return;
      el.addEventListener('scroll', updateGradient, { passive: true });
      const ro = new ResizeObserver(updateGradient);
      ro.observe(el);
      return () => {
        el.removeEventListener('scroll', updateGradient);
        ro.disconnect();
      };
    }, [updateGradient]);

    useEffect(() => {
      if (!open || !isMobile) return;
      const onKey = (e) => {
        if (e.key === 'Escape' && onOpenChange) onOpenChange(false);
      };
      window.addEventListener('keydown', onKey);
      return () => window.removeEventListener('keydown', onKey);
    }, [open, isMobile, onOpenChange]);

    const drawerHidden = isMobile && !open;

    return (
      <SidebarCollapsedContext.Provider value={collapsed}>
        <>
          <div
            aria-hidden
            onClick={() => onOpenChange && onOpenChange(false)}
            className={cn('fixed inset-0 z-65 bg-black/40 lg:hidden', open ? 'block' : 'hidden')}
          />
          <aside
            role={isMobile ? 'dialog' : undefined}
            aria-modal={isMobile ? true : undefined}
            aria-label={isMobile ? 'Navigation menu' : undefined}
            aria-hidden={drawerHidden ? true : undefined}
            inert={drawerHidden ? '' : undefined}
            className={cn(
              'flex h-full flex-col border-r border-border-subtle bg-surface-sidebar px-3 py-3.5',
              'sticky top-0 self-start lg:z-10 max-lg:fixed max-lg:left-0 max-lg:top-0 max-lg:z-70 max-lg:shadow-2xl',
              'max-lg:transition-transform max-lg:duration-200',
              open ? 'max-lg:translate-x-0' : 'max-lg:-translate-x-full',
              collapsed ? 'w-sidebar lg:w-16' : 'w-sidebar',
              className,
            )}
          >
            {logo && (
              <div
                className={cn(
                  'ml-[9px] mb-3 mt-2.5 flex h-[30px] items-center justify-between',
                  logoClassName,
                )}
              >
                <span className="flex items-center">
                  <span className={cn(collapsed && 'lg:hidden')}>{logo}</span>
                  {collapsed && (
                    <span className="hidden lg:block text-text-primary">{logoMark ?? logo}</span>
                  )}
                </span>
                {onCollapsedChange && (
                  <Button
                    variant="quiet"
                    size="xs"
                    aria-label="Collapse sidebar"
                    onClick={() => onCollapsedChange(true)}
                    className={cn('size-7 p-0', collapsed ? 'hidden' : 'hidden lg:flex')}
                  >
                    <G.PanelCollapseIcon className="size-4" />
                  </Button>
                )}
              </div>
            )}
            <div className="-mx-3 mb-2 h-px bg-border-subtle" />
            {onCollapsedChange && collapsed && (
              <Button
                variant="quiet"
                size="xs"
                aria-label="Expand sidebar"
                onClick={() => onCollapsedChange(false)}
                className="hidden lg:flex mb-2 mx-auto size-7 p-0"
              >
                <G.PanelExpandIcon className="size-4" />
              </Button>
            )}
            {accountSwitcher && <div className="mb-2.5">{accountSwitcher}</div>}
            <div className="relative flex min-h-0 flex-1 flex-col">
              <nav
                ref={navRef}
                className="flex min-h-0 flex-1 flex-col gap-px overflow-y-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"
              >
                {nav.map((section, i) => (
                  <div key={section.label ?? i} className={i > 0 ? 'mt-3.5' : undefined}>
                    <NavSection section={section} renderLink={renderLink} collapsed={collapsed} />
                  </div>
                ))}
              </nav>
              {showGradient && (
                <div className="pointer-events-none absolute inset-x-0 bottom-0 h-8 bg-linear-to-t from-surface-sidebar to-transparent" />
              )}
            </div>
            {userMenu && (
              <div className="-mx-3 mt-2.5 border-t border-border-subtle px-3 pt-2.5">{userMenu}</div>
            )}
          </aside>
        </>
      </SidebarCollapsedContext.Provider>
    );
  }

  /* sidebar-brand */
  function SidebarBrand({ badge, className }) {
    return (
      <span className={cn('flex items-center gap-2.5 text-text-primary', className)}>
        <TrayoWordmark className="h-6 w-auto" />
        {badge}
      </span>
    );
  }

  /* sidebar-tenant-row */
  function tenantInitials(name) {
    return name
      .split(' ')
      .map((word) => word[0])
      .filter(Boolean)
      .slice(0, 2)
      .join('')
      .toUpperCase();
  }

  const SidebarTenantRow = forwardRef(function SidebarTenantRow(
    { name, domain, logoUrl, interactive = false, className, ...props },
    ref,
  ) {
    const collapsed = useSidebarCollapsed();
    const rowClassName = cn(
      'flex w-full items-center gap-2.5 rounded-lg px-2 py-1.5 text-left text-text-primary',
      interactive && 'cursor-pointer hover:bg-sidebar-hover',
      collapsed && 'lg:justify-center lg:px-0',
      className,
    );
    const content = (
      <>
        <CompanyLogo
          domain={domain}
          logoUrl={logoUrl}
          name={name}
          className="h-6 w-6 shrink-0 rounded-xs border border-border-subtle bg-white object-cover"
          fallbackClassName="flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-xs bg-accent-brand text-caption font-bold leading-none text-text-inverse"
          fallbackText={tenantInitials(name)}
        />
        <span className={cn('min-w-0 flex-1 truncate text-sm font-semibold', collapsed && 'lg:hidden')}>
          {name}
        </span>
        {interactive && (
          <G.ChevronsUpDown
            size={14}
            aria-hidden
            className={cn('shrink-0 text-text-muted', collapsed && 'lg:hidden')}
          />
        )}
      </>
    );
    if (!interactive) {
      return <div className={rowClassName}>{content}</div>;
    }
    return (
      <button type="button" ref={ref} className={rowClassName} {...props}>
        {content}
      </button>
    );
  });

  /* ---------- DeveloperBar (components/DeveloperBar.tsx) ----------
   * The build-less skeleton has no dev server / git-branch endpoint; the
   * production behavior (`!isDev && !isPreview → null`) is preserved. */
  function DeveloperBar() {
    return null;
  }

  /* ---------- feature-flag keys (packages/feature-flags) ---------- */
  const HOME_REDESIGN_FLAG = 'home-redesign-enabled';
  const SEQUENCE_EMAIL_CONTEXT_FLAG = 'sequence-email-context-enabled';
  const SEQUENCE_XRAY_FLAG = 'sequence-xray-enabled';

  Object.assign(T.UI, {
    TrayoWordmark,
    TrayoLogoMark,
    Logo,
    SidebarCollapsedContext,
    useSidebarCollapsed,
    SIDEBAR_MOBILE_MEDIA,
    useSidebarMobile,
    SidebarTrigger,
    SidebarTriggerProvider,
    useSidebarTrigger,
    MobileSidebarTrigger,
    NavItem,
    NavSection,
    AppSidebar,
    SidebarBrand,
    SidebarTenantRow,
    DeveloperBar,
    HOME_REDESIGN_FLAG,
    SEQUENCE_EMAIL_CONTEXT_FLAG,
    SEQUENCE_XRAY_FLAG,
  });

  /* ======================================================================
   * features/run-monitor — provider + popup, with the Apollo stats hook
   * stubbed (stats: null) and workflow jobs fed from a local simulation
   * store instead of the `myWorkflowJobs` poll.
   * ==================================================================== */

  const WORKFLOW_JOB_STARTED_EVENT = 'trayo:workflow-job-started';
  const WORKFLOW_JOB_COMPLETED_EVENT = 'trayo:workflow-job-completed';

  /* dismissed-workflow-jobs.ts */
  const DISMISSED_KEY = 'trayo.dismissed-workflow-jobs';
  function readDismissedRaw() {
    try {
      const raw = sessionStorage.getItem(DISMISSED_KEY);
      if (!raw) return [];
      const parsed = JSON.parse(raw);
      if (!Array.isArray(parsed)) return [];
      return parsed.filter((v) => typeof v === 'string' && v.length > 0);
    } catch {
      return [];
    }
  }
  const loadDismissedWorkflowJobScopeKeys = () => new Set(readDismissedRaw());
  function rememberDismissedWorkflowJobScopeKey(scopeKey) {
    const next = new Set(readDismissedRaw());
    next.add(scopeKey);
    sessionStorage.setItem(DISMISSED_KEY, JSON.stringify([...next]));
  }

  function scopeKey(scope) {
    switch (scope.kind) {
      case 'batch':
        return `batch:${scope.batchId}`;
      case 'execution':
        return `execution:${scope.executionId}`;
      case 'workflow-job':
        return `workflow-job:${scope.workflowJobId}`;
    }
  }
  const isTerminalStatus = (status) =>
    status === 'completed' || status === 'failed' || status === 'cancelled';
  function sameScope(a, b) {
    if (a.kind === 'batch' && b.kind === 'batch') return a.batchId === b.batchId;
    if (a.kind === 'execution' && b.kind === 'execution') return a.executionId === b.executionId;
    return false;
  }

  const RunMonitorContext = createContext(null);
  function useRunMonitor() {
    const context = useContext(RunMonitorContext);
    if (!context) {
      throw new Error('useRunMonitor must be used within RunMonitorProvider');
    }
    return context;
  }

  function RunMonitorProvider({ children, renderSessionExtras }) {
    const [sessions, setSessions] = useState([]);
    const dismissedScopeKeys = useRef(loadDismissedWorkflowJobScopeKeys());

    const addSession = useCallback((session) => {
      const id = `rm-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
      setSessions((prev) => {
        const existing = prev.find((s) => !s.completedAt && sameScope(s.scope, session.scope));
        if (existing) return prev;
        return [{ ...session, id, expanded: true }, ...prev];
      });
    }, []);

    const removeSession = useCallback((id) => {
      setSessions((prev) => {
        const target = prev.find((s) => s.id === id);
        if (target && target.kind === 'workflow-job') {
          const key = scopeKey(target.scope);
          dismissedScopeKeys.current.add(key);
          rememberDismissedWorkflowJobScopeKey(key);
        }
        return prev.filter((s) => s.id !== id);
      });
    }, []);

    const toggleExpanded = useCallback((id) => {
      setSessions((prev) => prev.map((s) => (s.id === id ? { ...s, expanded: !s.expanded } : s)));
    }, []);

    const markCompleted = useCallback((id) => {
      setSessions((prev) =>
        prev.map((s) =>
          s.id === id && !s.completedAt ? { ...s, completedAt: new Date().toISOString() } : s,
        ),
      );
    }, []);

    const syncWorkflowJobs = useCallback((inputs) => {
      setSessions((prev) => {
        const dismissed = dismissedScopeKeys.current;
        const liveByScope = new Map();
        for (const i of inputs) {
          if (!dismissed.has(scopeKey(i.scope))) liveByScope.set(scopeKey(i.scope), i);
        }
        const merge = (input, existing) => {
          const next = {
            ...input,
            id: existing ? existing.id : `rm-wfjob-${input.scope.workflowJobId}`,
            expanded: existing ? existing.expanded : true,
            completedAt: isTerminalStatus(input.status)
              ? ((existing && existing.completedAt) ?? new Date().toISOString())
              : undefined,
          };
          if (
            existing &&
            existing.status === next.status &&
            existing.data === next.data &&
            existing.errorMessage === next.errorMessage &&
            existing.completedAt === next.completedAt &&
            existing.expanded === next.expanded &&
            existing.triggeredAt === next.triggeredAt
          ) {
            return existing;
          }
          return next;
        };
        const seen = new Set();
        const updated = [];
        for (const s of prev) {
          if (s.kind !== 'workflow-job') {
            updated.push(s);
            continue;
          }
          const key = scopeKey(s.scope);
          const input = liveByScope.get(key);
          if (!input) continue;
          seen.add(key);
          updated.push(merge(input, s));
        }
        const fresh = [];
        for (const i of inputs) {
          const key = scopeKey(i.scope);
          if (liveByScope.has(key) && !seen.has(key)) {
            seen.add(key);
            fresh.push(merge(i, undefined));
          }
        }
        if (fresh.length > 0) return [...fresh, ...updated];
        const unchanged = updated.length === prev.length && updated.every((s, i) => s === prev[i]);
        return unchanged ? prev : updated;
      });
    }, []);

    return (
      <RunMonitorContext.Provider
        value={{
          sessions,
          addSession,
          removeSession,
          toggleExpanded,
          markCompleted,
          syncWorkflowJobs,
          renderSessionExtras,
        }}
      >
        {children}
      </RunMonitorContext.Provider>
    );
  }

  /* use-run-monitor-stats — Apollo poll stubbed out for the skeleton. */
  function useRunMonitorStats() {
    return { stats: null, completed: false, reason: undefined };
  }

  /* ---------- workflow-job-view.ts helpers ---------- */
  function readProgress(data) {
    const p = data && data.progress;
    if (!p || typeof p !== 'object') return null;
    const { processed, total, label } = p;
    if (typeof processed !== 'number' || typeof total !== 'number') return null;
    return { processed, total, label: typeof label === 'string' ? label : undefined };
  }

  function humanizeStepName(name) {
    const words = name.trim().split(/[-_\s]+/).filter(Boolean);
    if (words.length === 0) return '';
    const phrase = words.join(' ');
    return phrase.charAt(0).toUpperCase() + phrase.slice(1);
  }

  function workflowJobTitle(session) {
    const data = session.data ?? null;
    if (session.jobKind === 'tenant-onboarding') {
      const name = data && data.companyName;
      if (typeof name === 'string' && name.trim()) return `Onboarding ${name.trim()}`;
      return 'Tenant onboarding';
    }
    if (session.jobKind === 'account-create') {
      const name = data && data.accountName;
      if (typeof name === 'string' && name.trim()) return `Setting up ${name.trim()}`;
      return 'Account setup';
    }
    if (session.jobKind === 'account-import') {
      const progress = readProgress(data);
      if (progress && progress.total > 0) {
        const n = progress.total;
        return `Importing ${n} account${n === 1 ? '' : 's'}`;
      }
      return 'Account import';
    }
    if (session.jobKind === 'stakeholder-search') {
      const progress = readProgress(data);
      if (progress && progress.total > 0) {
        const n = progress.total;
        return `Finding contacts for ${n} account${n === 1 ? '' : 's'}`;
      }
      return 'Finding contacts';
    }
    if (session.jobKind === 'timing-score') {
      const progress = readProgress(data);
      if (progress && progress.total > 0) {
        const n = progress.total;
        return `Recalculating ${n} account score${n === 1 ? '' : 's'}`;
      }
      return 'Recalculating scores';
    }
    if (session.jobKind === 'people-import') {
      const progress = readProgress(data);
      if (progress && progress.total > 0) {
        const n = progress.total;
        return `Importing ${n} contact${n === 1 ? '' : 's'}`;
      }
      return 'Importing contacts';
    }
    return session.jobKind.replace(/[-_]/g, ' ').replace(/^\w/, (c) => c.toUpperCase());
  }

  function readImportResult(data) {
    const r = data && data.result;
    if (!r || typeof r !== 'object') return null;
    const { created, reassigned, skipped, failed } = r;
    if (
      typeof created !== 'number' ||
      typeof reassigned !== 'number' ||
      typeof skipped !== 'number' ||
      typeof failed !== 'number'
    ) {
      return null;
    }
    return { created, reassigned, skipped, failed };
  }

  function readStakeholderResult(data) {
    const r = data && data.result;
    if (!r || typeof r !== 'object') return null;
    const { peopleAdded, accountsSearched, invokeFailures } = r;
    if (
      typeof peopleAdded !== 'number' ||
      typeof accountsSearched !== 'number' ||
      typeof invokeFailures !== 'number'
    ) {
      return null;
    }
    return { peopleAdded, accountsSearched, invokeFailures };
  }

  function formatStakeholderResult(result) {
    const people =
      result.peopleAdded === 0 ? 'No contacts found' : `+${result.peopleAdded} contacts added`;
    if (result.invokeFailures <= 0) return people;
    return `${people} · ${result.invokeFailures} account${result.invokeFailures === 1 ? '' : 's'} failed`;
  }

  function readPeopleImportResult(data) {
    const r = data && data.result;
    if (!r || typeof r !== 'object') return null;
    const { created, updated, skipped, failed, unassigned, cappedContacts, inaccessibleContacts } = r;
    if (
      typeof created !== 'number' ||
      typeof updated !== 'number' ||
      typeof skipped !== 'number' ||
      typeof failed !== 'number'
    ) {
      return null;
    }
    return {
      created,
      updated,
      skipped,
      failed,
      unassigned: typeof unassigned === 'number' ? unassigned : 0,
      cappedContacts: typeof cappedContacts === 'number' ? cappedContacts : 0,
      inaccessibleContacts:
        typeof inaccessibleContacts === 'number' ? inaccessibleContacts : 0,
    };
  }

  function formatPeopleImportResult(result) {
    const parts = [
      result.created > 0 ? `${result.created} created` : null,
      result.updated > 0 ? `${result.updated} updated` : null,
      result.skipped > 0 ? `${result.skipped} skipped` : null,
      result.failed > 0 ? `${result.failed} failed` : null,
    ].filter(Boolean);
    let base = parts.length > 0 ? parts.join(' · ') : 'No changes';
    if (result.unassigned > 0) {
      base = `${base} · ${result.unassigned} unassigned (company lookup failed)`;
    }
    if (result.inaccessibleContacts > 0) {
      base = `${base} · ${result.inaccessibleContacts} on a teammate's account — ask an owner to add you`;
    }
    if (result.cappedContacts > 0) {
      return `${base} · ${result.cappedContacts} contact${
        result.cappedContacts === 1 ? '' : 's'
      } skipped · account limit reached`;
    }
    return base;
  }

  function formatImportResult(result) {
    const parts = [
      result.created > 0 ? `${result.created} created` : null,
      result.reassigned > 0 ? `${result.reassigned} reassigned` : null,
      result.skipped > 0 ? `${result.skipped} skipped` : null,
      result.failed > 0 ? `${result.failed} failed` : null,
    ].filter(Boolean);
    return parts.length > 0 ? parts.join(' · ') : 'No changes';
  }

  function readRunningStepName(data) {
    const steps = data && data.steps;
    if (!Array.isArray(steps)) return undefined;
    const running = steps.find(
      (s) => !!s && typeof s === 'object' && typeof s.name === 'string' && s.status === 'running',
    );
    return running ? running.name : undefined;
  }

  const EXPECTED_ONBOARDING_STEPS = 33;
  function readOnboardingStepFraction(data) {
    const steps = data && data.steps;
    if (!Array.isArray(steps) || steps.length === 0) return null;
    const done = steps.filter(
      (s) => !!s && typeof s === 'object' && (s.status === 'completed' || s.status === 'skipped'),
    ).length;
    return Math.max(0, Math.min(done / EXPECTED_ONBOARDING_STEPS, 0.95));
  }

  function workflowJobFlags(session) {
    const { status, jobKind } = session;
    const isActive = status === 'pending' || status === 'running';
    const isCompleted = status === 'completed';
    const hardFailed = status === 'failed' || status === 'cancelled';
    const progress = readProgress(session.data);
    const importResult = jobKind === 'account-import' ? readImportResult(session.data) : null;
    const stakeholderResult =
      jobKind === 'stakeholder-search' ? readStakeholderResult(session.data) : null;
    const peopleImportResult =
      jobKind === 'people-import' ? readPeopleImportResult(session.data) : null;

    const rollup = peopleImportResult
      ? {
          failed: peopleImportResult.failed,
          warned: peopleImportResult.unassigned + peopleImportResult.inaccessibleContacts,
          total:
            peopleImportResult.created +
            peopleImportResult.updated +
            peopleImportResult.skipped +
            peopleImportResult.failed,
        }
      : importResult
        ? {
            failed: importResult.failed,
            warned: 0,
            total:
              importResult.created +
              importResult.reassigned +
              importResult.skipped +
              importResult.failed,
          }
        : null;
    const allFailed = isCompleted && !!rollup && rollup.total > 0 && rollup.failed >= rollup.total;
    const partial = isCompleted && !!rollup && !allFailed && (rollup.failed > 0 || rollup.warned > 0);
    const failed = hardFailed || allFailed;
    const succeeded = isCompleted && !failed && !partial;

    const onboardingFraction =
      jobKind === 'tenant-onboarding' ? readOnboardingStepFraction(session.data) : null;

    let percent = 0;
    if (progress && progress.total > 0) {
      const raw = Math.floor((progress.processed / progress.total) * 100);
      percent = isCompleted ? raw : Math.min(99, raw);
    } else if (onboardingFraction != null) {
      percent = isCompleted ? 100 : Math.min(99, Math.floor(onboardingFraction * 100));
    } else if (isCompleted) {
      percent = 100;
    }

    const runningStep = readRunningStepName(session.data);
    const runningStepLabel = runningStep ? humanizeStepName(runningStep) : undefined;

    const statusLabel = hardFailed
      ? status === 'cancelled'
        ? 'Cancelled'
        : 'Failed'
      : isCompleted && importResult
        ? formatImportResult(importResult)
        : isCompleted && stakeholderResult
          ? formatStakeholderResult(stakeholderResult)
          : isCompleted && peopleImportResult
            ? formatPeopleImportResult(peopleImportResult)
            : isActive && runningStepLabel
              ? runningStepLabel
              : (progress && progress.label) ??
                (isActive ? (status === 'pending' ? 'Queued' : 'Working…') : 'Done');

    return { isActive, succeeded, failed, partial, percent, statusLabel };
  }

  /* ---------- workflow-job-steps.tsx ---------- */
  function readSteps(data) {
    const steps = data && data.steps;
    if (!Array.isArray(steps)) return [];
    return steps.filter((s) => !!s && typeof s === 'object' && typeof s.name === 'string');
  }

  function WorkflowJobSteps({ session }) {
    const steps = readSteps(session.data);
    if (steps.length === 0) return null;
    return (
      <ul className="space-y-1.5 border-t px-3 py-2.5">
        {steps.map((step, i) => (
          <li key={`${step.name}-${i}`} className="flex items-center gap-2 text-xs">
            {step.status === 'running' ? (
              <G.Loader2 size={12} className="shrink-0 animate-spin text-blue-500" />
            ) : step.status === 'completed' ? (
              <G.Check size={12} className="shrink-0 text-green-500" />
            ) : step.status === 'skipped' ? (
              <G.Minus size={12} className="text-muted-foreground shrink-0" />
            ) : (
              <G.X size={12} className="shrink-0 text-red-500" />
            )}
            <span
              className={cn(
                'truncate',
                step.status === 'running' ? 'text-foreground' : 'text-muted-foreground',
              )}
            >
              {step.name}
            </span>
          </li>
        ))}
      </ul>
    );
  }

  /* ---------- run-monitor-card.tsx ---------- */
  const fmtNum = (n) => n.toLocaleString();

  function formatElapsed(ms) {
    const s = Math.floor(ms / 1000);
    const m = Math.floor(s / 60);
    const h = Math.floor(m / 60);
    if (h > 0) return `${h}:${String(m % 60).padStart(2, '0')}:${String(s % 60).padStart(2, '0')}`;
    return `${m}:${String(s % 60).padStart(2, '0')}`;
  }

  function useElapsedTimer(triggeredAt, completedAt) {
    const frozenElapsed = completedAt
      ? new Date(completedAt).getTime() - new Date(triggeredAt).getTime()
      : null;
    const [liveElapsed, setLiveElapsed] = useState(
      () => frozenElapsed ?? Date.now() - new Date(triggeredAt).getTime(),
    );
    useEffect(() => {
      if (frozenElapsed !== null) return;
      const start = new Date(triggeredAt).getTime();
      const tick = () => setLiveElapsed(Date.now() - start);
      tick();
      const interval = setInterval(tick, 1000);
      return () => clearInterval(interval);
    }, [triggeredAt, frozenElapsed]);
    return frozenElapsed ?? liveElapsed;
  }

  function MonitorCardHeader({ elapsed, onCollapse, onDismiss, children }) {
    return (
      <div className="flex items-center border-b">
        <button
          type="button"
          onClick={onCollapse}
          aria-label="Collapse"
          className="flex min-w-0 flex-1 cursor-pointer items-center justify-between gap-2 px-3 py-2 text-left transition-colors hover:bg-white/5"
        >
          <div className="flex min-w-0 items-center gap-2 overflow-hidden">{children}</div>
          <div className="flex shrink-0 items-center gap-1">
            <span className="text-muted-foreground whitespace-nowrap font-mono text-xs">
              {formatElapsed(elapsed)}
            </span>
            <G.ChevronDown size={14} className="text-muted-foreground" />
          </div>
        </button>
        <button
          type="button"
          onClick={onDismiss}
          aria-label="Dismiss"
          className="text-muted-foreground hover:text-foreground shrink-0 rounded p-2 pr-3"
        >
          <G.X size={14} />
        </button>
      </div>
    );
  }

  function BatchIdBadge({ batchId }) {
    const [copied, setCopied] = useState(false);
    const handleCopy = useCallback(() => {
      navigator.clipboard.writeText(batchId);
      setCopied(true);
      setTimeout(() => setCopied(false), 1500);
    }, [batchId]);
    const short = batchId.length > 8 ? batchId.slice(0, 8) : batchId;
    return (
      <button
        type="button"
        onClick={handleCopy}
        title={`Copy batch ID: ${batchId}`}
        className="text-muted-foreground hover:text-foreground inline-flex items-center gap-0.5 rounded px-1 py-0.5 font-mono transition-colors hover:bg-white/5"
      >
        {short}
        {copied ? <G.Check size={10} className="text-green-500" /> : <G.Copy size={10} />}
      </button>
    );
  }

  function WorkflowJobCard({ session, elapsed, onCollapse, onDismiss, extrasSlot }) {
    const { isActive, succeeded, failed, partial, percent, statusLabel } = workflowJobFlags(session);
    const progress = readProgress(session.data);
    const title = workflowJobTitle(session);
    return (
      <div
        className={cn(
          'w-80 overflow-hidden rounded-lg border border-border bg-surface-well shadow-2xl shadow-black/40 ring-1 ring-white/6 transition-colors',
          succeeded && 'border-green-500/40',
          partial && 'border-amber-500/40',
          failed && 'border-red-500/40',
        )}
      >
        <MonitorCardHeader elapsed={elapsed} onCollapse={onCollapse} onDismiss={onDismiss}>
          {isActive ? (
            <G.Loader2 className="shrink-0 animate-spin text-accent-text" />
          ) : succeeded ? (
            <G.CheckCircle2 className="shrink-0 text-green-500" />
          ) : partial ? (
            <G.AlertCircle className="shrink-0 text-amber-500" />
          ) : (
            <G.XCircle className="shrink-0 text-red-500" />
          )}
          <span className="truncate text-sm font-medium">{title}</span>
        </MonitorCardHeader>
        <div className="space-y-1.5 px-3 py-2.5">
          <div className="flex items-center justify-between">
            <span className="text-xs font-medium">{statusLabel}</span>
            {progress && progress.total > 0 && (
              <span className="text-muted-foreground text-xs tabular-nums">
                {fmtNum(progress.processed)} / {fmtNum(progress.total)}
              </span>
            )}
          </div>
          {progress && progress.total > 0 && (
            <Progress
              aria-label={statusLabel || 'Job progress'}
              value={percent}
              max={100}
              className={cn(
                'h-1.5 bg-muted-foreground/15',
                isActive && '[&>div]:bg-blue-500 progress-active',
                succeeded && '[&>div]:bg-green-500',
                partial && '[&>div]:bg-amber-500',
                failed && '[&>div]:bg-red-500',
              )}
            />
          )}
          {failed && session.errorMessage && (
            <p className="line-clamp-2 text-xs text-red-500/90">{session.errorMessage}</p>
          )}
        </div>
        {extrasSlot}
      </div>
    );
  }

  function RunMonitorCard({ session, stats, completionReason, onCollapse, onDismiss, extrasSlot }) {
    const elapsed = useElapsedTimer(session.triggeredAt, session.completedAt);
    if (session.kind === 'workflow-job') {
      return (
        <WorkflowJobCard
          session={session}
          elapsed={elapsed}
          onCollapse={onCollapse}
          onDismiss={onDismiss}
          extrasSlot={extrasSlot}
        />
      );
    }
    const disc = stats && stats.discoveries;
    const events = stats && stats.events;
    const discTotal = disc
      ? disc.pending + disc.running + disc.completed + disc.failed + disc.skipped
      : 0;
    const discMax = discTotal || (session.kind === 'discovery' ? session.discoveriesTriggered : 0);
    const discDone = disc ? disc.completed + disc.failed + disc.skipped : 0;
    const discActive = disc ? disc.pending + disc.running > 0 : !session.completedAt;
    const hasFailed = disc ? disc.failed > 0 : false;
    const eventsTotal = events
      ? events.pending + events.running + events.completed + events.rejected
      : 0;
    const eventsDone = events ? events.completed + events.rejected : 0;
    const eventsActive = events ? events.pending + events.running > 0 : false;
    const eventsAwaitingMore = discActive && !eventsActive && eventsTotal > 0;
    const eventsProgress =
      eventsTotal > 0
        ? eventsAwaitingMore
          ? Math.min(Math.round((eventsDone / eventsTotal) * 100), 90)
          : Math.round((eventsDone / eventsTotal) * 100)
        : 0;
    const isActive = session.completedAt ? false : discActive || eventsActive;
    const isDone = session.completedAt ? true : !isActive && discTotal > 0;
    const isEmptyScope = completionReason === 'empty-scope';
    const isPreparing = stats === null && !session.completedAt;

    return (
      <div
        className={cn(
          'w-80 overflow-hidden rounded-lg border border-border bg-surface-well shadow-2xl shadow-black/40 ring-1 ring-white/6 transition-colors',
          isDone && !hasFailed && 'border-green-500/40',
          isDone && hasFailed && 'border-amber-500/40',
        )}
      >
        <MonitorCardHeader elapsed={elapsed} onCollapse={onCollapse} onDismiss={onDismiss}>
          {session.kind === 'workflow' ? (
            <G.Workflow className="shrink-0 text-blue-400" />
          ) : isDone && !hasFailed ? (
            <G.CheckCircle2 className="shrink-0 text-green-500" />
          ) : isDone && hasFailed ? (
            <G.AlertCircle className="shrink-0 text-amber-500" />
          ) : session.tenantLogoUrl ? (
            <img src={session.tenantLogoUrl} alt="" className="h-4 w-4 shrink-0 rounded" />
          ) : (
            <div className="bg-muted flex h-4 w-4 shrink-0 items-center justify-center rounded text-[9px] font-bold">
              {session.tenantName.charAt(0).toUpperCase()}
            </div>
          )}
          <span className="truncate text-sm font-medium">
            {session.kind === 'discovery' ? session.tenantName : session.workflowName}
          </span>
        </MonitorCardHeader>

        {session.kind === 'discovery' && (
          <div className="text-muted-foreground flex items-center justify-between border-b px-3 py-1.5 text-[11px]">
            <span>
              {fmtNum(session.accountCount)} account{session.accountCount !== 1 ? 's' : ''}
              {' · '}
              {session.signalTypes
                .map((t) => (t === 'news' ? 'public' : t === 'job_change' ? 'career' : t))
                .join(', ')}
            </span>
            <BatchIdBadge batchId={session.scope.batchId} />
          </div>
        )}

        {isEmptyScope ? (
          <div className="px-3 py-3">
            <p className="text-muted-foreground text-xs">
              Nothing to enrich — no matching accounts or events.
            </p>
          </div>
        ) : isPreparing ? (
          <div className="px-3 py-3">
            <p className="text-muted-foreground text-xs">Preparing run…</p>
          </div>
        ) : (
          <>
            <div className="space-y-1.5 px-3 py-2.5">
              <div className="flex items-center justify-between">
                <span className="text-xs font-medium">
                  Discoveries
                  {discMax > 0 && (
                    <span className="text-muted-foreground ml-1 font-normal">{fmtNum(discMax)}</span>
                  )}
                </span>
                <span className="text-muted-foreground text-xs">
                  {discMax > 0 ? `${Math.round((discDone / discMax) * 100)}%` : ''}
                </span>
              </div>
              <Progress
                aria-label="Discoveries progress"
                value={discDone}
                max={discMax || 1}
                className={cn(
                  'h-1.5 bg-muted-foreground/15',
                  !discActive && !hasFailed && '[&>div]:bg-green-500',
                  hasFailed && '[&>div]:bg-amber-500',
                  discActive && '[&>div]:bg-blue-500',
                  discActive && 'progress-active',
                )}
              />
              {disc ? (
                <p className="text-xs">
                  <span className="text-green-500">{fmtNum(disc.completed)} done</span>
                  {disc.running > 0 && (
                    <span className="text-accent-text"> · {fmtNum(disc.running)} running</span>
                  )}
                  {disc.pending > 0 && (
                    <span className="text-muted-foreground/60"> · {fmtNum(disc.pending)} queued</span>
                  )}
                  {disc.failed > 0 && (
                    <span className="text-red-500"> · {fmtNum(disc.failed)} failed</span>
                  )}
                  {disc.skipped > 0 && (
                    <span className="text-amber-500/70"> · {fmtNum(disc.skipped)} skipped</span>
                  )}
                </p>
              ) : (
                <p className="text-muted-foreground text-xs">Starting...</p>
              )}
            </div>
            <div className="space-y-1.5 border-t px-3 py-2.5">
              <div className="flex items-center justify-between">
                <span className="text-xs font-medium">
                  Events
                  {eventsTotal > 0 && (
                    <span className="text-muted-foreground ml-1 font-normal">{fmtNum(eventsTotal)}</span>
                  )}
                </span>
                <span className="text-muted-foreground text-xs">
                  {eventsTotal > 0
                    ? eventsAwaitingMore
                      ? `${fmtNum(eventsDone)}/${fmtNum(eventsTotal)}`
                      : `${eventsProgress}%`
                    : ''}
                </span>
              </div>
              {eventsTotal > 0 ? (
                <>
                  <Progress
                    aria-label="Events progress"
                    value={eventsProgress}
                    max={100}
                    className={cn(
                      'h-1.5 bg-muted-foreground/15',
                      !eventsActive && !discActive && '[&>div]:bg-green-500',
                      (eventsActive || discActive) && '[&>div]:bg-blue-500',
                      (eventsActive || discActive) && 'progress-active',
                    )}
                  />
                  <p className="text-xs">
                    <span className="text-green-500">{fmtNum(events.completed)} done</span>
                    {events.rejected > 0 && (
                      <span className="text-amber-500/70"> · {fmtNum(events.rejected)} rejected</span>
                    )}
                    {events.running > 0 && (
                      <span className="text-accent-text"> · {fmtNum(events.running)} running</span>
                    )}
                    {events.pending > 0 && (
                      <span className="text-muted-foreground/60"> · {fmtNum(events.pending)} queued</span>
                    )}
                    {eventsAwaitingMore && (
                      <span className="text-muted-foreground/60"> · waiting for discoveries</span>
                    )}
                  </p>
                </>
              ) : isDone ? (
                <p className="text-muted-foreground text-xs">No events produced</p>
              ) : discActive ? (
                <p className="text-muted-foreground text-xs">Waiting for discoveries...</p>
              ) : (
                <p className="text-muted-foreground text-xs">Processing...</p>
              )}
            </div>
          </>
        )}
        {extrasSlot}
      </div>
    );
  }

  /* ---------- run-monitor-pill.tsx ---------- */
  function WorkflowJobPill({ session, onExpand, onDismiss }) {
    const { isActive, succeeded, failed, partial, percent } = workflowJobFlags(session);
    const title = workflowJobTitle(session);
    const progress = readProgress(session.data);
    const showPercent = progress != null && progress.total > 0;
    return (
      <div
        role="button"
        tabIndex={0}
        onClick={onExpand}
        onKeyDown={(e) => e.key === 'Enter' && onExpand()}
        aria-label={`${title} — click to expand`}
        title={title}
        className={cn(
          'flex cursor-pointer items-center gap-2 rounded-full border border-border bg-surface-well px-3 py-1.5 shadow-2xl shadow-black/40 ring-1 ring-white/6 transition-colors hover:border-accent-line',
          succeeded && 'border-green-500/30',
          partial && 'border-amber-500/30',
          failed && 'border-red-500/30',
        )}
      >
        {isActive ? (
          <G.Loader2 size={14} className="animate-spin text-accent-text" />
        ) : succeeded ? (
          <G.CheckCircle2 size={14} className="text-green-500" />
        ) : partial ? (
          <G.AlertCircle size={14} className="text-amber-500" />
        ) : (
          <G.XCircle size={14} className="text-red-500" />
        )}
        <span className="max-w-40 truncate text-xs font-medium">{title}</span>
        {showPercent && (
          <span className="text-muted-foreground text-xs font-medium tabular-nums">{percent}%</span>
        )}
        <button
          type="button"
          aria-label="Dismiss"
          onClick={(e) => {
            e.stopPropagation();
            onDismiss();
          }}
          className="text-muted-foreground hover:text-foreground -mr-1 rounded p-0.5"
        >
          <G.X size={12} />
        </button>
      </div>
    );
  }

  function RunMonitorPill({ session, stats, completionReason, onExpand, onDismiss }) {
    if (session.kind === 'workflow-job') {
      return <WorkflowJobPill session={session} onExpand={onExpand} onDismiss={onDismiss} />;
    }
    const disc = stats && stats.discoveries;
    const events = stats && stats.events;
    const discTotal = disc
      ? disc.pending + disc.running + disc.completed + disc.failed + disc.skipped
      : 0;
    const discMax = discTotal || (session.kind === 'discovery' ? session.discoveriesTriggered : 0);
    const discDone = disc ? disc.completed + disc.failed + disc.skipped : 0;
    const eventsTotal = events
      ? events.pending + events.running + events.completed + events.rejected
      : 0;
    const eventsDone = events ? events.completed + events.rejected : 0;
    const discActive = disc ? disc.pending + disc.running > 0 : !session.completedAt;
    const eventsActive = events ? events.pending + events.running > 0 : false;
    const isActive = session.completedAt ? false : discActive || eventsActive;
    const hasFailed = disc ? disc.failed > 0 : false;
    const isEmptyScope = completionReason === 'empty-scope';
    const discPct = discMax > 0 ? Math.round((discDone / discMax) * 100) : 0;
    const eventsPct = eventsTotal > 0 ? Math.round((eventsDone / eventsTotal) * 100) : null;
    const label = session.kind === 'workflow' ? session.workflowName : session.tenantName;
    const ariaLabel = `${label} run monitor — click to expand`;
    return (
      <div
        role="button"
        tabIndex={0}
        onClick={onExpand}
        onKeyDown={(e) => e.key === 'Enter' && onExpand()}
        aria-label={ariaLabel}
        title={label}
        className={cn(
          'flex cursor-pointer items-center gap-2 rounded-full border border-border bg-surface-well px-3 py-1.5 shadow-2xl shadow-black/40 ring-1 ring-white/6 transition-colors hover:border-accent-line',
          !isActive && !hasFailed && 'border-green-500/30',
          hasFailed && 'border-amber-500/30',
        )}
      >
        {session.kind === 'workflow' ? (
          isActive ? (
            <G.Workflow size={14} className="animate-pulse text-blue-400" />
          ) : (
            <G.Workflow size={14} className="text-blue-400" />
          )
        ) : isActive ? (
          <G.Loader2 size={14} className="animate-spin text-accent-text" />
        ) : hasFailed ? (
          <G.AlertCircle size={14} className="text-amber-500" />
        ) : (
          <G.Check size={14} className="text-green-500" />
        )}
        {session.kind === 'discovery' && session.tenantLogoUrl ? (
          <img src={session.tenantLogoUrl} alt="" className="h-4 w-4 rounded" />
        ) : session.kind === 'discovery' ? (
          <span className="text-muted-foreground text-xs font-bold">
            {session.tenantName.charAt(0).toUpperCase()}
          </span>
        ) : null}
        <span className="text-xs font-medium tabular-nums">
          {isEmptyScope ? (
            <span className="text-muted-foreground">—</span>
          ) : (
            <>
              {discPct}%
              {eventsPct !== null && (
                <span className="text-muted-foreground font-normal"> · {eventsPct}%</span>
              )}
            </>
          )}
        </span>
        <button
          type="button"
          aria-label="Dismiss"
          onClick={(e) => {
            e.stopPropagation();
            onDismiss();
          }}
          className="text-muted-foreground hover:text-foreground -mr-1 rounded p-0.5"
        >
          <G.X size={12} />
        </button>
      </div>
    );
  }

  /* ---------- run-monitor.tsx ---------- */
  function RunMonitorSessionView({ session }) {
    const { removeSession, toggleExpanded, markCompleted, renderSessionExtras } = useRunMonitor();
    const shouldPoll = !session.completedAt;
    const { stats, completed, reason } = useRunMonitorStats(session.scope, shouldPoll);
    useEffect(() => {
      if (completed && !session.completedAt) {
        markCompleted(session.id);
      }
    }, [completed, session.completedAt, session.id, markCompleted]);
    const extrasSlot = renderSessionExtras ? renderSessionExtras(session) : undefined;
    return session.expanded ? (
      <RunMonitorCard
        session={session}
        stats={stats}
        completionReason={reason}
        onCollapse={() => toggleExpanded(session.id)}
        onDismiss={() => removeSession(session.id)}
        extrasSlot={extrasSlot}
      />
    ) : (
      <RunMonitorPill
        session={session}
        stats={stats}
        completionReason={reason}
        onExpand={() => toggleExpanded(session.id)}
        onDismiss={() => removeSession(session.id)}
      />
    );
  }

  function RunMonitor() {
    const { sessions } = useRunMonitor();
    if (sessions.length === 0) return null;
    return (
      <div
        data-testid="run-monitor"
        className="fixed right-4 bottom-4 z-[99999] flex flex-col-reverse items-end gap-2"
      >
        {sessions.map((session) => (
          <RunMonitorSessionView key={session.id} session={session} />
        ))}
      </div>
    );
  }

  /* ---------- workflow-job simulation store (skeleton-only) ----------
   * Replaces the `myWorkflowJobs` GraphQL poll. Import dialogs (and any
   * T.Data simulation) upsert jobs here; WorkflowJobsFeeder syncs them into
   * the RunMonitorProvider and fires WORKFLOW_JOB_COMPLETED_EVENT. */
  const workflowJobsState = { jobs: new Map(), listeners: new Set(), seq: 0 };
  const WorkflowJobs = {
    list: () => Array.from(workflowJobsState.jobs.values()),
    get: (id) => workflowJobsState.jobs.get(id),
    upsert(job) {
      workflowJobsState.jobs.set(job.id, { ...workflowJobsState.jobs.get(job.id), ...job });
      workflowJobsState.listeners.forEach((fn) => fn());
      return workflowJobsState.jobs.get(job.id);
    },
    subscribe(fn) {
      workflowJobsState.listeners.add(fn);
      return () => workflowJobsState.listeners.delete(fn);
    },
    newId: (kind) => `wfjob-${kind}-${Date.now()}-${++workflowJobsState.seq}`,
  };

  /* Drive a simulated workflow job through steps + progress to completion. */
  function simulateWorkflowJob({
    jobKind,
    total = 10,
    listId,
    steps,
    result,
    durationMs = 2600,
    data: extraData,
  }) {
    const id = WorkflowJobs.newId(jobKind);
    const stepNames = steps || ['Parsing rows', 'Applying rows', 'Building list'];
    const startedAt = new Date().toISOString();
    const mkSteps = (doneCount, runningIndex) =>
      stepNames.map((name, i) => ({
        name,
        status: i < doneCount ? 'completed' : i === runningIndex ? 'running' : 'running',
      }));
    WorkflowJobs.upsert({
      id,
      jobKind,
      status: 'running',
      triggeredAt: startedAt,
      data: {
        ...extraData,
        progress: { processed: 0, total, label: 'Importing…' },
        steps: [{ name: stepNames[0], status: 'running' }],
      },
    });
    const tickMs = Math.max(150, Math.floor(durationMs / (total + 1)));
    let processed = 0;
    const interval = setInterval(() => {
      processed += 1;
      const frac = processed / total;
      const stepIdx = Math.min(stepNames.length - 1, Math.floor(frac * stepNames.length));
      const stepList = stepNames.map((name, i) => ({
        name,
        status: i < stepIdx ? 'completed' : i === stepIdx ? 'running' : 'running',
      }));
      if (processed >= total) {
        clearInterval(interval);
        WorkflowJobs.upsert({
          id,
          jobKind,
          status: 'completed',
          triggeredAt: startedAt,
          data: {
            ...extraData,
            progress: { processed: total, total, label: 'Imported' },
            steps: stepNames.map((name) => ({ name, status: 'completed' })),
            result:
              result ||
              (jobKind === 'people-import'
                ? { created: total, updated: 0, skipped: 0, failed: 0, unassigned: 0, cappedContacts: 0, inaccessibleContacts: 0 }
                : { created: total, reassigned: 0, skipped: 0, failed: 0 }),
            importListId: listId ?? null,
          },
        });
      } else {
        WorkflowJobs.upsert({
          id,
          jobKind,
          status: 'running',
          triggeredAt: startedAt,
          data: {
            ...extraData,
            progress: { processed, total, label: 'Importing…' },
            steps: stepList.filter((s, i) => i <= stepIdx),
          },
        });
      }
    }, tickMs);
    return id;
  }

  /* ---------- workflow-jobs-feeder.tsx (store-backed shim) ---------- */
  function WorkflowJobsFeeder({ kinds, silentKinds = [] }) {
    const { syncWorkflowJobs } = useRunMonitor();
    const prevStatuses = useRef(new Map());
    const kindsKey = kinds.join(',');
    const silentKey = silentKinds.join(',');
    useEffect(() => {
      const kindSet = new Set(kinds);
      const silentSet = new Set(silentKinds);
      const sync = () => {
        const jobs = WorkflowJobs.list().filter((j) => kindSet.has(j.jobKind));
        // Completion events fire for every tracked kind, silent or not.
        for (const j of jobs) {
          const prev = prevStatuses.current.get(j.id);
          if (prev !== j.status && isTerminalStatus(j.status)) {
            const importListId = j.data && j.data.importListId;
            window.dispatchEvent(
              new CustomEvent(WORKFLOW_JOB_COMPLETED_EVENT, {
                detail: {
                  workflowJobId: j.id,
                  jobKind: j.jobKind,
                  status: j.status,
                  importListId: typeof importListId === 'string' ? importListId : null,
                },
              }),
            );
          }
          prevStatuses.current.set(j.id, j.status);
        }
        syncWorkflowJobs(
          jobs
            .filter((j) => !silentSet.has(j.jobKind))
            .map((j) => ({
              kind: 'workflow-job',
              jobKind: j.jobKind,
              status: j.status,
              data: j.data ?? null,
              errorMessage: j.errorMessage ?? null,
              triggeredAt: j.triggeredAt,
              tenantId: '',
              scope: { kind: 'workflow-job', workflowJobId: j.id },
            })),
        );
      };
      sync();
      const unsub = WorkflowJobs.subscribe(sync);
      window.addEventListener(WORKFLOW_JOB_STARTED_EVENT, sync);
      return () => {
        unsub();
        window.removeEventListener(WORKFLOW_JOB_STARTED_EVENT, sync);
      };
    }, [kindsKey, silentKey, syncWorkflowJobs]);
    return null;
  }

  /* ---------- features/imports/use-import-job-progress.ts ---------- */
  function useImportJobRunning(jobId) {
    const subscribe = useCallback(
      (fn) => WorkflowJobs.subscribe(fn),
      [],
    );
    const getSnapshot = useCallback(() => {
      if (!jobId) return false;
      const job = WorkflowJobs.get(jobId);
      if (!job) return false;
      return !isTerminalStatus(job.status);
    }, [jobId]);
    return React.useSyncExternalStore(subscribe, getSnapshot);
  }

  /* ---------- features/accounts/import — ImportJobBody (faithful port,
   * skipped-CSV download reads the simulation store instead of Apollo) ---------- */
  function rowsToCsv(rows, includeUserEmail) {
    const esc = (v) => {
      const s = String(v ?? '');
      return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
    };
    const header = includeUserEmail
      ? ['name', 'url', 'userEmail', 'reason']
      : ['name', 'url', 'reason'];
    const lines = [header.join(',')];
    for (const r of rows) {
      const cells = includeUserEmail
        ? [r.name, r.url, r.userEmail ?? '', r.reason]
        : [r.name, r.url, r.reason];
      lines.push(cells.map(esc).join(','));
    }
    return lines.join('\n');
  }

  function ImportJobBody({ session, onOpenJob, onOpenList }) {
    const [downloading, setDownloading] = useState(false);
    const isPeopleImport = session.jobKind === 'people-import';
    const isActive = session.status === 'pending' || session.status === 'running';
    const data = session.data ?? {};
    const workflowJobId = session.id;
    const result = isPeopleImport ? null : readImportResult(data);
    const peopleResult = isPeopleImport ? readPeopleImportResult(data) : null;
    const skippedCount = ((result && result.skipped) ?? 0) + ((result && result.failed) ?? 0);
    const hasDownloadable = !isPeopleImport && session.status === 'completed' && skippedCount > 0;
    const importListId = typeof data.importListId === 'string' ? data.importListId : null;

    const downloadSkippedCsv = () => {
      setDownloading(true);
      try {
        const job = WorkflowJobs.get(session.scope.workflowJobId) || {};
        const full = job.data && job.data.result;
        const rows = (full && full.rows) || [];
        const skipped = rows.filter((r) => r.status !== 'created' && r.status !== 'reassigned');
        if (skipped.length === 0) return;
        const includeUserEmail = skipped.some((r) => !!r.userEmail);
        const csv = rowsToCsv(
          skipped.map((r) => ({
            name: r.name,
            url: r.url,
            userEmail: r.userEmail ?? undefined,
            reason: r.status,
          })),
          includeUserEmail,
        );
        const blob = new Blob([csv], { type: 'text/csv;charset=utf-8' });
        const blobUrl = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = blobUrl;
        a.download = `account-import-skipped-${new Date().toISOString().slice(0, 10)}.csv`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        setTimeout(() => URL.revokeObjectURL(blobUrl), 1000);
      } finally {
        setDownloading(false);
      }
    };

    return (
      <div className="space-y-0">
        <WorkflowJobSteps session={session} />
        {(isActive || result || peopleResult) && (
          <div className="space-y-1.5 border-t px-3 py-2.5">
            {session.status === 'completed' && result && <ImportResultCounts result={result} />}
            {session.status === 'completed' && peopleResult && (
              <p className="text-xs font-medium" data-testid="import-result-summary">
                {formatPeopleImportResult(peopleResult)}
              </p>
            )}
            <div className="flex flex-wrap items-center gap-x-2 gap-y-1 text-xs">
              {!isActive && (
                <button
                  type="button"
                  onClick={() => onOpenJob && onOpenJob(workflowJobId)}
                  className="text-accent-text hover:underline"
                  data-testid={`account-import-monitor-${workflowJobId}-view`}
                >
                  {isPeopleImport ? 'View contacts' : 'View accounts'}
                </button>
              )}
              {!isActive && importListId && onOpenList && (
                <>
                  <span className="text-text-muted">·</span>
                  <button
                    type="button"
                    onClick={() => onOpenList(importListId)}
                    className="text-accent-text hover:underline"
                    data-testid={`account-import-monitor-${workflowJobId}-list`}
                  >
                    View in Home
                  </button>
                </>
              )}
              {hasDownloadable && (
                <>
                  <span className="text-text-muted">·</span>
                  <button
                    type="button"
                    disabled={downloading}
                    onClick={downloadSkippedCsv}
                    className="inline-flex items-center gap-1 text-accent-text hover:underline disabled:opacity-60"
                    data-testid={`account-import-monitor-${workflowJobId}-download`}
                  >
                    <G.Download size={12} />
                    {downloading ? 'Preparing…' : 'Download skipped CSV'}
                  </button>
                </>
              )}
            </div>
          </div>
        )}
      </div>
    );
  }

  function ImportResultCounts({ result }) {
    const items = [];
    if (result.created > 0) items.push({ text: `${result.created} created`, className: 'text-success-text' });
    if (result.reassigned > 0) items.push({ text: `${result.reassigned} reassigned`, className: 'text-accent-text' });
    if (result.skipped > 0) items.push({ text: `${result.skipped} skipped`, className: 'text-warning-text' });
    if (result.failed > 0) items.push({ text: `${result.failed} failed`, className: 'text-destructive' });
    if (items.length === 0) {
      return (
        <p className="text-text-muted text-xs" data-testid="import-result-summary">
          {formatImportResult(result)}
        </p>
      );
    }
    return (
      <p className="text-xs font-medium" data-testid="import-result-summary">
        {items.map((item, i) => (
          <span key={item.text}>
            {i > 0 ? <span className="text-text-muted"> · </span> : null}
            <span className={item.className}>{item.text}</span>
          </span>
        ))}
      </p>
    );
  }

  /* ---------- CSV import dialogs (simplified functional ports) ----------
   * The real AccountImportDialog / BulkImportPeopleDialog are ~1.6k/0.9k-line
   * CSV pipelines (parse → preview → capacity → apply via GraphQL). The port
   * keeps the same prop surface + the queue/hand-off lifecycle (onBusyChange,
   * onSubmitted, onReady, WORKFLOW_JOB_* events, run-monitor card), driving a
   * simulated workflow job; the body is a reduced paste/pick step. */
  function CsvImportBody({
    kind, // 'account-import' | 'people-import'
    open,
    onOpenChange,
    onSubmitted,
    onReady,
    onBusyChange,
    onEvent,
    showTagInput,
  }) {
    const isPeople = kind === 'people-import';
    const [step, setStep] = useState('pick'); // pick | importing
    const [text, setText] = useState('');
    const [listName, setListName] = useState('');
    const [tag, setTag] = useState('');
    const [jobId, setJobId] = useState(null);
    const importing = step === 'importing';
    const running = useImportJobRunning(importing ? jobId : null);
    const readyFired = useRef(false);

    useEffect(() => {
      if (!open) {
        setStep('pick');
        setText('');
        setListName('');
        setTag('');
        setJobId(null);
        readyFired.current = false;
        if (onBusyChange) onBusyChange(false);
      }
    }, [open]);

    const rows = useMemo(
      () =>
        text
          .split(/\n+/)
          .map((l) => l.trim())
          .filter(Boolean)
          .map((line) => {
            const [name, url] = line.split(',').map((s) => s && s.trim());
            return { name: name || line, url: url || '' };
          }),
      [text],
    );

    /* Job finished → hand off. */
    useEffect(() => {
      if (!importing || !jobId || running || readyFired.current) return;
      readyFired.current = true;
      const job = WorkflowJobs.get(jobId);
      const listId = job && job.data ? job.data.importListId : null;
      if (onBusyChange) onBusyChange(false);
      const done = onReady ? onReady({ jobId, listId: listId ?? undefined }) : undefined;
      Promise.resolve(done).finally(() => onOpenChange(false));
    }, [importing, jobId, running]);

    const submit = () => {
      if (rows.length === 0) return;
      if (onEvent) onEvent({ kind: 'applied', rows: rows.length });
      const listId = `list-import-${Date.now()}`;
      const addList = T.Data && T.Data.createImportedList;
      if (addList) addList({ id: listId, name: listName || null, kind: isPeople ? 'people' : 'accounts', rows });
      const id = simulateWorkflowJob({
        jobKind: kind,
        total: rows.length,
        listId,
        data: { listName: listName || null, tag: tag || null },
      });
      setJobId(id);
      setStep('importing');
      if (onBusyChange) onBusyChange(true);
      window.dispatchEvent(new CustomEvent(WORKFLOW_JOB_STARTED_EVENT));
      if (onSubmitted) onSubmitted({ jobId: id, listId, fileName: undefined });
    };

    const onFile = (file) => {
      const reader = new FileReader();
      reader.onload = () => setText(String(reader.result || ''));
      reader.readAsText(file);
    };

    return (
      <div className="flex min-h-0 flex-1 flex-col gap-4">
        {step === 'pick' ? (
          <>
            <label
              className="flex min-h-28 cursor-pointer flex-col items-center justify-center gap-1.5 rounded-lg border border-dashed border-border-strong bg-surface-well/50 px-4 py-6 text-center text-sm text-text-secondary transition-colors hover:border-accent-line hover:bg-accent-soft"
              onDragOver={(e) => e.preventDefault()}
              onDrop={(e) => {
                e.preventDefault();
                const f = e.dataTransfer.files && e.dataTransfer.files[0];
                if (f) onFile(f);
              }}
            >
              <G.Download className="size-4 text-text-muted" />
              <span>
                Drop a CSV here or <span className="text-accent-text">browse</span>
              </span>
              <span className="text-xs text-text-muted">
                {isPeople ? 'LinkedIn profile URLs, one per row' : 'name and website columns'}
              </span>
              <input
                type="file"
                accept=".csv,text/csv"
                className="sr-only"
                onChange={(e) => {
                  const f = e.target.files && e.target.files[0];
                  if (f) onFile(f);
                }}
              />
            </label>
            <textarea
              value={text}
              onChange={(e) => setText(e.target.value)}
              placeholder={
                isPeople
                  ? 'Jane Cooper, https://linkedin.com/in/janecooper'
                  : 'Acme Inc, acme.com'
              }
              className="min-h-24 flex-1 resize-none rounded-lg border border-input bg-app-raised p-3 text-sm outline-none focus-visible:border-accent-line dark:bg-surface-well"
            />
            <div className="flex flex-wrap items-center gap-2">
              <Input
                value={listName}
                onChange={(e) => setListName(e.target.value)}
                placeholder="List name (optional)"
                className="max-w-56"
              />
              {showTagInput !== false && isPeople && (
                <Input
                  value={tag}
                  onChange={(e) => setTag(e.target.value)}
                  placeholder="Tag all imported (optional)"
                  className="max-w-56"
                />
              )}
              <span className="ml-auto text-xs text-text-muted tabular-nums">
                {rows.length} row{rows.length === 1 ? '' : 's'}
              </span>
            </div>
            <DialogFooter>
              <Button variant="tertiary" onClick={() => onOpenChange(false)}>
                Cancel
              </Button>
              <Button disabled={rows.length === 0} onClick={submit}>
                {isPeople ? 'Import contacts' : 'Import accounts'}
              </Button>
            </DialogFooter>
          </>
        ) : (
          <div className="flex flex-1 flex-col items-center justify-center gap-3 py-8 text-center">
            <G.Loader2 className="size-5 animate-spin text-accent-text" />
            <p className="text-sm font-medium text-text-primary">
              Importing {rows.length} {isPeople ? 'contacts' : 'accounts'}…
            </p>
            <p className="text-xs text-text-muted">
              This keeps running if you continue in the background.
            </p>
            <Button
              variant="tertiary"
              size="sm"
              onClick={() => {
                if (onBusyChange) onBusyChange(false);
                onOpenChange(false);
              }}
            >
              Continue in background
            </Button>
          </div>
        )}
      </div>
    );
  }

  function AccountImportDialog({
    embedded = false,
    open,
    onOpenChange,
    isAdmin,
    onSubmitted,
    onReady,
    onBusyChange,
    onEvent,
  }) {
    const body = (
      <CsvImportBody
        kind="account-import"
        open={open}
        onOpenChange={onOpenChange}
        onSubmitted={onSubmitted}
        onReady={onReady}
        onBusyChange={onBusyChange}
        onEvent={onEvent}
      />
    );
    if (embedded) return body;
    return (
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent size="medium" className="!flex h-[34rem] max-h-[85vh] flex-col overflow-hidden">
          <DialogHeader>
            <DialogTitle>Import CSV</DialogTitle>
            <DialogDescription>Add accounts from a CSV with name and website columns.</DialogDescription>
          </DialogHeader>
          {body}
        </DialogContent>
      </Dialog>
    );
  }

  function BulkImportPeopleDialog({
    embedded = false,
    open,
    onOpenChange,
    tenantId,
    onSubmitted,
    onReady,
    onBusyChange,
    onEvent,
    showTagInput,
  }) {
    const body = (
      <CsvImportBody
        kind="people-import"
        open={open}
        onOpenChange={onOpenChange}
        onSubmitted={onSubmitted}
        onReady={onReady}
        onBusyChange={onBusyChange}
        onEvent={onEvent}
        showTagInput={showTagInput}
      />
    );
    if (embedded) return body;
    return (
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent size="medium" className="!flex h-[34rem] max-h-[85vh] flex-col overflow-hidden">
          <DialogHeader>
            <DialogTitle>Import CSV</DialogTitle>
            <DialogDescription>Add contacts from a CSV of LinkedIn profiles.</DialogDescription>
          </DialogHeader>
          {body}
        </DialogContent>
      </Dialog>
    );
  }

  /* ---------- features/people/AddContactsDialog.tsx (faithful shell) ---------- */
  function AddContactsDialog({
    open,
    onOpenChange,
    onImportSubmitted,
    onImportReady,
    tenantId,
    showImportTagInput,
  }) {
    const [busy, setBusy] = useState(false);
    return (
      <Dialog open={open} onOpenChange={(o) => !busy && onOpenChange(o)}>
        <DialogContent
          size="medium"
          className="!flex h-[34rem] max-h-[85vh] flex-col overflow-hidden"
          data-testid="add-contacts-dialog"
          showCloseButton={!busy}
          onEscapeKeyDown={(e) => busy && e.preventDefault()}
          onPointerDownOutside={(e) => busy && e.preventDefault()}
          onInteractOutside={(e) => busy && e.preventDefault()}
        >
          <DialogHeader>
            <DialogTitle>Import CSV</DialogTitle>
            <DialogDescription>Add contacts from a CSV of LinkedIn profiles.</DialogDescription>
          </DialogHeader>
          <BulkImportPeopleDialog
            embedded
            open={open}
            onOpenChange={onOpenChange}
            tenantId={tenantId}
            onSubmitted={onImportSubmitted}
            onReady={onImportReady}
            onBusyChange={setBusy}
            showTagInput={showImportTagInput}
          />
        </DialogContent>
      </Dialog>
    );
  }

  /* ---------- find-email / find-phone hooks (simulated) ----------
   * Same result surface as the shared Apollo hooks; the lookup resolves via
   * T.Data.resolveFindEmail / resolveFindPhone (when data.jsx provides them)
   * after a short simulated delay, else lands on 'not_found'. */
  function useSimulatedEnrichment(personId, handlers, resolveName, valueKey) {
    const initial = useMemo(() => {
      const lookup = T.Data && T.Data[resolveName];
      const seeded = lookup ? lookup(personId, { peek: true }) : null;
      if (seeded && seeded.initialState) {
        return { state: seeded.initialState, value: seeded[valueKey] ?? null };
      }
      return { state: 'not_requested', value: null };
    }, [personId]);
    const [state, setState] = useState(initial.state);
    const [value, setValue] = useState(initial.value);
    useEffect(() => {
      setState(initial.state);
      setValue(initial.value);
    }, [initial]);
    const timer = useRef(null);
    useEffect(() => () => clearTimeout(timer.current), []);
    const trigger = useCallback(
      async (reason) => {
        if (!personId || state === 'in_progress') return;
        setState('in_progress');
        const startedAt = Date.now();
        const lookup = T.Data && T.Data[resolveName];
        timer.current = setTimeout(() => {
          const resolved = lookup ? lookup(personId, { reason }) : null;
          const found = resolved && resolved[valueKey];
          const outcome = resolved && resolved.outcome ? resolved.outcome : found ? 'found' : 'not_found';
          setValue(found ?? null);
          setState(outcome);
          if (handlers && handlers.onCompleted) {
            handlers.onCompleted(outcome, Date.now() - startedAt, !!found);
          }
        }, 1200 + Math.random() * 900);
      },
      [personId, state, handlers],
    );
    return {
      state,
      [valueKey]: value,
      retryAvailableAt: null,
      trigger,
      canTrigger: state !== 'in_progress' && !!personId,
      loading: false,
    };
  }

  function useFindEmail(personId, handlers = {}) {
    return useSimulatedEnrichment(personId, handlers, 'resolveFindEmail', 'email');
  }
  function useFindPhone(personId, handlers = {}) {
    return useSimulatedEnrichment(personId, handlers, 'resolveFindPhone', 'phone');
  }

  Object.assign(T.UI, {
    WORKFLOW_JOB_STARTED_EVENT,
    WORKFLOW_JOB_COMPLETED_EVENT,
    RunMonitorProvider,
    useRunMonitor,
    RunMonitor,
    RunMonitorCard,
    RunMonitorPill,
    RunMonitorSessionView,
    WorkflowJobsFeeder,
    WorkflowJobSteps,
    workflowJobTitle,
    workflowJobFlags,
    readProgress,
    readImportResult,
    readPeopleImportResult,
    formatImportResult,
    formatPeopleImportResult,
    WorkflowJobs,
    simulateWorkflowJob,
    useImportJobRunning,
    ImportJobBody,
    AccountImportDialog,
    BulkImportPeopleDialog,
    AddContactsDialog,
    useFindEmail,
    useFindPhone,
  });
})();

/* Addendum: shared sidebar-user-menu.tsx + segmented-switch/theme-switch.tsx
 * ports (missed in the first UI pass; layout.jsx consumes both). */
(() => {
  const T = window.T;
  const { useEffect, useRef, useState } = React;
  const cn = T.cn;
  const { SegmentedSwitch } = T.UI;
  const { ChevronUp, Sun, Moon } = T.Icons;
  const useSidebarCollapsed = T.UI.useSidebarCollapsed;

  /* Ported from packages/shared/src/components/segmented-switch/theme-switch.tsx */
  function ThemeSwitch({ value, onChange, className, fullWidth }) {
    return (
      <SegmentedSwitch
        aria-label="Theme"
        value={value}
        onChange={onChange}
        className={className}
        fullWidth={fullWidth}
        options={[
          {
            value: 'light',
            label: (
              <span className="inline-flex items-center gap-1.5 [&>svg]:size-3.5">
                <Sun /> Light
              </span>
            ),
          },
          {
            value: 'dark',
            label: (
              <span className="inline-flex items-center gap-1.5 [&>svg]:size-3.5">
                <Moon /> Dark
              </span>
            ),
          },
        ]}
      />
    );
  }

  const ITEM_CLASS =
    'flex w-full items-center gap-2 px-4 py-3 text-left text-sm text-text-secondary transition-colors hover:bg-surface-row hover:text-text-primary';

  /* Ported from packages/shared/src/components/app-sidebar/sidebar-user-menu.tsx */
  function SidebarUserMenu({
    name,
    role,
    initials,
    avatar,
    active = false,
    title,
    header,
    theme,
    onThemeChange,
    items = [],
    renderMenuLink,
    triggerTestId,
  }) {
    const collapsed = useSidebarCollapsed();
    const [open, setOpen] = useState(false);
    const wrapperRef = useRef(null);

    useEffect(() => {
      if (!open) return;
      const handleClickOutside = (event) => {
        if (wrapperRef.current && !wrapperRef.current.contains(event.target)) {
          setOpen(false);
        }
      };
      const handleEscape = (event) => {
        if (event.key === 'Escape') setOpen(false);
      };
      document.addEventListener('mousedown', handleClickOutside);
      document.addEventListener('keydown', handleEscape);
      return () => {
        document.removeEventListener('mousedown', handleClickOutside);
        document.removeEventListener('keydown', handleEscape);
      };
    }, [open]);

    const close = () => setOpen(false);
    const showThemeBlock = theme != null && onThemeChange != null;

    return (
      <div ref={wrapperRef} className="relative py-3">
        <button
          type="button"
          onClick={() => setOpen((prev) => !prev)}
          aria-haspopup="menu"
          aria-expanded={open}
          data-testid={triggerTestId}
          title={title}
          className={cn(
            'flex w-full cursor-pointer items-center gap-2 rounded-lg px-2 py-2 transition-colors',
            active || open
              ? 'bg-surface-well text-text-primary'
              : 'text-text-secondary hover:bg-surface-well',
            collapsed && 'lg:justify-center',
          )}
        >
          {avatar ?? (
            <div className="flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full bg-primary text-xs font-semibold uppercase text-primary-foreground">
              {initials}
            </div>
          )}
          <div className={cn('min-w-0 flex-1 text-left', collapsed && 'lg:hidden')}>
            <div className="truncate text-sm font-medium text-text-primary">
              {name}
            </div>
            {role && (
              <div className="truncate text-xs text-text-muted">{role}</div>
            )}
          </div>
          {/* Points up when closed to hint that the menu opens upward; flips on
              open so the affordance reads as "this is the active state". */}
          <ChevronUp
            size={16}
            className={cn(
              'flex-shrink-0 text-text-muted transition-transform',
              open && 'rotate-180',
              collapsed && 'lg:hidden',
            )}
          />
        </button>

        {open && (
          <div
            role="menu"
            className={cn(
              'absolute bottom-full mb-2 z-50 overflow-hidden rounded-lg border border-border-subtle bg-surface-card shadow-xl',
              collapsed ? 'left-0 min-w-[220px]' : 'left-0 right-0',
            )}
          >
            {header && (
              <div className="border-b border-border-subtle px-4 py-3">
                {header}
              </div>
            )}
            {showThemeBlock && (
              <div className="border-b border-border-subtle px-4 py-3">
                <div className="mb-2 text-eyebrow">
                  Theme
                </div>
                {/* Theme change does not close the menu, so the user sees the
                    selection land before dismissing. */}
                <ThemeSwitch value={theme} onChange={onThemeChange} fullWidth />
              </div>
            )}
            {items.map((item) => {
              const className = cn(ITEM_CLASS, item.separated && 'border-t border-border-subtle');
              const body = (
                <React.Fragment>
                  {item.icon && (
                    <span className="inline-flex shrink-0">{item.icon}</span>
                  )}
                  <span className="min-w-0 flex-1 truncate">{item.label}</span>
                </React.Fragment>
              );
              if (item.href && renderMenuLink) {
                return (
                  <span key={item.key}>
                    {renderMenuLink({
                      href: item.href,
                      className,
                      role: 'menuitem',
                      onClick: close,
                      'data-testid': item.testId,
                      children: body,
                    })}
                  </span>
                );
              }
              if (item.externalHref) {
                return (
                  <a
                    key={item.key}
                    href={item.externalHref}
                    target={item.target}
                    rel={item.rel}
                    role="menuitem"
                    data-testid={item.testId}
                    onClick={close}
                    className={className}
                  >
                    {body}
                  </a>
                );
              }
              return (
                <button
                  key={item.key}
                  type="button"
                  role="menuitem"
                  data-testid={item.testId}
                  onClick={() => {
                    close();
                    item.onSelect?.();
                  }}
                  className={className}
                >
                  {body}
                </button>
              );
            })}
          </div>
        )}
      </div>
    );
  }

  Object.assign(T.UI, { ThemeSwitch, SidebarUserMenu });
})();
