'use client';

import Link from 'next/link';
import { useCallback, useEffect, useId, useMemo, useRef, useState, type FormEvent } from 'react';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { useToast } from '@/components/crm/ToastProvider';
import { getBusinessSettings, updateBusinessSettings } from '@/features/settings/api.client';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import {
  DEFAULT_ACCESS,
  DEFAULT_INBOX_NAMES,
  DEFAULT_PROPERTIES,
  DEFAULT_SIDEBAR_VIEWS,
  PROPERTY_CATALOG,
  WIZARD_CHANNELS,
  nextViewId,
  type MemberToken,
  type SidebarView,
} from './data';
import { IbDialog } from './IbDialog';
import { IbMemberMultiSelect } from './IbMemberMultiSelect';
import { TeamInboxesPanel } from './TeamInboxesPanel';
import { workingHoursProblem } from './working-hours';
import { WorkingHoursFields } from './WorkingHoursFields';
import type { InboxWorkingHours } from '@/features/settings/types';

type TabKey = 'channels' | 'slas' | 'sidebar' | 'access';

function BookmarkPin() {
  return (
    <span className="ib-pin">
      <svg
        viewBox="0 0 24 24"
        width="13"
        height="13"
        fill="none"
        stroke="currentColor"
        strokeWidth="1.8"
      >
        <path d="M12 22s7-4.5 7-12a7 7 0 1 0-14 0c0 7.5 7 12 7 12Z" />
        <circle cx="12" cy="10" r="2.2" />
      </svg>
    </span>
  );
}

