'use client';

import { useEffect, useMemo, useState } from 'react';
import { Alert } from '@/components/crm/Alert';
import { CustomSelect } from '@/components/crm/CustomSelect';
import {
  APP_PERMISSIONS,
  PERMISSION_OBJECTS,
  SEGMENT_RIGHTS,
  segmentRightsOf,
  setEditsRecords,
  snippetWriteOf,
  workflowRightsOf,
  type WorkflowRights,
  type AppPermission,
  type EditScope,
  type ObjectRule,
  type PermissionObject,
  type PermissionRules,
  type PermissionSet,
  type SegmentRights,
  type ViewScope,
} from '@/features/permission-sets/api.client';
import { deleteCell, mergeCell, scopePatch } from '@/features/permission-sets/scopeRules';
import { EXTERNAL_WORKFLOW_ACTIONS } from '@/features/workflows/access';
import { WORKFLOW_ACTIONS, WORKFLOW_OBJECTS } from '@/features/workflows/types';
import { OBJECT_LABELS, actionLabel } from '@/features/workflows/ui/shared';
import { useCustomWorkflowObjects } from '@/features/workflows/useCustomWorkflowObjects';
import { cn } from '@/lib/utils/cn';
import { FieldAccessGrid } from './FieldAccessGrid';
import { DialogHead, SetDialog } from './settings-ui';

const OBJECT_LABEL: Record<PermissionObject, string> = {
  contact: 'Contacts',
  company: 'Companies',
  deal: 'Deals',
  task: 'Tasks',
  activity: 'Activities',
};

const APP_LABEL: Record<AppPermission, string> = {
  manage_settings: 'Manage settings',
  edit_property_settings: 'Edit property settings',
  manage_users: 'Manage users',
  manage_workflows: 'Manage workflows',
  view_workflows: 'View workflows',
  import: 'Import',
  use_sequences: 'Use sequences',
  manage_sequences: 'Manage sequences',
  manage_targets: 'Manage targets',
  // PB8: the 4 Nov design's "Playbooks" access item (settings-users-tabs.js:184).
  use_playbooks: 'Playbooks',
  export: 'Export',
  restore: 'Restore deleted records',
  access_inbox: 'Access Inbox',
  manage_inboxes: 'Manage team inboxes',
  connect_channels: 'Connect channels',
  view_unassigned_conversations: 'View unassigned team conversations',
  reassign_conversations: 'Reassign conversations',
};

/** HUB-743: the Segments rights' labels (the design's sub-rows: View, Create, Edit, Delete). */
const SEGMENT_LABEL: Record<keyof SegmentRights, string> = {
  view: 'View',
  create: 'Create',
  edit: 'Edit',
  delete: 'Delete',
};

const SNIPPET_WRITE_LABEL = 'Create, edit and delete snippets';

/**
 * HUB-743: what a set's segment rights add up to, as the design's status line
 * (settings-users-tabs.js formatPermStatus): "View, Create, Edit, Delete", or "Access disabled".
 */
export function segmentStatus(rights: SegmentRights): string {
  if (!rights.view) return 'Access disabled';
  return SEGMENT_RIGHTS.filter((right) => rights[right])
    .map((right) => SEGMENT_LABEL[right])
    .join(', ');
}

/**
 * HUB-743: one segment right changed. Without View none of the others apply, so unticking View
 * unticks them and ticking another ticks View. QA round 1 BUG-04: deleting a segment also needs
 * Edit (the API's `canDeleteList`), so ticking Delete ticks Edit and unticking Edit unticks Delete,
 * as the API's `normalizeSegmentRights` saves them.
 */
export function withSegmentRight(
  rights: SegmentRights,
  right: keyof SegmentRights,
  on: boolean,
): SegmentRights {
  if (right === 'view' && !on) return { view: false, create: false, edit: false, delete: false };
  return {
    ...rights,
    [right]: on,
    ...(on && { view: true }),
    ...(right === 'delete' && on && { edit: true }),
    ...(right === 'edit' && !on && { delete: false }),
  };
}

// `Team` (HUB-322): records of the user's teams and their child teams.
const VIEW_OPTIONS: Array<{ value: ViewScope; label: string }> = [
  { value: 'own', label: 'Own' },
  { value: 'team', label: 'Team' },
  { value: 'all', label: 'All' },
];

