'use client';

import { useCallback, useEffect, useId, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { useToast } from '@/components/crm/ToastProvider';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import { LpIcon, type LpIconName } from '@/features/list-page/ui/LpIcon';
import { LpModeIcon } from '@/features/list-page/ui/LpModeIcon';
import { LpModal } from '@/features/list-page/ui/LpModal';
import { listTeamOptions } from '@/features/members/api.client';
import { listAllOwners, type Owner } from '@/features/owners/api.client';
import { cn } from '@/lib/utils/cn';
import type { View } from '../types';

/** A view's type in the design: Table, Board, Report (chart), Calendar, Gantt (timeline). */
export type ViewType = 'table' | 'board' | 'chart' | 'calendar' | 'timeline';
export const VIEW_TYPES: Array<{ key: ViewType; label: string; icon: LpIconName }> = [
  { key: 'table', label: 'Table', icon: 'table' },
  { key: 'board', label: 'Board', icon: 'board' },
  { key: 'chart', label: 'Report', icon: 'chart' },
  { key: 'calendar', label: 'Calendar', icon: 'calendar' },
  { key: 'timeline', label: 'Gantt', icon: 'gantt' },
];

/** MT-2: the types a list offers, in the design's order (`types` absent: all of them). */
export const viewTypesOffered = (types?: readonly ViewType[]) =>
  types ? VIEW_TYPES.filter((t) => types.includes(t.key)) : VIEW_TYPES;

/**
 * Private / My team / Everyone. Everyone is the view's `isShared`. My team is the caller's
 * default team on the server with `serverShare` (Contacts, Companies), else kept in this browser.
 */
export type ViewAccess = 'private' | 'team' | 'everyone';

const NAME_MAX = 60;

function ModalButtons({
  cancel = 'Cancel',
  submit,
  tone = 'primary',
  busy,
  onCancel,
  onSubmit,
}: {
  cancel?: string;
  submit: string;
  tone?: 'primary' | 'danger';
  busy?: boolean;
  onCancel: () => void;
  onSubmit: () => void;
}) {
  return (
    <>
      <div className="lp-modal__left" />
      <div className="lp-modal__acts">
        <button type="button" className="lp-btn lp-btn--outline" onClick={onCancel}>
          {cancel}
        </button>
        <button
          type="button"
          className={cn('lp-btn', `lp-btn--${tone}`, busy && 'is-loading')}
          disabled={busy}
          onClick={onSubmit}
        >
          {submit}
        </button>
      </div>
    </>
  );
}

/**
 * The design's view-name dialog (list-page.js `createView` / `renameView`, view-settings.js
 * "Clone to new view"): a name, and optionally the view's layout and who it is shared with.
 * The name is checked when the dialog is submitted, not before.
 */
export function ViewNameModal({
  open,
  title,
  submitLabel = 'Save',
  initialName,
  placeholder,
  layout,
  types,
  share,
  nameTaken,
  onClose,
  onSubmit,
}: {
  open: boolean;
  title: string;
  submitLabel?: string;
  initialName: string;
  placeholder?: string;
  /** Show the Layout choice, starting at this type. */
  layout?: ViewType;
  /** MT-2: the Layout choices the list offers (default: every type). */
  types?: readonly ViewType[];
  /** Show "Shared with", starting at this access. */
  share?: ViewAccess;
  /** Another view already has this name. */
  nameTaken?: (name: string) => boolean;
  onClose: () => void;
  /** False keeps the dialog open (e.g. the API refused the name). */
  onSubmit: (values: { name: string; layout: ViewType; access: ViewAccess }) => Promise<boolean>;
}) {
  const id = useId();
  const [name, setName] = useState(initialName);
  const [type, setType] = useState<ViewType>(layout ?? 'table');
  const [access, setAccess] = useState<ViewAccess>(share ?? 'private');
  const [error, setError] = useState('');
  const [busy, setBusy] = useState(false);
  const inputRef = useRef<HTMLInputElement>(null);
  useEffect(() => {
    if (!open) return;
    setName(initialName);
    setType(layout ?? 'table');
    setAccess(share ?? 'private');
    setError('');
    setBusy(false);
    const t = window.setTimeout(() => inputRef.current?.select(), 30);
    return () => window.clearTimeout(t);
    // Reset only when the dialog opens.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open]);
  const submit = async () => {
    const nm = name.trim();
    const msg = !nm
      ? 'Enter a view name.'
      : nameTaken?.(nm)
        ? 'A view with this name already exists.'
        : '';
    if (msg) {
      setError(msg);
      inputRef.current?.focus();
      return;
    }
    setBusy(true);
    const ok = await onSubmit({ name: nm, layout: type, access });
    setBusy(false);
    if (ok) onClose();
  };
  return (
    <LpModal
      open={open}
      title={title}
      onClose={onClose}
      footer={
        <ModalButtons submit={submitLabel} busy={busy} onCancel={onClose} onSubmit={submit} />
      }
    >
      <div className="lp-field">
        <label htmlFor={`${id}-name`}>View name</label>
        <input
          ref={inputRef}
          id={`${id}-name`}
          className="lp-input"
          maxLength={NAME_MAX}
          placeholder={placeholder}
          value={name}
          aria-invalid={error ? true : undefined}
          aria-describedby={error ? `${id}-err` : undefined}
          onChange={(e) => {
            setName(e.target.value);
            if (error) setError('');
          }}
          onKeyDown={(e) => {
            if (e.key === 'Enter') {
              e.preventDefault();
              void submit();
            }
          }}
        />
        {error ? (
          <span id={`${id}-err`} className="lp-field__err">
            {error}
          </span>
        ) : null}
      </div>
      {layout ? (
        <fieldset className="lp-field">
          <legend>Layout</legend>
          <div className="lp-choice lp-choice--types">
            {viewTypesOffered(types).map((t) => (
              <label key={t.key} className="lp-choice__opt">
                <input
                  type="radio"
                  name={`${id}-layout`}
                  value={t.key}
                  checked={type === t.key}
                  onChange={() => setType(t.key)}
                />
                <LpModeIcon name={t.icon} />
                <span>{t.label}</span>
              </label>
            ))}
          </div>
        </fieldset>
      ) : null}
      {share ? (
        <fieldset className="lp-field">
          <legend>Shared with</legend>
          {(
            [
              ['private', 'Private', 'Only you'],
              ['team', 'My team', ''],
              ['everyone', 'Everyone', ''],
            ] as const
          ).map(([value, label, note]) => (
            <label key={value} className="lp-radio">
              <input
                type="radio"
                name={`${id}-share`}
                value={value}
                checked={access === value}
                onChange={() => setAccess(value)}
              />
              {label}
              {note ? <small className="lp-muted">{note}</small> : null}
            </label>
          ))}
        </fieldset>
      ) : null}
    </LpModal>
  );
}

/** "Delete view?" (list-page.js `deleteView`). */
export function DeleteViewModal({
  view,
  busy,
  onClose,
  onConfirm,
}: {
  view: View | null;
  busy: boolean;
  onClose: () => void;
  onConfirm: () => void;
}) {
  return (
    <LpModal
      open={view !== null}
      title="Delete view?"
      onClose={onClose}
      footer={
        <ModalButtons
          submit="Delete view"
          tone="danger"
          busy={busy}
          onCancel={onClose}
          onSubmit={onConfirm}
        />
      }
    >
      <p>
        Delete <strong>{view?.name}</strong>? This removes the view for everyone it is shared with.
        Records are not deleted.
      </p>
    </LpModal>
  );
}

/** "All <objects> views" (list-page.js `allViews`): search, open / go to, delete your own. */
export function AllViewsModal({
  open,
  plural,
  views,
  selectedId,
  openIds,
  layoutOf,
  createdBy,
  canCreate,
  onClose,
  onOpen,
  onDelete,
  onCreate,
}: {
  open: boolean;
  /** Lowercase plural: "All contacts views". */
  plural: string;
  views: View[];
  selectedId: string | null;
  openIds: Set<string>;
  layoutOf: (view: View) => string;
  createdBy: (view: View) => string;
  canCreate: boolean;
  onClose: () => void;
  onOpen: (view: View) => void;
  onDelete: (view: View) => void;
  onCreate: () => void;
}) {
  const [q, setQ] = useState('');
  useEffect(() => {
    if (open) setQ('');
  }, [open]);
  const list = views.filter((v) => v.name.toLowerCase().includes(q.trim().toLowerCase()));
  return (
    <LpModal
      open={open}
      title={`All ${plural} views`}
      onClose={onClose}
      className="lp-modal--wide"
      footer={
        <>
          <div className="lp-modal__left" />
          <div className="lp-modal__acts">
            <button type="button" className="lp-btn lp-btn--outline" onClick={onClose}>
              Close
            </button>
            {canCreate ? (
              <button type="button" className="lp-btn lp-btn--primary" onClick={onCreate}>
                Create new view
              </button>
            ) : null}
          </div>
        </>
      }
    >
      <label className="lp-search lp-search--sm">
        <LpIcon name="search" />
        <input
          type="search"
          placeholder="Search views"
          aria-label="Search views"
          autoComplete="off"
          value={q}
          onChange={(e) => setQ(e.target.value)}
        />
      </label>
      <div className="lp-allviews">
        {list.length ? (
          <table className="lp-mini">
            <thead>
              <tr>
                <th scope="col">Name</th>
                <th scope="col">Layout</th>
                <th scope="col">Created by</th>
                <th scope="col">
                  <span className="lp-sr">Actions</span>
                </th>
              </tr>
            </thead>
            <tbody>
              {list.map((v) => {
                const current = v.id === selectedId;
                return (
                  <tr key={v.id}>
                    <td>
                      <strong>{v.name}</strong>
                      {current ? (
                        <>
                          {' '}
                          <span className="lp-pill-tag">Current</span>
                        </>
                      ) : null}
                    </td>
                    <td>{layoutOf(v)}</td>
                    <td>{createdBy(v)}</td>
                    <td>
                      <div className="lp-mini__acts">
                        <button
                          type="button"
                          className="lp-btn lp-btn--outline lp-btn--sm"
                          onClick={() => onOpen(v)}
                        >
                          {current ? 'Opened' : openIds.has(v.id) ? 'Go to view' : 'Open'}
                        </button>
                        {v.canEdit && !v.isSystem ? (
                          <button
                            type="button"
                            className="lp-icon-btn lp-icon-btn--sm"
                            aria-label={`Delete ${v.name}`}
                            onClick={() => onDelete(v)}
                          >
                            <LpIcon name="trash" />
                          </button>
                        ) : null}
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        ) : (
          <p className="lp-opt__empty">No views match “{q}”</p>
        )}
      </div>
    </LpModal>
  );
}

/* ------------------------------------------------------------------ sharing */

export type ShareMember = { type: 'user' | 'team'; id: string };

/**
 * The people and teams a view is shared with, kept in this browser: lists without `serverShare`.
 * Contacts and Companies save them on the server and only read this for views saved before S2.
 */
export function useViewMembers(objectType: string) {
  const key = `crm.viewShare.${objectType}`;
  const read = useCallback((): Record<string, ShareMember[]> => {
    try {
      const v = JSON.parse(window.localStorage.getItem(key) ?? '{}') as unknown;
      return v && typeof v === 'object' ? (v as Record<string, ShareMember[]>) : {};
    } catch {
      return {};
    }
  }, [key]);
  const get = useCallback((viewId: string) => read()[viewId] ?? [], [read]);
  const set = useCallback(
    (viewId: string, members: ShareMember[]) => {
      try {
        const all = read();
        all[viewId] = members;
        window.localStorage.setItem(key, JSON.stringify(all));
      } catch {
        /* storage off: members are not kept */
      }
    },
    [key, read],
  );
  return { get, set };
}

function initials(name: string) {
  const p = name.trim().split(/\s+/);
  return (
    ((p[0] ?? '?')[0] ?? '?') + (p.length > 1 ? (p[p.length - 1]![0] ?? '') : '')
  ).toUpperCase();
}

/** A team id (UUID). The browser kept team names before S2. */
const TEAM_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;

const LINK_ACCESS = [
  ['private', 'Private', 'Only you have access to this view.'],
  ['everyone', 'Everyone', 'Everyone on your CRM account can access this view.'],
] as const;

/**
 * HubSpot's "Manage sharing" (components/share-dialog.js): add users and teams, see who has
 * access (the owner first), pick what everyone else with the link gets, copy the link.
 */
export function ShareViewDialog({
  view,
  ownerName,
  initialMembers,
  server = false,
  savedMembers = [],
  onClose,
  onSave,
}: {
  view: View | null;
  ownerName: (userId: string) => string | undefined;
  /** Who the dialog starts with. */
  initialMembers: ShareMember[];
  /**
   * S2 (Contacts, Companies): people and teams are saved on the server, teams by id. The dialog
   * is read-only for anyone who can't change the view, and says when users or teams fail to load.
   * Off: teams by name, kept in this browser, as before.
   */
  server?: boolean;
  /** With `server`: who the view is shared with now, so Save is on when the start differs. */
  savedMembers?: ShareMember[];
  onClose: () => void;
  /** False keeps the dialog open. */
  onSave: (share: { access: 'private' | 'everyone'; members: ShareMember[] }) => Promise<boolean>;
}) {
  const me = useCurrentUser();
  const toast = useToast();
  const open = view !== null;
  const [shown, setShown] = useState(false);
  const [users, setUsers] = useState<Owner[]>([]);
  /** `id` is the team's id with `server`, else its name (what the browser keeps). */
  const [teams, setTeams] = useState<Array<{ id: string; name: string }>>([]);
  const [loadFailed, setLoadFailed] = useState(false);
  /** The teams answered (or failed): until then, team names kept in this browser aren't ids yet. */
  const [teamsReady, setTeamsReady] = useState(false);
  const [access, setAccess] = useState<'private' | 'everyone'>('private');
  const [members, setMembers] = useState<ShareMember[]>([]);
  const [q, setQ] = useState('');
  const [resOpen, setResOpen] = useState(false);
  const [accOpen, setAccOpen] = useState(false);
  const [busy, setBusy] = useState(false);
  const startRef = useRef('');
  const closeRef = useRef(onClose);
  closeRef.current = onClose;
  const qRef = useRef<HTMLInputElement>(null);
  const accRef = useRef<HTMLButtonElement>(null);

  useEffect(() => {
    if (!view) {
      setShown(false);
      return;
    }
    const a = view.isShared || view.isSystem ? 'everyone' : 'private';
    setAccess(a);
    setMembers(initialMembers);
    startRef.current = JSON.stringify({ a, m: server ? savedMembers : initialMembers });
    setQ('');
    setResOpen(false);
    setAccOpen(false);
    setBusy(false);
    setLoadFailed(false);
    setTeamsReady(false);
    // A reply for a dialog since closed or opened for another view is dropped.
    let live = true;
    listAllOwners(false).then(
      (rows) => live && setUsers(rows.slice().sort((x, y) => x.name.localeCompare(y.name))),
      () => {
        if (!live) return;
        setUsers([]);
        setLoadFailed(true);
      },
    );
    listTeamOptions().then(
      (res) => {
        if (!live) return;
        setTeams(res.data.map((t) => ({ id: server ? t.id : t.name, name: t.name })));
        // Members this browser kept before S2 name their team: use its id. "My team" and
        // teams since deleted have none, so they are left out.
        if (server) {
          setMembers((list) =>
            list.flatMap((m) => {
              if (m.type !== 'team' || res.data.some((t) => t.id === m.id)) return [m];
              const byName = res.data.find((t) => t.name === m.id);
              return byName ? [{ type: 'team' as const, id: byName.id }] : [];
            }),
          );
        }
        setTeamsReady(true);
      },
      () => {
        if (!live) return;
        setTeams([]);
        setLoadFailed(true);
        // Team names this browser kept can't be matched to ids now: leave them out.
        if (server) {
          setMembers((list) => list.filter((m) => m.type !== 'team' || TEAM_ID.test(m.id)));
        }
        setTeamsReady(true);
      },
    );
    const opener = document.activeElement as HTMLElement | null;
    const raf = window.requestAnimationFrame(() => setShown(true));
    return () => {
      live = false;
      window.cancelAnimationFrame(raf);
      opener?.focus?.({ preventScroll: true });
    };
    // Reset when another view's dialog opens.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [view?.id]);

  useEffect(() => {
    if (!open) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key !== 'Escape') return;
      e.preventDefault();
      e.stopPropagation();
      if (accOpen) {
        setAccOpen(false);
        accRef.current?.focus();
      } else if (resOpen) {
        setResOpen(false);
        qRef.current?.focus();
      } else closeRef.current();
    };
    document.addEventListener('keydown', onKey, true);
    return () => document.removeEventListener('keydown', onKey, true);
  }, [open, accOpen, resOpen]);

  if (!view || typeof document === 'undefined') return null;

  const ownerId = view.ownerUserId;
  const owner = ownerId
    ? (users.find((u) => u.userId === ownerId) ?? {
        name: ownerName(ownerId) ?? (ownerId === me.user.id ? me.user.name : 'Owner'),
        email: '',
      })
    : null;
  const has = (m: ShareMember) => members.some((x) => x.type === m.type && x.id === m.id);
  const toggle = (m: ShareMember) =>
    setMembers((list) =>
      list.some((x) => x.type === m.type && x.id === m.id)
        ? list.filter((x) => !(x.type === m.type && x.id === m.id))
        : [...list, m],
    );
  const s = q.trim().toLowerCase();
  const userHits = users.filter(
    (u) => u.userId !== ownerId && (!s || `${u.name} ${u.email}`.toLowerCase().includes(s)),
  );
  const teamHits = teams.filter((t) => !s || t.name.toLowerCase().includes(s));
  const teamName = (id: string) => teams.find((t) => t.id === id)?.name ?? (server ? 'Team' : id);
  const dirty = JSON.stringify({ a: access, m: members }) !== startRef.current;
  const link = (() => {
    const u = new URL(window.location.href);
    u.searchParams.set('view', view.id);
    return u.toString();
  })();
  const copy = () => {
    const done = () => toast('Link copied to clipboard');
    if (navigator.clipboard && window.isSecureContext) {
      navigator.clipboard
        .writeText(link)
        .then(done, () => toast('Copy failed - select the address bar to copy the link', 'danger'));
      return;
    }
    const t = document.createElement('textarea');
    t.value = link;
    t.style.position = 'fixed';
    t.style.opacity = '0';
    document.body.appendChild(t);
    t.select();
    try {
      document.execCommand('copy');
      done();
    } catch {
      toast('Copy failed - select the address bar to copy the link', 'danger');
    }
    t.remove();
  };
  const save = async () => {
    if (!dirty || busy) return;
    setBusy(true);
    const ok = await onSave({ access, members });
    setBusy(false);
    if (ok) {
      toast(`Sharing updated for “${view.name}”`);
      onClose();
    }
  };
  const accLabel = LINK_ACCESS.find((x) => x[0] === access)![1];
  const lockAccess = view.isSystem || !view.canEdit;
  /** With `server`, people and teams change only for those who may change the view. */
  const readOnly = server && lockAccess;

  const row = (
    key: string,
    name: string,
    sub: string,
    badge: string | null,
    isOwner: boolean,
    member: ShareMember | null,
    team = false,
  ) => (
    <li key={key} className="cl-share__row">
      <span className="cl-av" aria-hidden>
        {team ? <LpIcon name="team" className="cl-i" /> : initials(name)}
      </span>
      <span className="cl-share__who">
        <span className="cl-share__name">{name}</span>
        <span className="cl-share__email">{sub}</span>
      </span>
      {badge ? <span className={cn('cl-badge', isOwner && 'cl-badge--owner')}>{badge}</span> : null}
      <button
        type="button"
        className="cl-share__rm"
        disabled={isOwner || !member || readOnly}
        title={isOwner ? 'The owner always has access' : undefined}
        aria-label={isOwner ? `${name} is the owner` : `Remove ${name}`}
        onClick={() => member && toggle(member)}
      >
        <LpIcon name="x" className="cl-i" />
      </button>
    </li>
  );

  return createPortal(
    <div
      className={cn('cl-modal-ov', shown && 'is-open')}
      onMouseDown={(e) => {
        if (e.target === e.currentTarget) {
          onClose();
          return;
        }
        const t = e.target as Element;
        if (resOpen && !t.closest('.cl-share__search')) setResOpen(false);
        if (accOpen && !t.closest('.cl-share__acc')) setAccOpen(false);
      }}
    >
      <div className="cl-modal cl-share" role="dialog" aria-modal="true" aria-labelledby="clShT">
        <header className="cl-modal__head">
          <h2 id="clShT">Manage sharing</h2>
          <button type="button" className="cl-x" aria-label="Close" onClick={onClose}>
            <LpIcon name="x" className="cl-i" />
          </button>
        </header>
        <div className="cl-modal__body cl-share__body">
          <p className="cl-sr">Sharing for the view {view.name}</p>
          <div className="cl-share__search">
            <label className="cl-pillsearch">
              <input
                ref={qRef}
                type="text"
                placeholder={
                  !readOnly
                    ? 'Search users and teams'
                    : view.isSystem
                      ? 'Default views are shared with everyone'
                      : 'Only the owner can change sharing'
                }
                aria-label="Search users and teams"
                autoComplete="off"
                role="combobox"
                disabled={readOnly}
                aria-expanded={resOpen}
                aria-controls="clShRes"
                value={q}
                onFocus={() => setResOpen(true)}
                onChange={(e) => {
                  setQ(e.target.value);
                  setResOpen(true);
                }}
              />
              {q ? (
                <button
                  type="button"
                  className="cl-pillsearch__clear"
                  aria-label="Clear search"
                  onClick={() => {
                    setQ('');
                    qRef.current?.focus();
                  }}
                >
                  <LpIcon name="x" className="cl-i" />
                </button>
              ) : (
                <span className="cl-pillsearch__ico">
                  <LpIcon name="search" className="cl-i" />
                </span>
              )}
            </label>
            {resOpen ? (
              <div
                className="cl-share__results"
                id="clShRes"
                role="listbox"
                aria-multiselectable="true"
              >
                {userHits.map((u) => {
                  const m: ShareMember = { type: 'user', id: u.userId };
                  const on = has(m);
                  return (
                    <button
                      key={u.userId}
                      type="button"
                      className="cl-share__opt"
                      role="option"
                      aria-selected={on}
                      onClick={() => toggle(m)}
                    >
                      <span className={cn('cl-cb', on && 'is-on')} aria-hidden>
                        <LpIcon name="check" className="cl-i" />
                      </span>
                      <span className="cl-av" aria-hidden>
                        {initials(u.name)}
                      </span>
                      <span className="cl-share__who">
                        <span className="cl-share__name">{u.name}</span>
                        <span className="cl-share__email">{u.email}</span>
                      </span>
                    </button>
                  );
                })}
                {teamHits.length ? (
                  <>
                    <div className="cl-share__resh" role="presentation">
                      Teams
                    </div>
                    {teamHits.map((t) => {
                      const m: ShareMember = { type: 'team', id: t.id };
                      const on = has(m);
                      return (
                        <button
                          key={t.id}
                          type="button"
                          className="cl-share__opt"
                          role="option"
                          aria-selected={on}
                          onClick={() => toggle(m)}
                        >
                          <span className={cn('cl-cb', on && 'is-on')} aria-hidden>
                            <LpIcon name="check" className="cl-i" />
                          </span>
                          <span className="cl-av" aria-hidden>
                            <LpIcon name="team" className="cl-i" />
                          </span>
                          <span className="cl-share__who">
                            <span className="cl-share__name">{t.name}</span>
                            <span className="cl-share__email">Team</span>
                          </span>
                        </button>
                      );
                    })}
                  </>
                ) : null}
                {server && loadFailed ? (
                  <div className="cl-share__none">Couldn&apos;t load users and teams</div>
                ) : !userHits.length && !teamHits.length ? (
                  <div className="cl-share__none">No users or teams match “{q}”</div>
                ) : null}
              </div>
            ) : null}
          </div>
          <h3 className="cl-share__h">Shared access</h3>
          <ul className="cl-share__list">
            {owner
              ? row('owner', owner.name, owner.email, 'Owner', true, null)
              : row(
                  'default',
                  'Default view',
                  'Built in, everyone has access',
                  'Default',
                  true,
                  null,
                )}
            {members.map((m) => {
              if (m.type === 'team') {
                return row(`t-${m.id}`, teamName(m.id), 'Team', 'Team', false, m, true);
              }
              const u = users.find((x) => x.userId === m.id);
              return row(
                `u-${m.id}`,
                u?.name ?? ownerName(m.id) ?? m.id,
                u?.email ?? '',
                null,
                false,
                m,
              );
            })}
          </ul>
          <div className="cl-share__link">
            <span className="cl-share__lbl">Anyone else with the link:</span>
            <div className="cl-share__acc">
              <button
                ref={accRef}
                type="button"
                className="cl-share__accbtn"
                aria-haspopup="listbox"
                aria-expanded={accOpen}
                disabled={lockAccess}
                title={
                  view.isSystem
                    ? 'Default views are shared with everyone'
                    : !view.canEdit
                      ? 'Only the owner can change this'
                      : undefined
                }
                onClick={() => setAccOpen((o) => !o)}
              >
                {accLabel}
                <span className="cl-caret" aria-hidden />
              </button>
              {accOpen ? (
                <div className="cl-share__accmenu" role="listbox" aria-label="Link access">
                  {LINK_ACCESS.map(([value, label, desc]) => (
                    <button
                      key={value}
                      type="button"
                      className={cn('cl-share__accopt', access === value && 'is-on')}
                      role="option"
                      aria-selected={access === value}
                      onClick={() => {
                        setAccess(value);
                        setAccOpen(false);
                        accRef.current?.focus();
                      }}
                    >
                      <strong>{label}</strong>
                      <span>{desc}</span>
                    </button>
                  ))}
                </div>
              ) : null}
            </div>
            <button type="button" className="cl-btn cl-btn--outline cl-btn--pill" onClick={copy}>
              <LpIcon name="link" className="cl-i" />
              Copy link
            </button>
          </div>
        </div>
        <footer className="cl-modal__foot">
          <button
            type="button"
            className="cl-btn cl-btn--primary"
            disabled={!dirty || busy || readOnly || (server && !teamsReady)}
            onClick={() => void save()}
          >
            Save
          </button>
          <button type="button" className="cl-btn cl-btn--outline" onClick={onClose}>
            Cancel
          </button>
        </footer>
      </div>
    </div>,
    document.body,
  );
}