export function InboxesSettingsView() {
  const toast = useToast();
  const renameTitleId = useId();
  const deleteTitleId = useId();
  const viewDialogTitleId = useId();
  const previewTitleId = useId();
  const drawerTitleId = useId();

  const [tab, setTab] = useState<TabKey>('channels');
  const [inboxNames, setInboxNames] = useState<string[]>(() => [...DEFAULT_INBOX_NAMES]);
  const [currentView, setCurrentView] = useState(() => DEFAULT_INBOX_NAMES[0] ?? 'Inbox');

  const [actionsOpen, setActionsOpen] = useState(false);
  const [openViewMenuId, setOpenViewMenuId] = useState<string | null>(null);

  const [slaFirstOpen, setSlaFirstOpen] = useState(false);
  const [slaCloseOpen, setSlaCloseOpen] = useState(false);
  const [hoursBasis, setHoursBasis] = useState('Operation hours');
  const [firstReplyOn, setFirstReplyOn] = useState(false);
  const [closeOn, setCloseOn] = useState(false);
  const [firstReplyTarget, setFirstReplyTarget] = useState('1 hour');
  const [closeTarget, setCloseTarget] = useState('1 business day');

  const [accessMode, setAccessMode] = useState<'all' | 'specific'>('specific');
  const [accessSet, setAccessSet] = useState<Set<MemberToken>>(() => new Set(DEFAULT_ACCESS));
  const [savedAccessMode, setSavedAccessMode] = useState<'all' | 'specific'>('specific');
  const [savedAccess, setSavedAccess] = useState<Set<MemberToken>>(() => new Set(DEFAULT_ACCESS));
  const [savedHours, setSavedHours] = useState('Operation hours');
  const [savedSlaTargets, setSavedSlaTargets] = useState({
    firstOn: false,
    first: '1 hour',
    closeOn: false,
    close: '1 business day',
  });
  const [workingHours, setWorkingHours] = useState<InboxWorkingHours | null>(null);
  const [savedWorkingHours, setSavedWorkingHours] = useState<InboxWorkingHours | null>(null);
  const [timeZone, setTimeZone] = useState('');
  const [dirty, setDirty] = useState(false);
  const [saveMessage, setSaveMessage] = useState("You've changed settings.");

  const [viewSearch, setViewSearch] = useState('');
  const [sidebarViews, setSidebarViews] = useState<SidebarView[]>(() => [...DEFAULT_SIDEBAR_VIEWS]);
  const [selectAllViews, setSelectAllViews] = useState(false);

  const [renameOpen, setRenameOpen] = useState(false);
  const [renameValue, setRenameValue] = useState('');

  const [deleteOpen, setDeleteOpen] = useState(false);

  const [wizardOpen, setWizardOpen] = useState(false);
  const [wizardStep, setWizardStep] = useState<1 | 2>(1);
  const [wizardName, setWizardName] = useState('');
  const [wizardAccess, setWizardAccess] = useState<'all' | 'specific'>('all');
  const [wizardMembers, setWizardMembers] = useState<Set<MemberToken>>(() => new Set());
  const [wizardChannel, setWizardChannel] = useState<string | null>(null);

  const [createViewOpen, setCreateViewOpen] = useState(false);
  const [newViewName, setNewViewName] = useState('');

  const [propertyOpen, setPropertyOpen] = useState(false);
  const [propertyMenuOpen, setPropertyMenuOpen] = useState(false);
  const [propertySearch, setPropertySearch] = useState('');
  const [selectedProperties, setSelectedProperties] = useState<string[]>(() => [
    ...DEFAULT_PROPERTIES,
  ]);
  const [previewOpen, setPreviewOpen] = useState(false);
  const [draggedProperty, setDraggedProperty] = useState<string | null>(null);

  const markDirty = useCallback(() => {
    setDirty(true);
    setSaveMessage("You've changed settings.");
  }, []);

  const closeMenus = useCallback(() => {
    setActionsOpen(false);
    setOpenViewMenuId(null);
  }, []);

  useEffect(() => {
    const onDoc = () => closeMenus();
    document.addEventListener('click', onDoc);
    return () => document.removeEventListener('click', onDoc);
  }, [closeMenus]);

  const filteredViews = useMemo(() => {
    const q = viewSearch.trim().toLowerCase();
    if (!q) return sidebarViews;
    return sidebarViews.filter((v) => v.name.toLowerCase().includes(q));
  }, [sidebarViews, viewSearch]);

  const propertyOptions = useMemo(() => {
    const q = propertySearch.trim().toLowerCase();
    return PROPERTY_CATALOG.filter((p) => !q || p.toLowerCase().includes(q));
  }, [propertySearch]);

  const openRename = () => {
    closeMenus();
    setRenameValue(currentView);
    setRenameOpen(true);
  };

  const confirmRename = () => {
    const v = renameValue.trim();
    if (!v) return;
    setInboxNames((names) => names.map((n) => (n === currentView ? v : n)));
    setCurrentView(v);
    setRenameOpen(false);
    toast('Inbox renamed', 'success');
  };

  const confirmDelete = () => {
    if (inboxNames.length <= 1) {
      toast('Cannot delete the last inbox', 'info');
      setDeleteOpen(false);
      return;
    }
    const next = inboxNames.filter((n) => n !== currentView);
    setInboxNames(next);
    setCurrentView(next[0] ?? 'Inbox');
    setDeleteOpen(false);
    toast('Inbox deleted', 'success');
  };

  const startWizard = () => {
    closeMenus();
    setWizardStep(1);
    setWizardName('');
    setWizardAccess('all');
    setWizardMembers(new Set());
    setWizardChannel(null);
    setWizardOpen(true);
  };

  const finishWizard = (channelLater: boolean) => {
    const name = wizardName.trim();
    if (!name) return;
    if (!inboxNames.includes(name)) {
      setInboxNames((n) => [...n, name]);
    }
    setCurrentView(name);
    setWizardOpen(false);
    if (channelLater) toast(`${name} created`, 'success');
    else toast(`${name} created. ${wizardChannel ?? 'Channel'} selected`, 'success');
  };

  const wizardNext = () => {
    const name = wizardName.trim();
    if (!name) {
      toast('Enter a team inbox name', 'info');
      return;
    }
    if (wizardAccess === 'specific' && wizardMembers.size === 0) {
      toast('Select at least one user or team', 'info');
      return;
    }
    setWizardStep(2);
  };

  const onCreateView = () => {
    const name = newViewName.trim();
    if (!name) return;
    const row: SidebarView = {
      id: nextViewId(),
      name,
      assignedTo: 'All unassigned teams and users',
      lastUpdated: 'Nov 3, 2026',
    };
    setSidebarViews((v) => [...v, row]);
    setCreateViewOpen(false);
    setNewViewName('');
    toast('Team view created', 'success');
  };

  const cloneView = (view: SidebarView) => {
    const name = `${view.name} (copy)`;
    setSidebarViews((v) => [
      ...v,
      {
        ...view,
        id: nextViewId(),
        name,
      },
    ]);
    toast('View cloned', 'success');
    setOpenViewMenuId(null);
  };

  const resetDefaultProperties = () => {
    setSelectedProperties([...DEFAULT_PROPERTIES]);
    toast('Default view reset', 'success');
    setOpenViewMenuId(null);
  };

  // Settings audit: SLA targets were kept in this browser only. They are the account's now.
  const slaUpdatedAt = useRef<string | undefined>(undefined);
  const saveSettings = async () => {
    const next = {
      firstOn: firstReplyOn,
      first: firstReplyTarget,
      closeOn,
      close: closeTarget,
    };
    const problem = workingHoursProblem(workingHours);
    if (problem) {
      toast(problem, 'danger');
      return;
    }
    try {
      const saved = await updateBusinessSettings({
        inboxSla: { hours: hoursBasis, ...next, workingHours },
        updatedAt: slaUpdatedAt.current,
      });
      slaUpdatedAt.current = saved.updatedAt;
    } catch (err) {
      toast(errorText(err), 'danger');
      return;
    }
    setSavedAccess(new Set(accessSet));
    setSavedAccessMode(accessMode);
    setSavedHours(hoursBasis);
    setSavedWorkingHours(workingHours);
    setSavedSlaTargets(next);
    setDirty(false);
    toast('Inbox settings saved', 'success');
  };

  const cancelSettings = () => {
    setAccessSet(new Set(savedAccess));
    setAccessMode(savedAccessMode);
    setHoursBasis(savedHours);
    setWorkingHours(savedWorkingHours);
    setFirstReplyOn(savedSlaTargets.firstOn);
    setCloseOn(savedSlaTargets.closeOn);
    setFirstReplyTarget(savedSlaTargets.first);
    setCloseTarget(savedSlaTargets.close);
    setDirty(false);
    toast('Changes discarded', 'info');
  };

  useEffect(() => {
    let live = true;
    getBusinessSettings().then(
      (settings) => {
        if (!live) return;
        slaUpdatedAt.current = settings.updatedAt;
        setTimeZone(settings.timezone);
        const saved = settings.inboxSla;
        if (!saved) return;
        setWorkingHours(saved.workingHours ?? null);
        setSavedWorkingHours(saved.workingHours ?? null);
        setHoursBasis(saved.hours);
        setSavedHours(saved.hours);
        setFirstReplyOn(saved.firstOn);
        setCloseOn(saved.closeOn);
        setFirstReplyTarget(saved.first);
        setCloseTarget(saved.close);
        setSavedSlaTargets({
          firstOn: saved.firstOn,
          first: saved.first,
          closeOn: saved.closeOn,
          close: saved.close,
        });
      },
      (err: unknown) => live && toast(errorText(err), 'danger'),
    );
    return () => {
      live = false;
    };
  }, [toast]);

  const onPropertyToggle = (prop: string, checked: boolean) => {
    setSelectedProperties((prev) => {
      if (checked && !prev.includes(prop)) return [...prev, prop];
      if (!checked) return prev.filter((x) => x !== prop);
      return prev;
    });
  };

  const onPropertyDrop = (target: string) => {
    if (!draggedProperty || draggedProperty === target) return;
    setSelectedProperties((prev) => {
      const from = prev.indexOf(draggedProperty);
      const to = prev.indexOf(target);
      if (from < 0 || to < 0) return prev;
      const next = [...prev];
      next.splice(from, 1);
      next.splice(to, 0, draggedProperty);
      return next;
    });
    setDraggedProperty(null);
  };

  const toggleViewRowChecks = (checked: boolean) => {
    setSelectAllViews(checked);
  };

  const sortViews = () => {
    setSidebarViews((v) => [...v].reverse());
  };

  return (
    <main className="ib-main" id="ib-main">
      <h1 className="set-head__title ib-page-title">Inboxes</h1>

      <TeamInboxesPanel />

      <div className="ib-viewbar">
        <label htmlFor="ib-current-view">Current view:</label>
        <div className="ib-select-wrap">
          <select
            id="ib-current-view"
            className="input"
            value={currentView}
            onChange={(e) => setCurrentView(e.target.value)}
          >
            {inboxNames.map((name) => (
              <option key={name} value={name}>
                {name}
              </option>
            ))}
          </select>
          <span className="ib-select-caret" aria-hidden>
            <CrmIcon name="chevron-down" className="iconSize-16" />
          </span>
        </div>
        <span className="ib-view-note">You&apos;re only modifying this view.</span>
        <div className="ib-actions-wrap">
          <button
            className="btn-crm btn-crm--outline ib-actions-trigger"
            type="button"
            aria-expanded={actionsOpen}
            onClick={(e) => {
              e.stopPropagation();
              setActionsOpen((o) => !o);
              setOpenViewMenuId(null);
            }}
          >
            Actions <CrmIcon name="chevron-down" className="iconSize-14" />
          </button>
          <div className="ib-menu" hidden={!actionsOpen}>
            <button type="button" onClick={openRename}>
              Rename inbox
            </button>
            <button type="button" onClick={startWizard}>
              Create new inbox
            </button>
            <button
              type="button"
              onClick={() => {
                closeMenus();
                setDeleteOpen(true);
              }}
            >
              Delete inbox
            </button>
          </div>
        </div>
      </div>

      <nav className="ib-tabs" role="tablist" aria-label="Inbox settings">
        {(
          [
            ['channels', 'Channels'],
            ['slas', 'SLAs'],
            ['sidebar', 'Sidebar Customization'],
            ['access', 'Access'],
          ] as const
        ).map(([key, label]) => (
          <button
            key={key}
            type="button"
            className={cn('ib-tab', tab === key && 'is-active')}
            role="tab"
            aria-selected={tab === key}
            onClick={() => {
              setTab(key);
              closeMenus();
            }}
          >
            {label}
          </button>
        ))}
      </nav>

      {/* Channels */}
      <section
        className={cn('ib-panel', tab === 'channels' && 'is-active')}
        role="tabpanel"
        hidden={tab !== 'channels'}
      >
        <div className="ib-channel-notice">
          <strong>New shared channels page</strong>
          <span>Manage your team channels in one place.</span>
          <Link href="/settings/channels">Go to channel settings</Link>
        </div>
      </section>

      {/* SLAs */}
      <section
        className={cn('ib-panel', tab === 'slas' && 'is-active')}
        role="tabpanel"
        hidden={tab !== 'slas'}
      >
        <div className="ib-sla-content">
          <h2>Ticket SLAs</h2>
          <p>
            Set standards for how quickly your team should respond to and close tickets. Team
            members
            <br className="ib-desktop-only" /> with paid seats will see a warning in this inbox when
            a ticket is due soon or overdue.
          </p>
          <div className="ib-sla-block">
            <h3>Manage when SLAs apply</h3>
            <p>
              Choose whether SLAs should be calculated based on working hours or calendar hours.{' '}
              <span
                className="ib-info"
                title="Choose the hours used to calculate ticket SLA deadlines"
              >
                <CrmIcon name="info" className="iconSize-14" />
              </span>
            </p>
            <label className="ib-field-label" htmlFor="ib-hours">
              Apply based on
            </label>
            <select
              className="input ib-hours"
              id="ib-hours"
              value={hoursBasis}
              onChange={(e) => {
                setHoursBasis(e.target.value);
                markDirty();
              }}
            >
              <option>Operation hours</option>
              <option>Calendar hours</option>
            </select>
            {hoursBasis === 'Operation hours' ? (
              <WorkingHoursFields
                value={workingHours}
                timeZone={timeZone}
                onChange={(next) => {
                  setWorkingHours(next);
                  markDirty();
                }}
              />
            ) : null}
            <h3 className="ib-limits-title crm-pt-3 crm-pb-1">Set SLA limits</h3>
            <div className="ib-sla-row">
              <button
                type="button"
                className="ib-sla-expand"
                aria-expanded={slaFirstOpen}
                onClick={() => setSlaFirstOpen((o) => !o)}
              >
                {slaFirstOpen ? '⌄ ' : '› '}
                <span>Time to first reply</span>
              </button>
              <label className="ib-switch">
                <input
                  type="checkbox"
                  aria-label="Time to first reply"
                  checked={firstReplyOn}
                  onChange={(e) => {
                    setFirstReplyOn(e.target.checked);
                    markDirty();
                  }}
                />
                <span />
              </label>
            </div>
            <div className="ib-sla-details" hidden={!slaFirstOpen}>
              <label>
                First reply target{' '}
                <select
                  className="input"
                  value={firstReplyTarget}
                  onChange={(e) => {
                    setFirstReplyTarget(e.target.value);
                    markDirty();
                  }}
                >
                  <option>1 hour</option>
                  <option>4 hours</option>
                  <option>1 business day</option>
                </select>
              </label>
              <p>Set the expected time for the first response to a new ticket.</p>
            </div>
            <div className="ib-sla-row">
              <button
                type="button"
                className="ib-sla-expand"
                aria-expanded={slaCloseOpen}
                onClick={() => setSlaCloseOpen((o) => !o)}
              >
                {slaCloseOpen ? '⌄ ' : '› '}
                <span>Time to close</span>
              </button>
              <label className="ib-switch">
                <input
                  type="checkbox"
                  aria-label="Time to close"
                  checked={closeOn}
                  onChange={(e) => {
                    setCloseOn(e.target.checked);
                    markDirty();
                  }}
                />
                <span />
              </label>
            </div>
            <div className="ib-sla-details" hidden={!slaCloseOpen}>
              <label>
                Close target{' '}
                <select
                  className="input"
                  value={closeTarget}
                  onChange={(e) => {
                    setCloseTarget(e.target.value);
                    markDirty();
                  }}
                >
                  <option>1 business day</option>
                  <option>3 business days</option>
                  <option>5 business days</option>
                </select>
              </label>
              <p>Set the expected time to resolve and close a ticket.</p>
            </div>
          </div>
        </div>
      </section>

      {/* Sidebar */}
      <section
        className={cn('ib-panel', tab === 'sidebar' && 'is-active')}
        role="tabpanel"
        hidden={tab !== 'sidebar'}
      >
        <div className="ib-sidebar-intro">
          <h2>Sidebar Customization</h2>
          <p>
            Customize the sidebar panel for your inbox. The list of sidebar views here are shared
            across all inboxes. To update the properties visible on the Ticket card,{' '}
            <a
              href="#"
              onClick={(e) => {
                e.preventDefault();
                setPropertyOpen(true);
                toast('CRM Preview Customization Settings', 'info');
              }}
            >
              navigate to CRM
              <br className="ib-desktop-only" /> Preview Customization Settings.
            </a>
          </p>
        </div>
        <div className="ib-sidebar-toolbar">
          <label className="ib-search">
            <input
              type="search"
              placeholder="Search by view name"
              value={viewSearch}
              onChange={(e) => setViewSearch(e.target.value)}
            />
            <CrmIcon name="search" className="iconSize-16" />
          </label>
          <button
            className="btn-crm btn-crm--outline"
            type="button"
            onClick={() => {
              setNewViewName('');
              setCreateViewOpen(true);
            }}
          >
            Create team view
          </button>
        </div>
        <div className="ib-views-table-wrap">
          <table className="ib-views-table">
            <thead>
              <tr>
                <th className="ib-check-col">
                  <input
                    type="checkbox"
                    aria-label="Select all views"
                    checked={selectAllViews}
                    onChange={(e) => toggleViewRowChecks(e.target.checked)}
                  />
                </th>
                <th>
                  <button type="button" onClick={sortViews}>
                    View name ↕
                  </button>
                </th>
                <th>
                  <button type="button" onClick={sortViews}>
                    Assigned to ↕
                  </button>
                </th>
                <th>
                  <button type="button" onClick={sortViews}>
                    Last updated ↕
                  </button>
                </th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              {filteredViews.map((view) => (
                <tr key={view.id} data-ib-view-row data-name={view.name}>
                  <td>
                    <input type="checkbox" aria-label={`Select ${view.name}`} />
                  </td>
                  <td>
                    <BookmarkPin />
                    <a
                      href="#"
                      onClick={(e) => {
                        e.preventDefault();
                        setPropertyOpen(true);
                      }}
                    >
                      {view.name}
                    </a>
                  </td>
                  <td>{view.assignedTo}</td>
                  <td style={{ whiteSpace: 'pre-line' }}>{view.lastUpdated}</td>
                  <td>
                    <div className="ib-row-menu-wrap">
                      <button
                        type="button"
                        className="ib-kebab"
                        aria-label={`${view.name} actions`}
                        onClick={(e) => {
                          e.stopPropagation();
                          setOpenViewMenuId((id) => (id === view.id ? null : view.id));
                          setActionsOpen(false);
                        }}
                      >
                        <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor">
                          <circle cx="5" cy="12" r="2" />
                          <circle cx="12" cy="12" r="2" />
                          <circle cx="19" cy="12" r="2" />
                        </svg>
                      </button>
                      <div className="ib-menu ib-menu--view" hidden={openViewMenuId !== view.id}>
                        <button type="button" onClick={() => cloneView(view)}>
                          Clone view
                        </button>
                        <button
                          type="button"
                          className="is-danger"
                          onClick={resetDefaultProperties}
                        >
                          Reset default view
                        </button>
                      </div>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
          <p className="ib-no-results" hidden={filteredViews.length > 0}>
            No views match your search.
          </p>
        </div>
        <div className="ib-pagination">
          <button type="button" disabled>
            ‹ &nbsp;Prev
          </button>
          <span>1</span>
          <button type="button" disabled>
            Next&nbsp; ›
          </button>
        </div>
      </section>

      {/* Access */}
      <section
        className={cn('ib-panel', tab === 'access' && 'is-active')}
        role="tabpanel"
        hidden={tab !== 'access'}
      >
        <div className="ib-access-content">
          <h2>Access</h2>
          <p>Manage who has access to this inbox.</p>
          <div className="ib-access-radios">
            <label>
              <input
                type="radio"
                name="ib-access"
                value="all"
                checked={accessMode === 'all'}
                onChange={() => {
                  setAccessMode('all');
                  markDirty();
                }}
              />
              <span>Available to everyone</span>
            </label>
            <label>
              <input
                type="radio"
                name="ib-access"
                value="specific"
                checked={accessMode === 'specific'}
                onChange={() => {
                  setAccessMode('specific');
                  markDirty();
                }}
              />
              <span>Select users and teams who can edit</span>
            </label>
          </div>
          <div className="ib-access-picker" hidden={accessMode !== 'specific'}>
            <h3>Who has access:</h3>
            <IbMemberMultiSelect
              selected={accessSet}
              onChange={(next) => {
                setAccessSet(next);
                markDirty();
              }}
            />
          </div>
        </div>
      </section>

      {/* Save bar */}
      <section className="ib-savebar" hidden={!dirty}>
        <button
          type="button"
          className="btn-crm btn-crm--primary"
          onClick={() => void saveSettings()}
        >
          Save
        </button>
        <button type="button" className="btn-crm btn-crm--outline" onClick={cancelSettings}>
          Cancel
        </button>
        <span>{saveMessage}</span>
      </section>

      {/* Rename */}
      <IbDialog
        open={renameOpen}
        onClose={() => setRenameOpen(false)}
        className="set-modal ib-small-modal"
      >
        <form
          onSubmit={(e: FormEvent) => {
            e.preventDefault();
            confirmRename();
          }}
        >
          <div className="set-modal__head">
            <h2 className="set-modal__title" id={renameTitleId}>
              Rename inbox
            </h2>
            <button
              type="button"
              className="ib-dialog-x"
              aria-label="Close"
              onClick={() => setRenameOpen(false)}
            >
              ×
            </button>
          </div>
          <div className="set-modal__body">
            <label className="field">
              <span className="field__label">Inbox name *</span>
              <input
                className="input"
                name="name"
                value={renameValue}
                onChange={(e) => setRenameValue(e.target.value)}
                required
                maxLength={60}
              />
            </label>
          </div>
          <div className="set-modal__foot">
            <button type="button" className="btn-crm btn-crm--primary" onClick={confirmRename}>
              Rename
            </button>
            <button
              type="button"
              className="btn-crm btn-crm--outline"
              onClick={() => setRenameOpen(false)}
            >
              Cancel
            </button>
          </div>
        </form>
      </IbDialog>

      {/* Delete */}
      <IbDialog open={deleteOpen} onClose={() => setDeleteOpen(false)} className="ib-delete-modal">
        <div className="ib-delete-title" id={deleteTitleId}>
          Do you really want to
          <br /> delete Inbox <span>{currentView}</span>?
        </div>
        <div className="ib-delete-body">
          <p>
            Deleting Inbox {currentView} will permanently remove it from your account. This
            can&apos;t be undone.
          </p>
          <p>If connected to forms.</p>
          <ul>
            <li>Legacy forms: All ticket properties will be removed from the form.</li>
            <li>
              New forms: Ticket properties will remain on the form, but no tickets will be created
              from submissions.
            </li>
          </ul>
          <label className="ib-delete-check">
            <input type="checkbox" />
            Delete all conversations threads (optional)
          </label>
          <div className="ib-delete-actions">
            <button type="button" className="btn-crm ib-danger-btn" onClick={confirmDelete}>
              Yes, delete
            </button>
            <button
              type="button"
              className="btn-crm btn-crm--outline"
              onClick={() => setDeleteOpen(false)}
            >
              Cancel
            </button>
          </div>
        </div>
      </IbDialog>

      {/* Create wizard */}
      <IbDialog
        open={wizardOpen}
        onClose={() => setWizardOpen(false)}
        className="ib-wizard"
        labelledBy={renameTitleId}
        onBackdropClick={false}
      >
        <section className={cn('ib-wizard-step', wizardStep === 1 && 'is-active')}>
          <div className="ib-wizard-content">
            <h2>Create team inbox</h2>
            <p>
              Team inboxes let teams manage all one-to-one communication from a shared inbox.
              Conversations in this inbox can only be seen by members of this team inbox.
            </p>
            <label className="field">
              <span className="field__label">Team inbox name *</span>
              <input
                className="input"
                type="text"
                placeholder="e.g., Sales"
                value={wizardName}
                onChange={(e) => setWizardName(e.target.value)}
                required
                maxLength={60}
              />
            </label>
            <div className="ib-wizard-radios">
              <label>
                <input
                  type="radio"
                  name="ib-new-access"
                  value="all"
                  checked={wizardAccess === 'all'}
                  onChange={() => setWizardAccess('all')}
                />
                <span>Available to everyone</span>
              </label>
              <label>
                <input
                  type="radio"
                  name="ib-new-access"
                  value="specific"
                  checked={wizardAccess === 'specific'}
                  onChange={() => setWizardAccess('specific')}
                />
                <span>Select users and teams who can edit</span>
              </label>
            </div>
            {wizardAccess === 'specific' ? (
              <div className="ib-wizard-members">
                <h3>Who has access:</h3>
                <IbMemberMultiSelect
                  selected={wizardMembers}
                  onChange={setWizardMembers}
                  chipsDataAttr="data-ib-wizard-chips"
                  compact
                />
              </div>
            ) : null}
          </div>
          <footer className="ib-wizard-footer">
            <button type="button" className="ib-text-button" onClick={() => setWizardOpen(false)}>
              Cancel
            </button>
            <button
              type="button"
              className="btn-crm btn-crm--primary"
              disabled={!wizardName.trim()}
              onClick={wizardNext}
            >
              Next <CrmIcon name="chevron-right" className="iconSize-14" />
            </button>
          </footer>
        </section>

        <section className={cn('ib-wizard-step', wizardStep === 2 && 'is-active')}>
          <div className="ib-channel-step">
            <h2>Which channel would you like to connect?</h2>
            <div className="ib-channel-cards">
              {WIZARD_CHANNELS.map((ch) => (
                <button
                  key={ch.id}
                  type="button"
                  className={cn('ib-channel-card', wizardChannel === ch.id && 'is-selected')}
                  onClick={() => {
                    setWizardChannel(ch.id);
                    toast(`${ch.label} — connect flow not implemented (demo)`, 'info');
                  }}
                >
                  <span className={cn('ib-channel-art', ch.artClass)}>
                    {ch.icon === 'mail' && <CrmIcon name="mail" className="iconSize-42" />}
                    {ch.icon === 'phone' && <CrmIcon name="phone" className="iconSize-42" />}
                    {ch.icon === 'feedback' && (
                      <svg
                        viewBox="0 0 24 24"
                        width="42"
                        height="42"
                        fill="none"
                        stroke="currentColor"
                        strokeWidth="1.5"
                      >
                        <path d="M7 5.5h12a1.5 1.5 0 0 1 1.5 1.5v9a1.5 1.5 0 0 1-1.5 1.5h-7l-4.5 3v-3H7A1.5 1.5 0 0 1 5.5 16V7A1.5 1.5 0 0 1 7 5.5Z" />
                      </svg>
                    )}
                    {ch.icon === 'file' && (
                      <svg
                        viewBox="0 0 24 24"
                        width="42"
                        height="42"
                        fill="none"
                        stroke="currentColor"
                        strokeWidth="1.5"
                      >
                        <path d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z" />
                        <path d="M14 3v5h5" />
                      </svg>
                    )}
                  </span>
                  <b>{ch.label}</b>
                  <small>{ch.desc}</small>
                </button>
              ))}
            </div>
          </div>
          <footer className="ib-wizard-footer ib-wizard-footer--step2">
            <button
              type="button"
              className="btn-crm btn-crm--outline"
              onClick={() => setWizardStep(1)}
            >
              <CrmIcon name="chevron-left" className="iconSize-14" />
              Back
            </button>
            <button type="button" className="ib-text-button" onClick={() => setWizardOpen(false)}>
              Cancel
            </button>
            <button
              type="button"
              className="btn-crm btn-crm--outline ib-later"
              onClick={() => finishWizard(true)}
            >
              Connect a channel later
            </button>
          </footer>
        </section>
      </IbDialog>

      {/* Create team view */}
      <IbDialog
        open={createViewOpen}
        onClose={() => setCreateViewOpen(false)}
        className="set-modal ib-small-modal"
      >
        <div className="set-modal__head">
          <h2 className="set-modal__title" id={viewDialogTitleId}>
            Create team view
          </h2>
          <button
            type="button"
            className="ib-dialog-x"
            aria-label="Close"
            onClick={() => setCreateViewOpen(false)}
          >
            ×
          </button>
        </div>
        <div className="set-modal__body">
          <label className="field">
            <span className="field__label">View name *</span>
            <input
              className="input"
              placeholder="e.g. My team's view"
              value={newViewName}
              onChange={(e) => setNewViewName(e.target.value)}
              required
            />
          </label>
          <label className="field">
            <span className="field__label">Assigned to</span>
            <select className="input" defaultValue="all">
              <option>All unassigned teams and users</option>
              <option>Specific teams and users</option>
            </select>
          </label>
        </div>
        <div className="set-modal__foot">
          <button type="button" className="btn-crm btn-crm--primary" onClick={onCreateView}>
            Save
          </button>
          <button
            type="button"
            className="btn-crm btn-crm--outline"
            onClick={() => setCreateViewOpen(false)}
          >
            Cancel
          </button>
        </div>
      </IbDialog>

      {/* Property drawer */}
      <IbDialog
        open={propertyOpen}
        onClose={() => {
          setPropertyOpen(false);
          setPropertyMenuOpen(false);
        }}
        className="ib-property-drawer"
        labelledBy={drawerTitleId}
      >
        <div className="ib-drawer-head">
          <h2 id={drawerTitleId}>Edit Ticket property list</h2>
          <button type="button" aria-label="Close" onClick={() => setPropertyOpen(false)}>
            ×
          </button>
        </div>
        <div className="ib-drawer-body">
          <p>Choose which properties to show on this card.</p>
          <div className="ib-property-picker-wrap">
            <button
              type="button"
              className="ib-property-add"
              onClick={() => setPropertyMenuOpen((o) => !o)}
            >
              Add properties <span>⌄</span>
            </button>
            <div className="ib-property-menu" hidden={!propertyMenuOpen}>
              <label className="ib-property-search">
                <input
                  type="search"
                  placeholder="Search"
                  value={propertySearch}
                  onChange={(e) => setPropertySearch(e.target.value)}
                />
                <CrmIcon name="search" className="iconSize-16" />
              </label>
              <h3>Ticket information</h3>
              <div className="ib-property-options">
                {propertyOptions.map((p) => (
                  <label key={p} className="ib-property-option">
                    <input
                      type="checkbox"
                      value={p}
                      checked={selectedProperties.includes(p)}
                      onChange={(e) => onPropertyToggle(p, e.target.checked)}
                    />
                    <span>{p}</span>
                  </label>
                ))}
              </div>
            </div>
          </div>
          <div className="ib-property-selected">
            {selectedProperties.map((p, index) => (
              <div
                key={p}
                className={cn('ib-property-chip', draggedProperty === p && 'is-dragging')}
                draggable
                data-property={p}
                data-property-index={index}
                onDragStart={() => setDraggedProperty(p)}
                onDragEnd={() => setDraggedProperty(null)}
                onDragOver={(e) => {
                  if (draggedProperty && draggedProperty !== p) {
                    e.preventDefault();
                    e.currentTarget.classList.add('is-drop-target');
                  }
                }}
                onDragLeave={(e) => {
                  e.currentTarget.classList.remove('is-drop-target');
                }}
                onDrop={(e) => {
                  e.preventDefault();
                  e.currentTarget.classList.remove('is-drop-target');
                  onPropertyDrop(p);
                }}
              >
                <span className="ib-property-drag" aria-hidden>
                  ⠿
                </span>
                <span>{p}</span>
                <button
                  type="button"
                  aria-label={`Remove ${p}`}
                  onClick={() => onPropertyToggle(p, false)}
                >
                  ×
                </button>
              </div>
            ))}
          </div>
        </div>
        <footer className="ib-drawer-footer">
          <button
            type="button"
            className="btn-crm btn-crm--primary"
            onClick={() => {
              setPropertyOpen(false);
              toast('Ticket property list saved', 'success');
            }}
          >
            Save
          </button>
          <button
            type="button"
            className="btn-crm btn-crm--outline"
            onClick={() => {
              setPreviewOpen(true);
            }}
          >
            Preview
          </button>
        </footer>
      </IbDialog>

      {/* Ticket preview */}
      <IbDialog
        open={previewOpen}
        onClose={() => setPreviewOpen(false)}
        className="set-modal ib-preview-modal"
      >
        <div className="set-modal__head">
          <h2 className="set-modal__title" id={previewTitleId}>
            Ticket card preview
          </h2>
          <button
            type="button"
            className="ib-dialog-x"
            aria-label="Close"
            onClick={() => setPreviewOpen(false)}
          >
            ×
          </button>
        </div>
        <div className="set-modal__body">
          <div className="ib-ticket-preview-card">
            <h3>Ticket information</h3>
            <div>
              {selectedProperties.map((p) => (
                <div key={p}>
                  <b>{p}</b>
                </div>
              ))}
            </div>
          </div>
        </div>
        <div className="set-modal__foot">
          <button
            type="button"
            className="btn-crm btn-crm--outline"
            onClick={() => setPreviewOpen(false)}
          >
            Close preview
          </button>
        </div>
      </IbDialog>
    </main>
  );
}