const EDIT_OPTIONS: Array<{ value: EditScope; label: string }> = [
  { value: 'none', label: 'None' },
  { value: 'own', label: 'Own' },
  { value: 'team', label: 'Team' },
  { value: 'all', label: 'All' },
];

function emptyRules(): PermissionRules {
  return {
    objects: Object.fromEntries(
      PERMISSION_OBJECTS.map((o) => [o, { view: 'own', edit: 'none', delete: false }]),
    ) as Record<PermissionObject, ObjectRule>,
    // a new set starts with the Inbox open, like the built-in ones; PB8: and Playbooks (the
    // user's call, 30 Nov 2026: on for every set)
    app: Object.fromEntries(
      APP_PERMISSIONS.map((p) => [
        p,
        p === 'access_inbox' || p === 'view_unassigned_conversations' || p === 'use_playbooks',
      ]),
    ) as Record<AppPermission, boolean>,
    // HUB-743: as a set that edits no records: view segments only.
    segments: { view: true, create: false, edit: false, delete: false },
  };
}

function cloneRules(rules: PermissionRules): PermissionRules {
  return {
    objects: Object.fromEntries(
      PERMISSION_OBJECTS.map((o) => [o, { ...rules.objects[o] }]),
    ) as Record<PermissionObject, ObjectRule>,
    app: { ...rules.app },
    // HUB-316: kept, so saving other changes doesn't drop the set's field rules.
    fields: Object.fromEntries(
      Object.entries(rules.fields ?? {}).map(([object, fields]) => [object, { ...fields }]),
    ),
    // HUB-743: a set saved before segment rights shows (and saves) what its role gave it.
    segments: { ...segmentRightsOf(rules) },
    // HUB-751: kept as saved. Not filled in: a set that edits nothing today would be saved as
    // "no snippets" and stay so when editing is turned on.
    ...(rules.snippets && { snippets: { ...rules.snippets } }),
    // HUB-746: kept as saved; a set without them keeps what "Manage workflows" gives.
    ...(rules.workflows && { workflows: { ...rules.workflows } }),
  };
}

export type PermissionSetEditorMode =
  | { kind: 'create'; sets: PermissionSet[]; seed?: PermissionSet }
  | { kind: 'edit'; set: PermissionSet }
  /** Sequences SQ-4 (Q-03): a built-in set, read only, with Copy. */
  | { kind: 'view'; set: PermissionSet };

