'use client';

import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { CustomSelect } from '@/components/crm/CustomSelect';
import { useToast } from '@/components/crm/ToastProvider';
import { logout, logoutAll } from '@/features/auth/api.client';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import { signOutExtension } from '@/features/extension/bridge';
import type { MyMailbox } from '@/features/inbox/types';
import type { MyCalendar } from '@/features/meetings/types';
import { errorText, isApiError } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import {
  connectGmail,
  connectGoogleCalendar,
  disconnectGmail,
  disconnectGoogleCalendar,
  getMyCalendar,
  getMyMailbox,
  getProfile,
  removeProfilePhoto,
  updateGmailConsent,
  updateProfile,
  uploadProfilePhoto,
} from '../api.client';
import { HOME_PAGE_OPTIONS, type HomePage, type Profile, type UpdateProfileBody } from '../types';
import { useApplyProfile } from '../UserPrefs';
import {
  ConfirmDialog,
  DialogHead,
  SetDialog,
  SettingsForm,
  SettingsFormsProvider,
  SuField,
  TabPanel,
  useHashTab,
} from './settings-ui';
import { GeneralAutomationTab } from './GeneralAutomationTab';
import { GeneralCalendarTab } from './GeneralCalendarTab';
import { GeneralCallingTab } from './GeneralCallingTab';
import { GeneralEmailTab } from './GeneralEmailTab';
import { GeneralOsTabs } from './GeneralOsTabs';
import { ProfileTwoFactorPanel } from './ProfileTwoFactorPanel';
import { SecurityDangerZone, SecurityPasswordBlock } from './SecurityAccount';
import { SecurityEmailBlock } from './SecurityEmail';
import { SecurityPasskeys } from './SecurityPasskeys';
import { SecuritySessions } from './SecuritySessions';

/**
 * Settings > Your Preferences > General (design: settings-profile.php), on the API:
 * GET/PATCH /me/profile, the Gmail mailbox (/mailboxes/me) and Google Calendar
 * (/calendars/me) connections.
 * Tabs: Profile | Email | Calling | Calendar | Tasks | Security | Automation.
 */

const TABS = [
  { id: 'tab-profile', label: 'Profile' },
  { id: 'tab-email', label: 'Email' },
  { id: 'tab-calling', label: 'Calling' },
  { id: 'tab-calendar', label: 'Calendar' },
  { id: 'tab-tasks', label: 'Tasks' },
  { id: 'tab-security', label: 'Security' },
  { id: 'tab-automation', label: 'Automation' },
];

/** Security and Automation stay in More at every width, matching the design bar. */
const LANGUAGES: [Profile['language'], string][] = [
  ['en', 'English'],
  ['hi', 'Hindi'],
  ['es', 'Español'],
  ['fr', 'Français'],
  ['de', 'Deutsch'],
];

const REGION_FORMATS: [Profile['regionFormat'], string, string][] = [
  ['us', 'United States', 'Dates and times: October 15, 2026, 10/15/2026, 1:03 AM'],
  ['uk', 'United Kingdom', 'Dates and times: 15 October 2026, 15/10/2026, 1:03 am'],
  ['in', 'India', 'Dates and times: 15 October 2026, 15/10/2026, 1:03 am'],
  ['de', 'Germany', 'Dates and times: 15. Oktober 2026, 15.10.2026, 01:03'],
];

/** Personal timezone for activity timestamps (QA B5). Empty = business default. */
const PROFILE_TIMEZONES: [string, string][] = [
  ['', 'Use account default'],
  ['America/Los_Angeles', 'UTC −08:00 Los Angeles'],
  ['America/Denver', 'UTC −07:00 Denver'],
  ['America/Chicago', 'UTC −06:00 Chicago'],
  ['America/New_York', 'UTC −05:00 New York'],
  ['UTC', 'UTC +00:00 UTC'],
  ['Europe/London', 'UTC +00:00 London'],
  ['Europe/Berlin', 'UTC +01:00 Berlin'],
  ['Asia/Dubai', 'UTC +04:00 Dubai'],
  ['Asia/Kolkata', 'UTC +05:30 Kolkata (IST)'],
  ['Asia/Singapore', 'UTC +08:00 Singapore'],
  ['Asia/Tokyo', 'UTC +09:00 Tokyo'],
  ['Australia/Sydney', 'UTC +10:00 Sydney'],
];

/** Mark a hidden form field dirty the same way Default Home Page does for the save bar. */
function setHiddenInputValue(input: HTMLInputElement | null, next: string) {
  if (!input) return;
  const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set;
  setter?.call(input, next);
  input.dispatchEvent(new Event('input', { bubbles: true }));
}

const TASK_DUE: [Profile['preferences']['taskDefaultDue'], string][] = [
  ['none', 'No due date'],
  ['today', 'Today'],
  ['tomorrow', 'Tomorrow'],
  ['in_3_business_days', 'In 3 business days'],
  ['in_1_week', 'In 1 week'],
  ['in_2_weeks', 'In 2 weeks'],
  ['in_1_month', 'In 1 month'],
  ['in_3_months', 'In 3 months'],
  ['in_6_months', 'In 6 months'],
];

const TASK_REMINDER: [Profile['preferences']['taskDefaultReminder'], string][] = [
  ['none', 'No reminder'],
  ['at_due_time', 'At task due time'],
  ['30_minutes_before', '30 minutes before'],
  ['1_hour_before', '1 hour before'],
  ['1_day_before', '1 day before'],
];

/** Due time: 8:00 AM to 5:00 PM on the half hour, as the design. */
const TASK_TIMES: [string, string][] = Array.from({ length: 19 }, (_, i) => {
  const minutes = 8 * 60 + i * 30;
  const hh = Math.floor(minutes / 60);
  const mm = minutes % 60;
  const label = new Date(2000, 0, 1, hh, mm).toLocaleTimeString('en-US', {
    hour: 'numeric',
    minute: '2-digit',
  });
  return [`${String(hh).padStart(2, '0')}:${String(mm).padStart(2, '0')}`, label];
});

/** Messages for GMAIL_CONNECT_ERRORS / CALENDAR_CONNECT_ERRORS; any other code gets a generic one. */
const CONNECT_ERRORS: Record<string, string> = {
  invalid_state: 'The connection link expired. Please try again.',
  access_denied: 'You cancelled the Google sign-in.',
  missing_scope: 'Allow all the permissions Google asks for, then try again.',
  no_refresh_token: 'Google did not grant lasting access. Please try again.',
  no_mailbox: 'That Google account has no Gmail mailbox.',
  mailbox_in_use: 'Another CRM user already connected that Gmail address.',
  calendar_in_use: 'Another CRM user already connected that calendar.',
  connect_failed: 'Something went wrong while connecting. Please try again.',
};

const initialsOf = (name: string) =>
  name
    .split(/\s+/)
    .filter(Boolean)
    .slice(0, 2)
    .map((w) => (w[0] ?? '').toUpperCase())
    .join('');

/** While a connection's first sync runs, its status is read again this often… */
const SYNC_POLL_MS = 5_000;
/** …at most this many times (3 minutes). */
const SYNC_POLL_MAX = 36;

const field = (form: HTMLFormElement, name: string) =>
  (form.elements.namedItem(name) as HTMLInputElement | HTMLSelectElement | null)?.value ?? '';
const textOrNull = (v: string) => (v.trim() ? v.trim() : null);

/** Writes a hidden field the way the browser would, so the settings save bar notices. */
function writeHidden(input: HTMLInputElement, value: string) {
  const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set;
  setter?.call(input, value);
  input.dispatchEvent(new Event('input', { bubbles: true }));
}

/**
 * Due date, due time and reminder as the design's dropdowns. The hidden fields carry the
 * values, so Save and Cancel still work.
 */
function TaskDefaultsFields({
  profile,
  resetRef,
}: {
  profile: Profile;
  resetRef: { current: () => void };
}) {
  const saved = profile.preferences;
  const [due, setDue] = useState(saved.taskDefaultDue);
  const [time, setTime] = useState(saved.taskDefaultTime ?? '08:00');
  const [reminder, setReminder] = useState(saved.taskDefaultReminder);
  const dueRef = useRef<HTMLInputElement>(null);
  const timeRef = useRef<HTMLInputElement>(null);
  const reminderRef = useRef<HTMLInputElement>(null);

  const restore = useCallback(() => {
    setDue(saved.taskDefaultDue);
    setTime(saved.taskDefaultTime ?? '08:00');
    setReminder(saved.taskDefaultReminder);
  }, [saved.taskDefaultDue, saved.taskDefaultTime, saved.taskDefaultReminder]);

  useEffect(() => {
    resetRef.current = restore;
  }, [resetRef, restore]);
  useEffect(() => {
    restore();
  }, [restore]);

  const pick =
    (input: { current: HTMLInputElement | null }, set: (value: string) => void) =>
    (next: string) => {
      if (!next || !input.current) return;
      writeHidden(input.current, next);
      set(next);
    };

  return (
    <div className="set-tasks-grid">
      <div className="field">
        <label className="field__label" htmlFor="t-due">
          Due date
        </label>
        <input ref={dueRef} type="hidden" name="task_due" value={due} readOnly />
        <CustomSelect
          id="t-due"
          placeholder="Due date"
          value={due}
          searchable={false}
          menuActions={false}
          options={TASK_DUE.map(([value, label]) => ({ value, label }))}
          onChange={pick(dueRef, (next) =>
            setDue(next as Profile['preferences']['taskDefaultDue']),
          )}
        />
      </div>
      <div className="field">
        <label className="field__label" htmlFor="t-time">
          Due time
        </label>
        <input ref={timeRef} type="hidden" name="task_time" value={time} readOnly />
        <CustomSelect
          id="t-time"
          placeholder="Due time"
          searchPlaceholder="Search times"
          value={time}
          searchable
          menuActions={false}
          options={TASK_TIMES.map(([value, label]) => ({ value, label }))}
          onChange={pick(timeRef, setTime)}
        />
      </div>
      <div className="field">
        <label className="field__label" htmlFor="t-reminder">
          Reminder
        </label>
        <input ref={reminderRef} type="hidden" name="task_reminder" value={reminder} readOnly />
        <CustomSelect
          id="t-reminder"
          placeholder="Reminder"
          value={reminder}
          searchable={false}
          menuActions={false}
          options={TASK_REMINDER.map(([value, label]) => ({ value, label }))}
          onChange={pick(reminderRef, (next) =>
            setReminder(next as Profile['preferences']['taskDefaultReminder']),
          )}
        />
      </div>
    </div>
  );
}