export function PermissionSetEditor({
  mode,
  open,
  onClose,
  onSave,
  saving,
  error,
  members = [],
  onCopy,
}: {
  mode: PermissionSetEditorMode | null;
  open: boolean;
  onClose: () => void;
  onSave: (input: {
    name: string;
    copyFromId?: string;
    rules: PermissionRules;
    updatedAt?: string;
  }) => Promise<void>;
  saving: boolean;
  error: string | null;
  /** Who is on each set: the Users tab lists the members of the set being edited. */
  members?: { userId: string; name: string; email: string; permissionSetId: string | null }[];
  /** View mode: Copy opens the create-from-copy flow; left out when the user can't create sets. */
  onCopy?: (set: PermissionSet) => void;
}) {
  const isCreate = mode?.kind === 'create';
  const seed = mode?.kind === 'create' ? mode.seed : undefined;
  const editing = mode?.kind === 'edit' || mode?.kind === 'view' ? mode.set : null;
  const readOnly = mode?.kind === 'view';
  // Every control is off while saving, and always for a built-in set.
  const locked = saving || readOnly;

  const [name, setName] = useState('');
  const [copyFromId, setCopyFromId] = useState('');
  const [rules, setRules] = useState<PermissionRules>(emptyRules);
  // Design settings-users.php: Access (set the rules), Review (what they add up to), Users.
  const [tab, setTab] = useState<'access' | 'review' | 'users'>('access');
  const [reviewQuery, setReviewQuery] = useState('');

  useEffect(() => {
    if (!open || !mode) return;
    setTab('access');
    setReviewQuery('');
    if (mode.kind === 'edit' || mode.kind === 'view') {
      setName(mode.set.name);
      setCopyFromId('');
      setRules(cloneRules(mode.set.rules));
      return;
    }
    setName(mode.seed ? `${mode.seed.name} copy` : '');
    setCopyFromId(mode.seed?.id ?? '');
    setRules(mode.seed ? cloneRules(mode.seed.rules) : emptyRules());
  }, [open, mode]);

  const copyOptions = useMemo(() => {
    if (mode?.kind !== 'create') return [];
    return [
      { value: '', label: 'Start empty (view own only)' },
      ...mode.sets.map((s) => ({ value: s.id, label: s.name })),
    ];
  }, [mode]);

  const onCopyChange = (id: string) => {
    setCopyFromId(id);
    if (!mode || mode.kind !== 'create') return;
    if (!id) {
      setRules(emptyRules());
      return;
    }
    const source = mode.sets.find((s) => s.id === id);
    if (source) setRules(cloneRules(source.rules));
  };

  const setObject = (object: PermissionObject, patch: Partial<ObjectRule>) => {
    setRules((current) => ({
      ...current,
      objects: {
        ...current.objects,
        [object]: { ...current.objects[object], ...patch },
      },
    }));
  };

  const setApp = (permission: AppPermission, value: boolean) => {
    setRules((current) => ({
      ...current,
      app: { ...current.app, [permission]: value },
    }));
  };

  const title = readOnly
    ? 'View permission set'
    : seed
      ? 'Copy permission set'
      : isCreate
        ? 'Create permission set'
        : 'Edit permission set';
  const titleId = isCreate ? 'ps-create-title' : 'ps-edit-title';

  return (
    <SetDialog open={open} onClose={onClose} drawer labelledBy={titleId} className="ps-editor">
      <form
        onSubmit={(e) => {
          e.preventDefault();
          if (readOnly) return;
          void onSave({
            name: name.trim(),
            ...(isCreate && copyFromId ? { copyFromId } : {}),
            rules,
            ...(editing ? { updatedAt: editing.updatedAt } : {}),
          });
        }}
        noValidate
      >
        <DialogHead id={titleId} title={title} onClose={onClose} />
        <div className="set-modal__body">
          {error ? <Alert tone="danger">{error}</Alert> : null}
          {readOnly ? (
            <Alert tone="info">Built in, can&apos;t be changed. Copy it to make your own.</Alert>
          ) : null}
          <nav
            className="ut-subview-tabs ps-editor__tabs"
            role="tablist"
            aria-label="Permission set"
          >
            {(
              [
                ['access', 'Access'],
                ['review', 'Review'],
                ['users', 'Users'],
              ] as const
            ).map(([id, label]) => (
              <button
                key={id}
                type="button"
                role="tab"
                aria-selected={tab === id}
                className={cn('ut-subview-tab', tab === id && 'active')}
                onClick={() => setTab(id)}
              >
                {label}
              </button>
            ))}
          </nav>
          <div hidden={tab !== 'access'}>
            <div className="field">
              <label className="field__label" htmlFor="ps-name">
                Name
              </label>
              <input
                className="input"
                id="ps-name"
                value={name}
                maxLength={100}
                autoComplete="off"
                disabled={locked}
                onChange={(e) => setName(e.target.value)}
              />
            </div>

            {isCreate ? (
              <div className="field">
                <span className="field__label">Copy from</span>
                <CustomSelect
                  placeholder="Start empty"
                  value={copyFromId}
                  options={copyOptions}
                  searchable={copyOptions.length > 8}
                  disabled={locked}
                  onChange={onCopyChange}
                />
                <p className="field__help">
                  Start from another set, then adjust the rules below before saving.
                </p>
              </div>
            ) : null}

            <h3 className="ps-editor__heading">Record access</h3>
            <div className="set-table-card ps-editor__table">
              <table className="set-table">
                <thead>
                  <tr>
                    <th>Object</th>
                    <th>View</th>
                    <th>Edit</th>
                    <th>Delete</th>
                    <th>Merge</th>
                  </tr>
                </thead>
                <tbody>
                  {PERMISSION_OBJECTS.map((object) => {
                    const rule = rules.objects[object];
                    // P2a: contacts and companies have Delete and Merge scopes (scopeRules.ts).
                    const del = deleteCell(object, rule);
                    const merge = mergeCell(object, rule);
                    return (
                      <tr key={object}>
                        <td className="crm-fw-semibold">{OBJECT_LABEL[object]}</td>
                        <td>
                          <CustomSelect
                            placeholder="View"
                            value={rule.view}
                            options={VIEW_OPTIONS}
                            searchable={false}
                            disabled={locked}
                            onChange={(v) => setObject(object, { view: v as ViewScope })}
                          />
                        </td>
                        <td>
                          <CustomSelect
                            placeholder="Edit"
                            value={rule.edit}
                            options={EDIT_OPTIONS}
                            searchable={false}
                            disabled={locked}
                            onChange={(v) => setObject(object, { edit: v as EditScope })}
                          />
                        </td>
                        <td>
                          {del.kind === 'scope' ? (
                            <CustomSelect
                              placeholder="Delete"
                              value={del.value}
                              options={EDIT_OPTIONS}
                              searchable={false}
                              disabled={locked}
                              onChange={(v) =>
                                setObject(object, scopePatch(rule, 'delete', v as EditScope))
                              }
                            />
                          ) : (
                            <label className="check">
                              <input
                                type="checkbox"
                                checked={del.checked}
                                disabled={locked}
                                onChange={(e) => setObject(object, { delete: e.target.checked })}
                              />
                              <span className="check__box" aria-hidden />
                              <span className="crm-visually-hidden">
                                Delete {OBJECT_LABEL[object]}
                              </span>
                            </label>
                          )}
                        </td>
                        <td>
                          {merge.kind === 'scope' ? (
                            <CustomSelect
                              placeholder="Merge"
                              value={merge.value}
                              options={EDIT_OPTIONS}
                              searchable={false}
                              disabled={locked}
                              onChange={(v) =>
                                setObject(object, scopePatch(rule, 'merge', v as EditScope))
                              }
                            />
                          ) : (
                            <span aria-hidden>—</span>
                          )}
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
            <p className="field__help">
              Own: records the user owns. Team: records owned by anyone in the user&apos;s teams or
              their child teams. All: every record.
            </p>

            <h3 className="ps-editor__heading">App permissions</h3>
            <div className="ps-editor__apps">
              {APP_PERMISSIONS.map((permission) => (
                <label className="check" key={permission}>
                  <input
                    type="checkbox"
                    checked={rules.app[permission]}
                    disabled={locked}
                    onChange={(e) => setApp(permission, e.target.checked)}
                  />
                  <span className="check__box" aria-hidden />
                  {APP_LABEL[permission]}
                </label>
              ))}
            </div>

            <WorkflowRightsSection
              rights={workflowRightsOf(rules)}
              disabled={locked || !rules.app.manage_workflows}
              onChange={(patch) =>
                setRules((current) => ({
                  ...current,
                  workflows: { ...workflowRightsOf(current), ...patch },
                }))
              }
            />

            {/* HUB-743: the design's permission item (settings-users-tabs.js, `.ut-perm-item`). */}
            <SegmentRightsItem
              rights={segmentRightsOf(rules)}
              disabled={locked}
              onChange={(right, on) =>
                setRules((current) => ({
                  ...current,
                  segments: withSegmentRight(segmentRightsOf(current), right, on),
                }))
              }
            />
            <p className="field__help">
              Each segment&apos;s own access also applies. Super Admins can always do everything.
            </p>

            <h3 className="ps-editor__heading">Snippets</h3>
            <label className="check">
              <input
                type="checkbox"
                checked={snippetWriteOf(rules)}
                disabled={locked || !setEditsRecords(rules)}
                onChange={(e) =>
                  setRules((current) => ({ ...current, snippets: { write: e.target.checked } }))
                }
              />
              <span className="check__box" aria-hidden />
              {SNIPPET_WRITE_LABEL}
            </label>
            <p className="field__help">
              Includes folders, import, export and Restore deleted. Everyone can still insert the
              snippets they can see. A set that edits no records can&apos;t create snippets.
            </p>

            <h3 className="ps-editor__heading">Field access</h3>
            <FieldAccessGrid
              value={rules.fields ?? {}}
              disabled={locked}
              onChange={(fields) => setRules((current) => ({ ...current, fields }))}
            />
          </div>
          {tab === 'review' ? (
            <ReviewPane rules={rules} query={reviewQuery} onQuery={setReviewQuery} />
          ) : null}
          {tab === 'users' ? (
            <div className="ps-editor__users">
              {editing ? (
                (() => {
                  const on = members.filter((m) => m.permissionSetId === editing.id);
                  return on.length ? (
                    <>
                      <p className="field__help">
                        {on.length} user{on.length === 1 ? ' has' : 's have'} this permission set.
                        Change a user&apos;s set from the Users tab.
                      </p>
                      <ul className="ps-editor__user-list">
                        {on.map((m) => (
                          <li key={m.userId}>
                            <strong>{m.name}</strong>
                            <span>{m.email}</span>
                          </li>
                        ))}
                      </ul>
                    </>
                  ) : (
                    <p className="field__help">
                      No users have this permission set yet. Assign it to users from the Users tab.
                    </p>
                  );
                })()
              ) : (
                <p className="field__help">
                  Create the set first, then assign it to users from the Users tab.
                </p>
              )}
            </div>
          ) : null}
        </div>
        <div className="set-modal__foot">
          <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
            {readOnly ? 'Close' : 'Cancel'}
          </button>
          {readOnly ? (
            editing && onCopy ? (
              // Its own key: React must not reuse this node as the submit button below, or the
              // click that leaves view mode would submit the copy form.
              <button
                key="copy"
                type="button"
                className="btn-crm btn-crm--primary"
                onClick={() => onCopy(editing)}
              >
                Copy
              </button>
            ) : null
          ) : (
            <button
              key="save"
              type="submit"
              className={cn('btn-crm btn-crm--primary', saving && 'is-loading')}
              aria-busy={saving}
              disabled={saving || name.trim().length === 0}
            >
              {saving ? 'Saving…' : seed ? 'Create copy' : isCreate ? 'Create set' : 'Save changes'}
            </button>
          )}
        </div>
      </form>
    </SetDialog>
  );
}

const WORKFLOW_RIGHT_ROWS: {
  key: 'publish' | 'delete' | 'enroll' | 'externalActions' | 'customCode';
  label: string;
}[] = [
  { key: 'publish', label: 'Turn workflows on or off and publish changes' },
  { key: 'delete', label: 'Delete and restore workflows' },
  { key: 'enroll', label: 'Enroll and unenroll records, retry or skip steps' },
  {
    key: 'externalActions',
    label: 'Add steps that send outside the CRM (email, SMS, webhook, Slack, Google Sheets)',
  },
  { key: 'customCode', label: 'Add custom code steps' },
];

/** The kinds of step a set can be limited to one by one; custom code has its own box above. */
const WORKFLOW_STEP_KINDS: string[] = [
  'delay',
  'branch',
  ...WORKFLOW_ACTIONS.filter((a) => a !== 'custom_code'),
];

const stepKindLabel = (kind: string) =>
  kind === 'delay' ? 'Delay' : kind === 'branch' ? 'Branch' : actionLabel(kind);

/**
 * HUB-746 (go-live 954): what "Manage workflows" covers, by action, by kind of step and by
 * object. Off while the set can't manage workflows.
 */
function WorkflowRightsSection({
  rights,
  disabled,
  onChange,
}: {
  rights: WorkflowRights;
  disabled: boolean;
  onChange: (patch: Partial<WorkflowRights>) => void;
}) {
  const custom = useCustomWorkflowObjects();
  const objects = [...WORKFLOW_OBJECTS, ...custom.map((o) => o.key)].filter(
    (key, i, all) => all.indexOf(key) === i,
  );
  const chosen = rights.objects;
  const blocked = rights.blockedSteps ?? [];
  // Open with nothing blocked yet, until a kind is unticked.
  const [choosingSteps, setChoosingSteps] = useState(false);
  const showSteps = choosingSteps || blocked.length > 0;
  return (
    <>
      <h3 className="ps-editor__heading">Workflow access</h3>
      <div className="ps-editor__apps">
        {WORKFLOW_RIGHT_ROWS.map(({ key, label }) => (
          <label className="check" key={key}>
            <input
              type="checkbox"
              checked={rights[key]}
              disabled={disabled}
              onChange={(e) => onChange({ [key]: e.target.checked })}
            />
            <span className="check__box" aria-hidden />
            {label}
          </label>
        ))}
      </div>
      <label className="check crm-mt-3">
        <input
          type="checkbox"
          checked={showSteps}
          disabled={disabled}
          onChange={(e) => {
            setChoosingSteps(e.target.checked);
            if (!e.target.checked) onChange({ blockedSteps: [] });
          }}
        />
        <span className="check__box" aria-hidden />
        Only certain kinds of step
      </label>
      {showSteps ? (
        <div className="ps-editor__apps crm-mt-2" role="group" aria-label="Workflow step kinds">
          {WORKFLOW_STEP_KINDS.map((kind) => {
            const outside = !rights.externalActions && EXTERNAL_WORKFLOW_ACTIONS.includes(kind);
            return (
              <label className="check" key={kind}>
                <input
                  type="checkbox"
                  checked={!outside && !blocked.includes(kind)}
                  disabled={disabled || outside}
                  onChange={(e) =>
                    onChange({
                      blockedSteps: e.target.checked
                        ? blocked.filter((k) => k !== kind)
                        : [...blocked, kind],
                    })
                  }
                />
                <span className="check__box" aria-hidden />
                {stepKindLabel(kind)}
              </label>
            );
          })}
        </div>
      ) : null}
      <label className="check crm-mt-3">
        <input
          type="checkbox"
          checked={chosen !== null}
          disabled={disabled}
          onChange={(e) => onChange({ objects: e.target.checked ? [...objects] : null })}
        />
        <span className="check__box" aria-hidden />
        Only workflows of certain objects
      </label>
      {chosen !== null ? (
        <div className="ps-editor__apps crm-mt-2" role="group" aria-label="Workflow objects">
          {objects.map((key) => (
            <label className="check" key={key}>
              <input
                type="checkbox"
                checked={chosen.includes(key)}
                disabled={disabled}
                onChange={(e) =>
                  onChange({
                    objects: e.target.checked ? [...chosen, key] : chosen.filter((o) => o !== key),
                  })
                }
              />
              <span className="check__box" aria-hidden />
              {OBJECT_LABELS[key]?.many ?? key}
            </label>
          ))}
        </div>
      ) : null}
      <p className="field__help">
        These narrow “Manage workflows”; without it they give nothing. Turning a workflow on also
        needs its owner or a Super Admin. Viewing is not limited by object.
      </p>
    </>
  );
}

/** Review tab: every permission the set gives, as text, with a search. */
function ReviewPane({
  rules,
  query,
  onQuery,
}: {
  rules: PermissionRules;
  query: string;
  onQuery: (q: string) => void;
}) {
  const scope = (v: string) => (v === 'none' ? 'None' : v.charAt(0).toUpperCase() + v.slice(1));
  const rows: { section: string; name: string; value: string }[] = [
    ...PERMISSION_OBJECTS.flatMap((object) => {
      const rule = rules.objects[object];
      const del = deleteCell(object, rule);
      const merge = mergeCell(object, rule);
      return [
        {
          section: 'Record access',
          name: `${OBJECT_LABEL[object]}: view`,
          value: scope(rule.view),
        },
        {
          section: 'Record access',
          name: `${OBJECT_LABEL[object]}: edit`,
          value: scope(rule.edit),
        },
        {
          section: 'Record access',
          name: `${OBJECT_LABEL[object]}: delete`,
          value: del.kind === 'scope' ? scope(del.value) : del.checked ? 'Yes' : 'No',
        },
        ...(merge.kind === 'scope'
          ? [
              {
                section: 'Record access',
                name: `${OBJECT_LABEL[object]}: merge`,
                value: scope(merge.value),
              },
            ]
          : []),
      ];
    }),
    ...APP_PERMISSIONS.map((permission) => ({
      section: 'App permissions',
      name: APP_LABEL[permission],
      value: rules.app[permission] ? 'Yes' : 'No',
    })),
    ...(rules.app.manage_workflows
      ? [
          ...WORKFLOW_RIGHT_ROWS.map(({ key, label }) => ({
            section: 'Workflows',
            name: label,
            value: workflowRightsOf(rules)[key] ? 'Yes' : 'No',
          })),
          {
            section: 'Workflows',
            name: 'Kinds of step they cannot add or change',
            value: workflowRightsOf(rules).blockedSteps?.map(stepKindLabel).join(', ') || 'None',
          },
          {
            section: 'Workflows',
            name: 'Workflows of these objects',
            value:
              workflowRightsOf(rules)
                .objects?.map((o) => OBJECT_LABELS[o]?.many ?? o)
                .join(', ') ?? 'Every object',
          },
        ]
      : []),
    // HUB-743: as the design's status line (settings-users-tabs.js formatPermStatus).
    { section: 'Segments', name: 'Segments', value: segmentStatus(segmentRightsOf(rules)) },
    { section: 'Snippets', name: SNIPPET_WRITE_LABEL, value: snippetWriteOf(rules) ? 'Yes' : 'No' },
  ];
  const q = query.trim().toLowerCase();
  const shown = rows.filter((r) => !q || r.name.toLowerCase().includes(q));
  const sections = [...new Set(shown.map((r) => r.section))];
  return (
    <div className="ps-editor__review">
      <input
        type="search"
        className="input"
        placeholder="Search"
        aria-label="Search permissions"
        value={query}
        onChange={(e) => onQuery(e.target.value)}
      />
      {sections.length ? (
        sections.map((section) => (
          <section key={section}>
            <h3 className="ps-editor__heading">{section}</h3>
            <dl className="ps-editor__review-list">
              {shown
                .filter((r) => r.section === section)
                .map((r) => (
                  <div key={r.name}>
                    <dt>{r.name}</dt>
                    <dd>{r.value}</dd>
                  </div>
                ))}
            </dl>
          </section>
        ))
      ) : (
        <p className="field__help">No permissions match “{query.trim()}”.</p>
      )}
    </div>
  );
}

/**
 * HUB-743: Segments as the design's permission item (settings-users-tabs.js, `.ut-perm-item`):
 * the switch is View (off: "Access disabled"), the sub-rows Create, Edit and Delete (Critical).
 * The design's copy is its Lists item's (Marketing), which are our segments.
 */
function SegmentRightsItem({
  rights,
  disabled,
  onChange,
}: {
  rights: SegmentRights;
  disabled: boolean;
  onChange: (right: keyof SegmentRights, on: boolean) => void;
}) {
  const [open, setOpen] = useState(true);
  return (
    <div className={cn('ut-perm-item', open && 'is-open')}>
      <div className="ut-perm-item__head">
        <div className="ut-perm-item__info">
          <div className="ut-perm-item__title-row">
            <button
              type="button"
              className="ut-perm-item__toggle-head"
              aria-expanded={open}
              aria-controls="psSegmentRights"
              onClick={() => setOpen((v) => !v)}
            >
              <svg
                className="icon iconSize-14 ut-perm-item__arrow"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
                aria-hidden="true"
              >
                <path d="m6 9 6 6 6-6" />
              </svg>
              <span className="ut-perm-item__title">Segments</span>
            </button>
          </div>
          <p className="ut-perm-item__desc">Segment contacts and build dynamic or static lists.</p>
          <span className="ut-perm-item__status">{segmentStatus(rights)}</span>
        </div>
        <div className="ut-perm-item__acts">
          <label className="switch">
            <input
              type="checkbox"
              checked={rights.view}
              disabled={disabled}
              aria-label="View segments"
              onChange={(e) => onChange('view', e.target.checked)}
            />
            <span className="switch__track" />
            <span className="switch__state-label">{rights.view ? 'ON' : 'OFF'}</span>
          </label>
        </div>
      </div>
      <div className="ut-perm-item__body" id="psSegmentRights">
        {SEGMENT_RIGHTS.filter((right) => right !== 'view').map((right) => (
          <div className="ut-perm-subrow" key={right}>
            <span className="ut-perm-subrow__lbl">
              {SEGMENT_LABEL[right]}
              {right === 'delete' ? <span className="ut-critical-badge">Critical</span> : null}
            </span>
            <label className="switch">
              <input
                type="checkbox"
                checked={rights[right]}
                disabled={disabled}
                aria-label={`${SEGMENT_LABEL[right]} segments`}
                onChange={(e) => onChange(right, e.target.checked)}
              />
              <span className="switch__track" />
            </label>
          </div>
        ))}
      </div>
    </div>
  );
}