export function ProfileSettingsView() {
  const toast = useToast();
  const applyProfile = useApplyProfile();
  const router = useRouter();
  const searchParams = useSearchParams();
  const businessTimeZone = useCurrentUser().business.timezone;
  const [tab, setTab] = useHashTab(TABS);

  const [profile, setProfile] = useState<Profile | null>(null);
  const [homePage, setHomePage] = useState<HomePage>('home');
  const [language, setLanguage] = useState<Profile['language']>('en');
  const [regionFormat, setRegionFormat] = useState<Profile['regionFormat']>('us');
  const [timezone, setTimezone] = useState('');
  const homeInputRef = useRef<HTMLInputElement>(null);
  const languageInputRef = useRef<HTMLInputElement>(null);
  const formatInputRef = useRef<HTMLInputElement>(null);
  const timezoneInputRef = useRef<HTMLInputElement>(null);
  const resetTaskDefaults = useRef<() => void>(() => {});
  const [mailbox, setMailbox] = useState<MyMailbox | null>(null);
  const [calendar, setCalendar] = useState<MyCalendar | null>(null);
  const [signOutOpen, setSignOutOpen] = useState(false);
  const [signOutAllOpen, setSignOutAllOpen] = useState(false);
  const [confirmDisconnect, setConfirmDisconnect] = useState<'gmail' | 'calendar' | null>(null);
  const updatedAt = useRef<string | undefined>(undefined);

  const timezoneSelectOptions = useMemo(() => {
    const rows = PROFILE_TIMEZONES.map(([value, label]) =>
      value === ''
        ? { value: '', label: `Use account default (${businessTimeZone})` }
        : { value, label },
    );
    if (profile?.timezone && !rows.some((row) => row.value === profile.timezone)) {
      rows.splice(1, 0, { value: profile.timezone, label: profile.timezone });
    }
    return rows;
  }, [businessTimeZone, profile?.timezone]);

  const formatSelectOptions = useMemo(
    () => REGION_FORMATS.map(([value, label]) => ({ value, label })),
    [],
  );

  const languageSelectOptions = useMemo(
    () => LANGUAGES.map(([value, label]) => ({ value, label })),
    [],
  );

  useEffect(() => {
    getProfile().then(
      (p) => {
        updatedAt.current = p.updatedAt;
        setProfile(p);
        setHomePage(p.preferences.defaultHomePage);
        setLanguage(p.language);
        setRegionFormat(p.regionFormat);
        setTimezone(p.timezone ?? '');
      },
      (err) => toast(errorText(err), 'danger'),
    );
    getMyMailbox().then(setMailbox, () => {});
    getMyCalendar().then(setCalendar, () => {});
  }, [toast]);

  /* result of the Google connect round trip (/settings/email, /settings/calendar) */
  useEffect(() => {
    for (const [key, label] of [
      ['email', 'Gmail'],
      ['calendar', 'Google Calendar'],
    ] as const) {
      const v = searchParams.get(key);
      if (!v) continue;
      if (v === 'connected') {
        toast(`${label} connected`, 'success');
        // Read the new connection right away (QA #443), not only the one read on load.
        if (key === 'email') getMyMailbox().then(setMailbox, () => {});
        else getMyCalendar().then(setCalendar, () => {});
      } else {
        const code = v.replace(/^error-/, '');
        toast(
          (Object.hasOwn(CONNECT_ERRORS, code) && CONNECT_ERRORS[code]) ||
            `Could not connect ${label}. Please try again.`,
          'danger',
        );
      }
      router.replace(`/settings/profile#tab-${key}`);
    }
  }, [searchParams, router, toast]);

  // A fresh connection syncs first. Keep reading its status until the sync is done, so the
  // badge turns from "Syncing" to "Connected" without a page reload (QA #443). The timer must
  // not depend on the connection object: each read replaced that object and cleared the timer
  // before it could fire, so the page stayed on Syncing until a reload.
  const calendarSyncing =
    calendar?.connected === true &&
    (calendar.status === 'syncing' || (calendar.status === 'connected' && !calendar.lastSyncedAt));
  useEffect(() => {
    if (!calendarSyncing) return;
    let polls = 0;
    let stopped = false;
    const read = (count: boolean) => {
      if (stopped) return;
      if (count) {
        if (polls >= SYNC_POLL_MAX) return;
        polls += 1;
      }
      getMyCalendar().then(
        (next) => {
          if (!stopped) setCalendar(next);
        },
        () => {},
      );
    };
    const timer = window.setInterval(() => read(true), SYNC_POLL_MS);
    const onFocus = () => read(false);
    const onVisible = () => {
      if (document.visibilityState === 'visible') read(false);
    };
    window.addEventListener('focus', onFocus);
    document.addEventListener('visibilitychange', onVisible);
    return () => {
      stopped = true;
      window.clearInterval(timer);
      window.removeEventListener('focus', onFocus);
      document.removeEventListener('visibilitychange', onVisible);
    };
  }, [calendarSyncing]);
  const mailboxSyncing =
    mailbox?.connected === true &&
    (mailbox.status === 'syncing' || (mailbox.status === 'connected' && !mailbox.lastSyncedAt));
  useEffect(() => {
    if (!mailboxSyncing) return;
    let polls = 0;
    let stopped = false;
    const read = (count: boolean) => {
      if (stopped) return;
      if (count) {
        if (polls >= SYNC_POLL_MAX) return;
        polls += 1;
      }
      getMyMailbox().then(
        (next) => {
          if (!stopped) setMailbox(next);
        },
        () => {},
      );
    };
    const timer = window.setInterval(() => read(true), SYNC_POLL_MS);
    const onFocus = () => read(false);
    const onVisible = () => {
      if (document.visibilityState === 'visible') read(false);
    };
    window.addEventListener('focus', onFocus);
    document.addEventListener('visibilitychange', onVisible);
    return () => {
      stopped = true;
      window.clearInterval(timer);
      window.removeEventListener('focus', onFocus);
      document.removeEventListener('visibilitychange', onVisible);
    };
  }, [mailboxSyncing]);

  /** PATCH /me/profile with the loaded `updatedAt`; false keeps the unsaved changes. */
  const save = useCallback(
    async (body: UpdateProfileBody) => {
      try {
        const p = await updateProfile({ ...body, updatedAt: updatedAt.current });
        updatedAt.current = p.updatedAt;
        setProfile(p);
        applyProfile(p);
      } catch (err) {
        toast(
          isApiError(err) && err.isConflict
            ? 'Your profile changed somewhere else. Reload the page to see the latest values.'
            : errorText(err),
          'danger',
        );
        return false;
      }
    },
    [toast, applyProfile],
  );

  const saveProfile = useCallback(
    (form: HTMLFormElement) => {
      const country = field(form, 'phone_country');
      const phoneRaw = field(form, 'phone').trim();
      if (phoneRaw && phoneRaw !== '+1' && !/^\+?[0-9][0-9\s().-]*$/.test(phoneRaw)) {
        toast('Enter a phone number with digits only', 'danger');
        return false;
      }
      const phoneDigits = phoneRaw.replace(/\D/g, '');
      if (phoneRaw && phoneRaw !== '+1' && (phoneDigits.length < 7 || phoneDigits.length > 15)) {
        toast('Enter a phone number with 7 to 15 digits', 'danger');
        return false;
      }
      return save({
        firstName: textOrNull(field(form, 'first_name')),
        lastName: textOrNull(field(form, 'last_name')),
        phone: !phoneRaw || phoneRaw === '+1' ? null : phoneRaw,
        language: field(form, 'language') as Profile['language'],
        regionFormat: field(form, 'format') as Profile['regionFormat'],
        timezone: textOrNull(field(form, 'timezone')),
        preferences: {
          defaultHomePage: (field(form, 'home_page') ||
            'home') as Profile['preferences']['defaultHomePage'],
        },
        // country is UI-only until a dedicated field exists
        ...(country ? {} : {}),
      });
    },
    [save, toast],
  );

  const saveMeetingDefaults = useCallback(
    (form: HTMLFormElement) => {
      const on = (name: string) =>
        (form.elements.namedItem(name) as HTMLInputElement | null)?.checked ?? false;
      return save({
        preferences: {
          meetingDefaultMinutes: Number(field(form, 'meeting_length')),
          meetingBufferMinutes: Number(field(form, 'buffer')),
          calendarSync: on('calendar_sync'),
          availabilityCalendar: (field(form, 'availability_calendar') ||
            'primary') as Profile['preferences']['availabilityCalendar'],
          outOfOfficeSync: on('ooo_sync'),
          meetingsSlug: field(form, 'meetings_url').trim().toLowerCase(),
        },
      });
    },
    [save],
  );

  const saveTaskDefaults = useCallback(
    (form: HTMLFormElement) => {
      const listView = form.elements.namedItem('followup_list_view') as HTMLInputElement | null;
      const disqualify = form.elements.namedItem(
        'followup_disqualify_lead',
      ) as HTMLInputElement | null;
      return save({
        preferences: {
          taskDefaultDue: field(form, 'task_due') as Profile['preferences']['taskDefaultDue'],
          taskDefaultReminder: field(
            form,
            'task_reminder',
          ) as Profile['preferences']['taskDefaultReminder'],
          taskDefaultTime: field(form, 'task_time') || '08:00',
          followUpTaskListView: !!listView?.checked,
          followUpTaskDisqualifyLead: !!disqualify?.checked,
        },
      });
    },
    [save],
  );

  const saveAutomation = useCallback(
    (form: HTMLFormElement) => {
      const minimap = form.elements.namedItem('workflow_minimap') as HTMLInputElement | null;
      const raw = field(form, 'workflow_default_zoom').replace(/%/g, '').trim();
      return save({
        preferences: {
          workflowMinimap: !!minimap?.checked,
          workflowDefaultZoom: Number(raw),
        },
      });
    },
    [save],
  );

  const goConnect = async (connect: () => Promise<{ authUrl: string }>) => {
    try {
      const { authUrl } = await connect();
      window.location.assign(authUrl);
    } catch (err) {
      toast(errorText(err), 'danger');
    }
  };

  const onDisconnectGmail = async () => {
    try {
      await disconnectGmail();
      setMailbox(await getMyMailbox());
      toast('Connected inbox removed', 'success');
    } catch (err) {
      toast(errorText(err), 'danger');
    }
  };

  const onUpgradeGmailConsent = async () => {
    try {
      setMailbox(await updateGmailConsent('all'));
      toast('Gmail updated to All Features', 'success');
    } catch (err) {
      toast(errorText(err), 'danger');
    }
  };

  const onDisconnectCalendar = async () => {
    try {
      await disconnectGoogleCalendar();
      setCalendar(await getMyCalendar());
      toast('Calendar disconnected', 'info');
    } catch (err) {
      toast(errorText(err), 'danger');
    }
  };

  const onSignOut = async () => {
    try {
      await signOutExtension();
    } catch {
      // extension may be missing
    }
    try {
      await logout();
    } catch {
      // still leave
    }
    router.replace('/login?signed_out=1');
  };

  const onSignOutAll = async () => {
    try {
      await signOutExtension();
    } catch {
      // extension may be missing
    }
    try {
      await logoutAll();
    } catch {
      // still leave this browser
    }
    router.replace('/login?signed_out=1');
  };

  const closeSignOut = useCallback(() => setSignOutOpen(false), []);
  const closeConfirmDisconnect = useCallback(() => setConfirmDisconnect(null), []);

  const header = (
    <>
      <header className="set-head">
        <div>
          <h1 className="set-head__title">General</h1>
        </div>
      </header>
      <GeneralOsTabs label="General settings" tabs={TABS} active={tab} onSelect={setTab} noMore />
    </>
  );

  if (!profile) {
    return (
      <>
        {header}
        <p className="crm-text-muted">Loading your settings…</p>
      </>
    );
  }

  const [nameFirst = '', ...nameRest] = profile.name.split(' ');

  return (
    <SettingsFormsProvider>
      {header}

      {/* ========================================================== PROFILE */}
      <TabPanel id="tab-profile" active={tab}>
        <p className="set-preferences-note">These preferences only apply to you.</p>

        <SettingsForm
          onSave={saveProfile}
          onReset={() => {
            setHomePage(profile.preferences.defaultHomePage);
            setLanguage(profile.language);
            setRegionFormat(profile.regionFormat);
            setTimezone(profile.timezone ?? '');
          }}
        >
          <div className="card set-card">
            <div className="set-card__head">
              <div>
                <h2 className="set-card__title">Global</h2>
                <p className="set-card__sub">This applies across any CRM accounts you have.</p>
              </div>
            </div>

            <div className="photo-row">
              <div
                className="photo-row__img"
                id="profile-photo"
                data-initials={initialsOf(profile.name)}
              >
                {profile.hasAvatar ? (
                  <img
                    src={`/api/v1/me/profile/avatar?v=${encodeURIComponent(profile.updatedAt)}`}
                    alt=""
                  />
                ) : (
                  initialsOf(profile.name)
                )}
              </div>
              <div>
                <div className="photo-row__actions">
                  <label className="btn-crm btn-crm--outline btn-crm--sm">
                    Upload photo
                    <input
                      type="file"
                      accept="image/jpeg,image/png,image/gif"
                      hidden
                      onChange={(event) => {
                        event.stopPropagation();
                        const file = event.target.files?.[0];
                        event.target.value = '';
                        if (!file) return;
                        void (async () => {
                          try {
                            const next = await uploadProfilePhoto(file);
                            setProfile(next);
                            applyProfile(next);
                            toast('Profile photo saved.', 'success');
                          } catch (err) {
                            toast(errorText(err), 'danger');
                          }
                        })();
                      }}
                    />
                  </label>
                  <button
                    type="button"
                    className="btn-crm btn-crm--ghost btn-crm--sm"
                    disabled={!profile.hasAvatar}
                    onClick={() => {
                      void (async () => {
                        try {
                          const next = await removeProfilePhoto();
                          setProfile(next);
                          applyProfile(next);
                          toast('Profile photo removed.', 'success');
                        } catch (err) {
                          toast(errorText(err), 'danger');
                        }
                      })();
                    }}
                  >
                    Remove
                  </button>
                </div>
                <p className="field__help crm-mt-2">JPG, PNG or GIF, up to 2 MB.</p>
              </div>
            </div>

            <div className="set-grid">
              <SuField label="First name" htmlFor="p-first" error="Enter your first name">
                <input
                  className="input"
                  id="p-first"
                  name="first_name"
                  defaultValue={profile.firstName ?? nameFirst}
                  required
                  maxLength={100}
                />
              </SuField>
              <div className="field">
                <label className="field__label" htmlFor="p-last">
                  Last name
                </label>
                <input
                  className="input"
                  id="p-last"
                  name="last_name"
                  defaultValue={profile.lastName ?? nameRest.join(' ')}
                  maxLength={100}
                />
              </div>
              <div className="field">
                <label className="field__label set-label" htmlFor="p-lang">
                  Language{' '}
                  <span
                    className="set-info"
                    tabIndex={0}
                    data-tip-text="Choose the language used for your interface."
                    aria-label="Language info"
                  >
                    <CrmIcon name="info" className="iconSize-14" />
                  </span>
                </label>
                <input
                  ref={languageInputRef}
                  type="hidden"
                  id="p-lang-value"
                  name="language"
                  value={language}
                  onChange={() => {
                    /* Dropdown below is the control; this field only carries the value. */
                  }}
                />
                <CustomSelect
                  id="p-lang"
                  placeholder="Pick a language"
                  searchPlaceholder="Search languages"
                  value={language}
                  searchable
                  options={languageSelectOptions}
                  onChange={(value) => {
                    const next = (value || profile.language) as Profile['language'];
                    setLanguage(next);
                    setHiddenInputValue(languageInputRef.current, next);
                  }}
                />
              </div>
              <div className="field field--full">
                <label className="field__label set-label" htmlFor="p-format">
                  Date, time, and number format{' '}
                  <span
                    className="set-info"
                    tabIndex={0}
                    data-tip-text="How dates, times, and numbers are displayed in your personal view."
                    aria-label="Format info"
                  >
                    <CrmIcon name="info" className="iconSize-14" />
                  </span>
                </label>
                <p className="field__help set-format-preview" data-format-preview>
                  {REGION_FORMATS.find(([v]) => v === regionFormat)?.[2] ?? REGION_FORMATS[0]![2]}
                </p>
                <input
                  ref={formatInputRef}
                  type="hidden"
                  id="p-format-value"
                  name="format"
                  value={regionFormat}
                  onChange={() => {
                    /* Dropdown below is the control; this field only carries the value. */
                  }}
                />
                <CustomSelect
                  id="p-format"
                  placeholder="Pick a format"
                  searchPlaceholder="Search formats"
                  value={regionFormat}
                  searchable
                  options={formatSelectOptions}
                  onChange={(value) => {
                    const next = (value || profile.regionFormat) as Profile['regionFormat'];
                    setRegionFormat(next);
                    setHiddenInputValue(formatInputRef.current, next);
                  }}
                />
              </div>
              <div className="field field--full">
                <label className="field__label set-label" htmlFor="p-timezone">
                  Time zone{' '}
                  <span
                    className="set-info"
                    tabIndex={0}
                    data-tip-text="Used for activity timestamps on records (Email sent, calls, tasks)."
                    aria-label="Time zone info"
                  >
                    <CrmIcon name="info" className="iconSize-14" />
                  </span>
                </label>
                <p className="field__help">
                  India format only changes how dates look. Set this to Kolkata (IST) so timeline
                  times match local time.
                </p>
                <input
                  ref={timezoneInputRef}
                  type="hidden"
                  id="p-timezone-value"
                  name="timezone"
                  value={timezone}
                  onChange={() => {
                    /* Dropdown below is the control; this field only carries the value. */
                  }}
                />
                <CustomSelect
                  id="p-timezone"
                  placeholder="Pick a time zone"
                  searchPlaceholder="Search time zones"
                  value={timezone}
                  searchable
                  options={timezoneSelectOptions}
                  onChange={(value) => {
                    setTimezone(value);
                    setHiddenInputValue(timezoneInputRef.current, value);
                  }}
                />
              </div>
              <div className="field field--full">
                <label className="field__label" htmlFor="p-phone">
                  Phone number
                </label>
                <p className="field__help">
                  We may use this phone number to contact you about security events. Please refer to
                  our privacy policy for{' '}
                  <a className="set-link-inline" href="/settings/privacy" target="_blank">
                    more information <CrmIcon name="external" className="iconSize-14" />
                  </a>
                </p>
                <div className="phone-input-group">
                  <select
                    className="input phone-input-group__country"
                    name="phone_country"
                    aria-label="Country code"
                    defaultValue="US"
                  >
                    <option value="US">US</option>
                    <option value="IN">IN</option>
                    <option value="GB">GB</option>
                    <option value="CA">CA</option>
                    <option value="AU">AU</option>
                    <option value="DE">DE</option>
                    <option value="FR">FR</option>
                  </select>
                  <input
                    className="input phone-input-group__number"
                    id="p-phone"
                    name="phone"
                    type="tel"
                    defaultValue={profile.phone ?? '+1'}
                    maxLength={50}
                    placeholder="+1"
                  />
                </div>
              </div>
            </div>
          </div>

          <div className="card set-card">
            <div className="set-card__head">
              <div>
                <h2 className="set-card__title">Defaults</h2>
                <p className="set-card__sub">This only applies to this CRM account.</p>
              </div>
            </div>
            <div className="set-grid">
              <div className="field">
                <label className="field__label set-label" htmlFor="p-home">
                  Default Home Page{' '}
                  <span
                    className="set-info"
                    tabIndex={0}
                    data-tip-text="Choose the home page that appears when you sign in."
                    aria-label="Default home page info"
                  >
                    <CrmIcon name="info" className="iconSize-14" />
                  </span>
                </label>
                <input
                  ref={homeInputRef}
                  type="hidden"
                  id="p-home-value"
                  name="home_page"
                  value={homePage}
                  onChange={() => {
                    /* The dropdown below is the control; this field only carries the value. */
                  }}
                />
                <CustomSelect
                  id="p-home"
                  className="set-home-select"
                  placeholder="Pick a default home page"
                  searchPlaceholder="Search objects"
                  value={homePage}
                  searchable
                  options={HOME_PAGE_OPTIONS.map((option) => ({
                    value: option.value,
                    label: option.label,
                  }))}
                  onChange={(value) => {
                    const next = (value || profile.preferences.defaultHomePage) as HomePage;
                    setHomePage(next);
                    setHiddenInputValue(homeInputRef.current, next);
                  }}
                />
              </div>
              <div className="field field--full">
                <div className="set-label">
                  <span className="field__label">General working hours</span>
                  <span
                    className="set-info"
                    tabIndex={0}
                    data-tip-text="Set your standard working schedule and meeting availability."
                    aria-label="Working hours info"
                  >
                    <CrmIcon name="info" className="iconSize-14" />
                  </span>
                </div>
                <a
                  href="/settings/user?tab=preferences&sub=working-hours#working-hours"
                  className="set-link-ext"
                  target="_blank"
                  rel="noreferrer"
                >
                  Edit working hours <CrmIcon name="external" className="iconSize-14" />
                </a>
              </div>
            </div>
          </div>
        </SettingsForm>
      </TabPanel>

      {/* ============================================================ EMAIL */}
      <TabPanel id="tab-email" active={tab}>
        <GeneralEmailTab
          mailbox={mailbox}
          profile={profile}
          onProfileUpdated={(p) => {
            updatedAt.current = p.updatedAt;
            setProfile(p);
          }}
          onConnect={() => goConnect(() => connectGmail({ consent: 'all' }))}
          onUpgradeConsent={onUpgradeGmailConsent}
          onDisconnect={() => setConfirmDisconnect('gmail')}
        />
      </TabPanel>

      {/* ========================================================= CALLING */}
      <TabPanel id="tab-calling" active={tab}>
        <GeneralCallingTab
          profile={profile}
          onSavePrefs={(preferences) => save({ preferences })}
          onOpenProfileTab={() => setTab('tab-profile')}
        />
      </TabPanel>

      {/* ========================================================= CALENDAR */}
      <TabPanel id="tab-calendar" active={tab}>
        <GeneralCalendarTab
          profile={profile}
          calendar={calendar}
          onSave={saveMeetingDefaults}
          onConnectGoogle={() => goConnect(connectGoogleCalendar)}
          onDisconnect={() => setConfirmDisconnect('calendar')}
          onReconnect={() => goConnect(connectGoogleCalendar)}
        />
      </TabPanel>

      {/* ============================================================ TASKS */}
      <TabPanel id="tab-tasks" active={tab}>
        <p className="set-preferences-note">These preferences only apply to you.</p>
        <SettingsForm
          className="set-tasks-form"
          onSave={saveTaskDefaults}
          onReset={() => resetTaskDefaults.current()}
        >
          <section className="set-tasks-section">
            <h2 className="set-card__title">Defaults</h2>
            <p className="set-calendar-description">Set preferences for task creation.</p>
            <TaskDefaultsFields profile={profile} resetRef={resetTaskDefaults} />
          </section>
          <section className="set-tasks-section">
            <h2 className="set-card__title">Follow-up tasks</h2>
            <p className="set-calendar-description">Set preferences for follow-up reminders.</p>
            <label className="check set-task-check">
              <input
                type="checkbox"
                name="followup_list_view"
                defaultChecked={profile.preferences.followUpTaskListView !== false}
              />
              <span className="check__box" aria-hidden="true" />
              <span>
                Get prompted to create a follow-up task every time you complete a task from a list
                view
              </span>
            </label>
            <label className="check set-task-check">
              <input
                type="checkbox"
                name="followup_disqualify_lead"
                defaultChecked={profile.preferences.followUpTaskDisqualifyLead !== false}
              />
              <span className="check__box" aria-hidden="true" />
              <span>Get prompted to create a follow-up task every time you disqualify a lead</span>
            </label>
          </section>
        </SettingsForm>
      </TabPanel>

      {/* ========================================================= SECURITY */}
      <TabPanel id="tab-security" active={tab}>
        <div className="set-security-page">
          <p className="set-preferences-note">
            These preferences will only be applied to you. For account security settings please go
            to{' '}
            <Link href="/settings/security" className="set-security-link">
              <strong>account settings</strong> <CrmIcon name="external" className="iconSize-14" />
            </Link>
            .
          </p>
          <section className="set-security-section">
            <h2 className="set-security-title">Security</h2>
            <p className="set-security-subtitle">
              Set preferences related to login and your personal account security.
            </p>
            <SecurityEmailBlock email={profile.email} />
            <SecurityPasswordBlock email={profile.email} />
            <SecurityPasskeys />
            <ProfileTwoFactorPanel />
          </section>
          <SecuritySessions
            onSignOutCurrent={() => setSignOutOpen(true)}
            onLogoutAll={() => setSignOutAllOpen(true)}
          >
            <SecurityDangerZone email={profile.email} />
          </SecuritySessions>
        </div>
      </TabPanel>

      {/* ========================================================= AUTOMATION */}
      <TabPanel id="tab-automation" active={tab}>
        <GeneralAutomationTab profile={profile} onSave={saveAutomation} />
      </TabPanel>

      {/* Sign out (confirmation, centred) */}
      <ConfirmDialog
        id="so"
        open={signOutOpen}
        onClose={closeSignOut}
        title="Sign out?"
        confirmLabel="Sign out"
        onConfirm={onSignOut}
      >
        <p>You will be signed out of the CRM in this browser.</p>
      </ConfirmDialog>

      <SetDialog
        open={signOutAllOpen}
        onClose={() => setSignOutAllOpen(false)}
        labelledBy="security-logout-all-title"
        className="set-security-dialog"
      >
        <DialogHead
          id="security-logout-all-title"
          title="Log out of all sessions?"
          onClose={() => setSignOutAllOpen(false)}
        />
        <div className="set-security-dialog-body">
          <p>This will log you out of all devices and sessions, including this active one.</p>
        </div>
        <div className="set-security-dialog-foot">
          <button
            type="button"
            className="btn-crm btn-crm--danger"
            onClick={() => void onSignOutAll()}
          >
            Log out of all sessions
          </button>
          <button
            type="button"
            className="btn-crm btn-crm--outline"
            onClick={() => setSignOutAllOpen(false)}
          >
            Cancel
          </button>
        </div>
      </SetDialog>

      {/* Disconnect Gmail / Google Calendar */}
      <ConfirmDialog
        id="disconnect"
        open={confirmDisconnect !== null}
        onClose={closeConfirmDisconnect}
        title={confirmDisconnect === 'gmail' ? 'Disconnect Gmail?' : 'Disconnect Google Calendar?'}
        confirmLabel="Disconnect"
        danger
        onConfirm={confirmDisconnect === 'gmail' ? onDisconnectGmail : onDisconnectCalendar}
      >
        <p>
          {confirmDisconnect === 'gmail'
            ? 'The CRM stops syncing your email and you can no longer send email from the CRM until you connect again.'
            : 'The CRM stops syncing your calendar and you can no longer schedule meetings from the CRM until you connect again. Synced events are removed from the CRM.'}
        </p>
      </ConfirmDialog>
    </SettingsFormsProvider>
  );
}
