"use client";

import Link from 'next/link';
import { useEffect, useMemo, useState } from 'react';
import { PageHeader } from '@/components/ui/page-header';
import { WorkspaceAdminPath } from '@/components/workspace-admin-path';
import { apiGet, apiPost, apiPut } from '@/lib/api';
import type { EmailTwoFactorPolicy, AuthSessionChallengeState, EmailTwoFactorRevocationState, LoginChallengeAuditEvent, NotificationReadiness, User } from '@/types';

function SummaryCard({ label, value, detail }: { label: string; value: string; detail: string }) {
  return (
    <div className="rounded-2xl border border-slate-200 bg-white px-4 py-4 shadow-sm">
      <div className="text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400">{label}</div>
      <div className="mt-2 text-2xl font-semibold tracking-tight text-slate-950">{value}</div>
      <div className="mt-1 text-sm leading-5 text-slate-500">{detail}</div>
    </div>
  );
}

function FlowPill({ label, value, tone = 'slate' }: { label: string; value: number; tone?: 'slate' | 'blue' | 'emerald' | 'amber' }) {
  const toneClasses = {
    slate: 'bg-slate-200',
    blue: 'bg-blue-500',
    emerald: 'bg-emerald-500',
    amber: 'bg-amber-500',
  } as const;
  return (
    <div className="rounded-2xl border border-slate-200 bg-white px-4 py-4 shadow-sm">
      <div className="flex items-center justify-between gap-3">
        <div>
          <div className="text-sm font-semibold text-slate-900">{label}</div>
          <div className="mt-1 text-xs text-slate-500">{value}% of the current account-security picture.</div>
        </div>
        <div className="text-lg font-semibold text-slate-900">{value}%</div>
      </div>
      <div className="mt-3 h-2 rounded-full bg-slate-100">
        <div className={`h-2 rounded-full ${toneClasses[tone]}`} style={{ width: `${Math.max(8, Math.min(100, value))}%` }} />
      </div>
    </div>
  );
}

export default function ProfilePage() {
  const [currentUser, setCurrentUser] = useState<User | null>(null);
  const [profileForm, setProfileForm] = useState({ firstName: '', lastName: '', email: '' });
  const [passwordForm, setPasswordForm] = useState({ currentPassword: '', newPassword: '', confirmPassword: '' });
  const [loading, setLoading] = useState(true);
  const [savingProfile, setSavingProfile] = useState(false);
  const [savingPassword, setSavingPassword] = useState(false);
  const [sendingVerification, setSendingVerification] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);
  const [emailTwoFactorPolicy, setEmailTwoFactorPolicy] = useState<EmailTwoFactorPolicy | null>(null);
  const [authSession, setAuthSession] = useState<AuthSessionChallengeState | null>(null);
  const [challengeAudit, setChallengeAudit] = useState<LoginChallengeAuditEvent[]>([]);
  const [revocation, setRevocation] = useState<EmailTwoFactorRevocationState | null>(null);
  const [revokingTrustedSession, setRevokingTrustedSession] = useState(false);
  const [notificationReadiness, setNotificationReadiness] = useState<NotificationReadiness | null>(null);

  async function loadProfile() {
    try {
      setLoading(true);
      setError(null);
      const [{ user }, { profile }, { policy, authSession, audit, revocation }, { readiness }] = await Promise.all([
        apiGet<{ user: User }>('/api/auth/me'),
        apiGet<{ profile: User }>('/api/profile'),
        apiGet<{ policy: EmailTwoFactorPolicy; authSession: AuthSessionChallengeState; audit: LoginChallengeAuditEvent[]; revocation: EmailTwoFactorRevocationState }>('/api/auth/email-2fa/policy'),
        apiGet<{ readiness: NotificationReadiness }>('/api/notifications/readiness'),
      ]);
      setCurrentUser(user);
      setEmailTwoFactorPolicy(policy);
      setAuthSession(authSession);
      setChallengeAudit(audit ?? []);
      setRevocation(revocation ?? null);
      setNotificationReadiness(readiness ?? null);
      setProfileForm({
        firstName: profile.firstName ?? '',
        lastName: profile.lastName ?? '',
        email: profile.email ?? '',
      });
    } catch (err: any) {
      setError(err?.message ?? 'Failed to load account settings');
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    loadProfile();
  }, []);

  async function sendVerificationEmail() {
    try {
      setSendingVerification(true);
      setError(null);
      setSuccess(null);
      const result = await apiPost<{ queued: boolean; alreadyVerified?: boolean; deliveryStatus?: string }>('/api/auth/email-verification/request', {});
      setSuccess(result.alreadyVerified ? 'This email is already verified.' : `Verification email ${result.deliveryStatus === 'SENT' ? 'sent' : 'prepared'} successfully.`);
      await loadProfile();
    } catch (err: any) {
      setError(err?.message ?? 'Failed to prepare verification email');
    } finally {
      setSendingVerification(false);
    }
  }

  async function saveProfile(e: React.FormEvent) {
    e.preventDefault();
    try {
      setSavingProfile(true);
      setError(null);
      setSuccess(null);
      const { profile } = await apiPut<{ profile: User }>('/api/profile', profileForm);
      setProfileForm({
        firstName: profile.firstName ?? '',
        lastName: profile.lastName ?? '',
        email: profile.email ?? '',
      });
      setSuccess('Profile updated successfully.');
      await loadProfile();
    } catch (err: any) {
      setError(err?.message ?? 'Failed to update profile');
    } finally {
      setSavingProfile(false);
    }
  }

  async function savePassword(e: React.FormEvent) {
    e.preventDefault();
    if (passwordForm.newPassword !== passwordForm.confirmPassword) {
      setError('New password and confirmation do not match.');
      setSuccess(null);
      return;
    }

    try {
      setSavingPassword(true);
      setError(null);
      setSuccess(null);
      await apiPost('/api/profile/password', {
        currentPassword: passwordForm.currentPassword,
        newPassword: passwordForm.newPassword,
      });
      setPasswordForm({ currentPassword: '', newPassword: '', confirmPassword: '' });
      setSuccess('Password changed successfully.');
    } catch (err: any) {
      setError(err?.message ?? 'Failed to change password');
    } finally {
      setSavingPassword(false);
    }
  }

  async function revokeTrustedSession() {
    try {
      setRevokingTrustedSession(true);
      setError(null);
      setSuccess(null);
      await apiPost<{ revoked: boolean }>('/api/auth/email-2fa/revoke-trusted-session', {});
      setSuccess('Trusted email 2FA session grace was revoked for this browser. The next eligible login will require a fresh challenge.');
      await loadProfile();
    } catch (err: any) {
      setError(err?.message ?? 'Failed to revoke trusted session grace');
    } finally {
      setRevokingTrustedSession(false);
    }
  }

  const roleLabel = currentUser?.isSuperAdmin ? 'Super Admin' : currentUser?.role === 'ORG_ADMIN' ? 'Company Admin' : 'Dispatcher';
  const verificationLabel = useMemo(() => currentUser?.emailVerifiedAt ? 'Verified' : 'Verification needed', [currentUser?.emailVerifiedAt]);
  const emailChallengeRequiredByPolicy = Boolean(emailTwoFactorPolicy?.requiredForCurrentUser);
  const workspaceBrandName = currentUser?.organization?.name || 'Your workspace';
  const workspaceReplyToPreview = notificationReadiness?.workspaceReplyToSupported ? `ops@${workspaceBrandName.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'workspace'}.example.com` : (notificationReadiness?.replyTo || null);
  const accountSecurityItems = useMemo(() => {
    const verified = currentUser?.emailVerifiedAt ? 100 : 35;
    const challenge = authSession?.challengeSatisfied ? 100 : emailChallengeRequiredByPolicy ? 45 : 70;
    const delivery = notificationReadiness?.replyToGovernanceMode === 'WORKSPACE_REPLY_TO_ALLOWED' ? 85 : 65;
    const recovery = revocation?.canRevokeTrustedSession ? 80 : authSession?.trustedUntil ? 65 : 90;
    return { verified, challenge, delivery, recovery };
  }, [authSession?.challengeSatisfied, authSession?.trustedUntil, currentUser?.emailVerifiedAt, emailChallengeRequiredByPolicy, notificationReadiness?.replyToGovernanceMode, revocation?.canRevokeTrustedSession]);

  if (loading) {
    return <div className="text-sm text-gray-500">Loading account settings...</div>;
  }

  return (
    <div className="space-y-6">
      <PageHeader title="Profile & Security" subtitle="Manage your account identity, sign-in protections, and how this profile fits the workspace." />

      <WorkspaceAdminPath
        eyebrow="Account area"
        title="Profile and account security"
        subtitle="This page keeps your name, email, password, and sign-in safety in one place."
        helper={currentUser?.isSuperAdmin ? 'Platform controls stay in Super Admin. This page is for your own name, email, password, and sign-in safety.' : 'Company settings are separate. This page is for your own name, email, password, and sign-in safety.'}
        links={[
          { href: '/profile', label: 'Profile & Security', description: 'Identity, password, and email challenge controls for the current account.' },
          { href: '/company', label: 'Workspace Settings', description: 'Company profile, users, and team access.' },
          { href: '/company/integrations', label: 'Third-Party Integrations', description: 'Email, phone, maps, accounting, and payment setup for admins.' },
        ]}
      />

      {error ? <div className="rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">{error}</div> : null}
      {success ? <div className="rounded-xl border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm text-emerald-700">{success}</div> : null}

      <section className="grid gap-4 xl:grid-cols-4">
        <SummaryCard label="Account role" value={roleLabel} detail={currentUser?.isSuperAdmin ? 'Platform support access.' : currentUser?.role === 'ORG_ADMIN' ? 'Company administration and daily operations.' : 'Daily workspace operations and follow-up.'} />
        <SummaryCard label="Email verification" value={verificationLabel} detail={currentUser?.emailVerifiedAt ? `Verified on ${new Date(currentUser.emailVerifiedAt).toLocaleDateString()}` : 'Verify this address before using account recovery or protected sign-in.'} />
        <SummaryCard label="Session method" value={authSession?.authMethod === 'EMAIL_2FA' ? 'Email 2FA' : 'Password only'} detail={authSession?.challengeSatisfied ? 'This current session completed the protected sign-in step.' : 'This current session did not complete an email challenge.'} />
        <SummaryCard label="Email messages" value={notificationReadiness?.replyToGovernanceMode === 'WORKSPACE_REPLY_TO_ALLOWED' ? 'Company reply address' : 'Platform reply address'} detail="Email message setup is handled in Workspace Settings when admins need it." />
      </section>

      <section className="grid gap-4 xl:grid-cols-[1.1fr_0.9fr]">
        <div className="rounded-3xl border border-slate-200 bg-white p-6 shadow-sm">
          <div className="flex items-start justify-between gap-4">
            <div>
              <div className="text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400">Account security</div>
              <h2 className="mt-2 text-xl font-semibold tracking-tight text-slate-950">Security at a glance</h2>
              <p className="mt-2 text-sm text-slate-600">A simple look at your email verification, sign-in protection, and account recovery options.</p>
            </div>
            <div className="rounded-2xl border border-blue-200 bg-blue-50 px-4 py-3 text-sm text-blue-800">Your main account safety checks are grouped here first. Deeper details stay closed unless needed.</div>
          </div>
          <div className="mt-6 grid gap-3 sm:grid-cols-2">
            <FlowPill label="Email verified" value={accountSecurityItems.verified} tone={currentUser?.emailVerifiedAt ? 'emerald' : 'amber'} />
            <FlowPill label="Sign-in protection" value={accountSecurityItems.challenge} tone={authSession?.challengeSatisfied ? 'blue' : emailChallengeRequiredByPolicy ? 'amber' : 'slate'} />
            <FlowPill label="Email message setup" value={accountSecurityItems.delivery} tone="blue" />
            <FlowPill label="Recovery option" value={accountSecurityItems.recovery} tone={revocation?.canRevokeTrustedSession ? 'emerald' : 'slate'} />
          </div>
        </div>

        <div className="rounded-3xl border border-slate-200 bg-white p-6 shadow-sm">
          <div className="text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400">Workspace links</div>
          <h2 className="mt-2 text-xl font-semibold tracking-tight text-slate-950">Go where you need next</h2>
          <p className="mt-2 text-sm text-slate-600">This keeps profile work connected to the pages users usually need right after reviewing account or security status.</p>
          <div className="mt-6 grid gap-3">
            {[
              { href: '/company', title: 'Workspace settings', detail: 'Company profile, users, and setup.' },
              { href: '/company/integrations', title: 'Third-Party Integrations', detail: 'Connect email, phone, maps, accounting, and payment tools.' },
              { href: '/dashboard', title: 'Return to CORI Briefing', detail: 'Go back to the daily business briefing.' },
              { href: '/dispatch', title: 'Open Dispatch Board', detail: 'Return to the Dispatch Board after reviewing account safety.' },
            ].map((item) => (
              <Link key={item.href} href={item.href} className="rounded-2xl border border-slate-200 bg-slate-50 px-4 py-4 transition hover:border-slate-300 hover:bg-white">
                <div className="text-sm font-semibold text-slate-900">{item.title}</div>
                <div className="mt-1 text-xs leading-5 text-slate-500">{item.detail}</div>
              </Link>
            ))}
          </div>
        </div>
      </section>

      <div className="grid gap-6 lg:grid-cols-[1.05fr_0.95fr]">
        <section id="profile" className="rounded-2xl border bg-white p-6 shadow-sm">
          <h2 className="text-lg font-semibold">Profile details</h2>
          <p className="mt-1 text-sm text-gray-500">These details identify the person currently signed in to this workspace.</p>

          <form onSubmit={saveProfile} className="mt-6 space-y-4">
            <div className="grid gap-4 sm:grid-cols-2">
              <label className="block text-sm">
                <div className="mb-1 font-medium">First name</div>
                <input value={profileForm.firstName} onChange={(e) => setProfileForm((p) => ({ ...p, firstName: e.target.value }))} className="w-full rounded-xl border px-3 py-2" />
              </label>
              <label className="block text-sm">
                <div className="mb-1 font-medium">Last name</div>
                <input value={profileForm.lastName} onChange={(e) => setProfileForm((p) => ({ ...p, lastName: e.target.value }))} className="w-full rounded-xl border px-3 py-2" />
              </label>
            </div>
            <label className="block text-sm">
              <div className="mb-1 font-medium">Email</div>
              <input type="email" value={profileForm.email} onChange={(e) => setProfileForm((p) => ({ ...p, email: e.target.value }))} className="w-full rounded-xl border px-3 py-2" />
            </label>
            <div className={`rounded-xl border px-4 py-3 text-sm ${currentUser?.emailVerifiedAt ? 'border-emerald-200 bg-emerald-50 text-emerald-700' : 'border-amber-200 bg-amber-50 text-amber-700'}`}>
              <div className="font-medium">Email verification status: {verificationLabel}</div>
              <div className="mt-1 text-xs">{currentUser?.emailVerifiedAt ? `Verified on ${new Date(currentUser.emailVerifiedAt).toLocaleString()}` : 'Verify this email before using account recovery or protected sign-in.'}</div>
            </div>
            <div className="flex flex-wrap gap-3">
              <button type="submit" disabled={savingProfile} className="rounded-xl bg-black px-4 py-2 text-sm font-medium text-white disabled:opacity-60">{savingProfile ? 'Saving...' : 'Save profile'}</button>
              <button type="button" onClick={sendVerificationEmail} disabled={sendingVerification || Boolean(currentUser?.emailVerifiedAt)} className="rounded-xl border px-4 py-2 text-sm font-medium disabled:opacity-60">{sendingVerification ? 'Preparing...' : currentUser?.emailVerifiedAt ? 'Email verified' : 'Send verification email'}</button>
            </div>
          </form>
        </section>

        <section className="rounded-2xl border bg-white p-6 shadow-sm">
          <h2 className="text-lg font-semibold">Account context</h2>
          <p className="mt-1 text-sm text-gray-500">This shows your role and company access.</p>
          <div className="mt-6 grid gap-3 text-sm text-gray-600">
            <div className="rounded-xl border bg-gray-50 p-3"><div className="font-medium text-gray-900">Workspace</div><div className="mt-1">{currentUser?.isSuperAdmin ? 'Dispatch Spot Platform' : currentUser?.organization?.name || 'No workspace assigned'}</div></div>
            <div className="rounded-xl border bg-gray-50 p-3"><div className="font-medium text-gray-900">Role</div><div className="mt-1">{roleLabel}</div></div>
            <div className="rounded-xl border bg-gray-50 p-3"><div className="font-medium text-gray-900">Access level</div><div className="mt-1">{currentUser?.isSuperAdmin ? 'Platform admin access' : currentUser?.role === 'ORG_ADMIN' ? 'Company admin access' : 'Daily company access'}</div></div>
            <div className="rounded-xl border bg-gray-50 p-3"><div className="font-medium text-gray-900">Brand preview</div><div className="mt-1">{workspaceBrandName} via Dispatch Spot</div></div>
          </div>
        </section>
      </div>

      <section id="security" className="rounded-2xl border bg-white p-6 shadow-sm max-w-4xl">
        <h2 className="text-lg font-semibold">Password and sign-in protection</h2>
        <p className="mt-1 text-sm text-gray-500">Change your password and review whether this browser has completed protected sign-in.</p>

        <div className={`mt-6 rounded-xl border px-4 py-3 text-sm ${emailChallengeRequiredByPolicy ? 'border-blue-200 bg-blue-50 text-blue-800' : 'border-slate-200 bg-slate-50 text-slate-700'}`}>
          <div className="font-medium">Email sign-in protection</div>
          <div className="mt-1 text-xs">{emailChallengeRequiredByPolicy ? 'This role may need an email code when signing in.' : 'This role does not currently require an email code every time.'}</div>
          <div className="mt-3 grid gap-2 text-[11px] sm:grid-cols-2 xl:grid-cols-4">
            <div className="rounded-lg border border-current/15 bg-white/70 px-3 py-2">Policy enabled: <span className="font-semibold">{emailTwoFactorPolicy?.enabled ? 'Yes' : 'No'}</span></div>
            <div className="rounded-lg border border-current/15 bg-white/70 px-3 py-2">SMTP delivery active: <span className="font-semibold">{emailTwoFactorPolicy?.deliveryActive ? 'Yes' : 'No'}</span></div>
            <div className="rounded-lg border border-current/15 bg-white/70 px-3 py-2">Platform admin sign-in rule: <span className="font-semibold">{emailTwoFactorPolicy?.requireForSuperAdmin ? 'Enabled' : 'Disabled'}</span></div>
            <div className="rounded-lg border border-current/15 bg-white/70 px-3 py-2">Company admin sign-in rule: <span className="font-semibold">{emailTwoFactorPolicy?.requireForOrgAdmin ? 'Enabled' : 'Disabled'}</span></div>
          </div>
        </div>

        <div className={`mt-4 rounded-xl border px-4 py-3 text-sm ${authSession?.challengeSatisfied ? 'border-emerald-200 bg-emerald-50 text-emerald-700' : 'border-slate-200 bg-slate-50 text-slate-700'}`}>
          <div className="font-medium">Current sign-in session</div>
          <div className="mt-1 text-xs">{authSession?.challengeSatisfied ? 'This session completed the protected sign-in step.' : 'This session signed in without an email code.'}</div>
          <div className="mt-2 text-[11px]">Auth method: <span className="font-semibold">{authSession?.authMethod === 'EMAIL_2FA' ? 'Email 2FA' : 'Password only'}</span>{authSession?.emailTwoFactorSatisfiedAt ? <span> · Verified {new Date(authSession.emailTwoFactorSatisfiedAt).toLocaleString()}</span> : null}{authSession?.emailTwoFactorPolicyKey ? <span> · Policy source {authSession.emailTwoFactorPolicyKey}</span> : null}{authSession?.trustedUntil ? <span> · Trusted until {new Date(authSession.trustedUntil).toLocaleString()}</span> : null}</div>
          <div className="mt-3 grid gap-2 text-[11px] sm:grid-cols-2">
            <div className="rounded-lg border border-current/15 bg-white/70 px-3 py-2">Override state: <span className="font-semibold">{emailTwoFactorPolicy?.overrideState ?? 'NONE'}</span></div>
            <div className="rounded-lg border border-current/15 bg-white/70 px-3 py-2">Revocation visible: <span className="font-semibold">{revocation?.revocationVisible ? 'Yes' : 'No'}</span></div>
          </div>
          <div className="mt-2 text-[11px]">{emailTwoFactorPolicy?.overrideReason ?? 'No per-user email 2FA override is currently applied.'}</div>
          <div className="mt-3 flex flex-wrap gap-3">
            <button type="button" onClick={revokeTrustedSession} disabled={revokingTrustedSession || !revocation?.canRevokeTrustedSession} className="rounded-xl border bg-white px-4 py-2 text-sm font-medium disabled:opacity-60">{revokingTrustedSession ? 'Revoking...' : 'Forget this trusted browser'}</button>
          </div>
        </div>

        <form onSubmit={savePassword} className="mt-6 space-y-4">
          <label className="block text-sm">
            <div className="mb-1 font-medium">Current password</div>
            <input type="password" value={passwordForm.currentPassword} onChange={(e) => setPasswordForm((p) => ({ ...p, currentPassword: e.target.value }))} className="w-full rounded-xl border px-3 py-2" />
          </label>
          <div className="grid gap-4 sm:grid-cols-2">
            <label className="block text-sm">
              <div className="mb-1 font-medium">New password</div>
              <input type="password" value={passwordForm.newPassword} onChange={(e) => setPasswordForm((p) => ({ ...p, newPassword: e.target.value }))} className="w-full rounded-xl border px-3 py-2" />
            </label>
            <label className="block text-sm">
              <div className="mb-1 font-medium">Confirm new password</div>
              <input type="password" value={passwordForm.confirmPassword} onChange={(e) => setPasswordForm((p) => ({ ...p, confirmPassword: e.target.value }))} className="w-full rounded-xl border px-3 py-2" />
            </label>
          </div>
          <button type="submit" disabled={savingPassword} className="rounded-xl border bg-white px-4 py-2 text-sm font-medium disabled:opacity-60">{savingPassword ? 'Updating...' : 'Change password'}</button>
        </form>
      </section>

      <details className="group rounded-2xl border bg-white p-6 shadow-sm">
        <summary className="cursor-pointer list-none">
          <div className="flex items-center justify-between gap-3">
            <div>
              <h2 className="text-lg font-semibold">More account details</h2>
              <p className="mt-1 text-sm text-gray-500">Open this only when an admin or support person asks for more account details.</p>
            </div>
            <div className="rounded-full border px-3 py-1 text-xs font-medium text-slate-600 group-open:bg-slate-900 group-open:text-white">Expand</div>
          </div>
        </summary>

        <div className="mt-6 space-y-6">
          <section className="rounded-2xl border bg-white p-6 shadow-sm">
            <h2 className="text-lg font-semibold">Email delivery details</h2>
            <p className="mt-1 text-sm text-gray-500">Dispatch Spot controls email delivery safely. Company email setup belongs in Third-Party Integrations.</p>
            <div className="mt-6 grid gap-3 text-sm text-gray-600 lg:grid-cols-2 xl:grid-cols-4">
              <div className="rounded-xl border bg-gray-50 p-3"><div className="font-medium text-gray-900">Current sender model</div><div className="mt-1">Dispatch Spot managed email sender</div></div>
              <div className="rounded-xl border bg-gray-50 p-3"><div className="font-medium text-gray-900">Company email sending</div><div className="mt-1">Set this up in Third-Party Integrations when available</div></div>
              <div className="rounded-xl border bg-gray-50 p-3"><div className="font-medium text-gray-900">Reply address options</div><div className="mt-1">Managed safely by the workspace setup</div></div>
              <div className="rounded-xl border bg-gray-50 p-3"><div className="font-medium text-gray-900">Verified company domains</div><div className="mt-1">Planned for a later setup step</div></div>
            </div>
            <div className="mt-4 grid gap-3 text-sm text-gray-600 lg:grid-cols-3">
              <div className="rounded-xl border bg-slate-50 p-3"><div className="font-medium text-gray-900">Safety note</div><div className="mt-1">Dispatch Spot keeps sender setup safe so email is less likely to break.</div></div>
              <div className="rounded-xl border bg-slate-50 p-3"><div className="font-medium text-gray-900">What workspaces control</div><div className="mt-1">Who receives messages and what reply address is shown.</div></div>
              <div className="rounded-xl border bg-slate-50 p-3"><div className="font-medium text-gray-900">Later option</div><div className="mt-1">Verified company sending domains can be added later when the setup is ready.</div></div>
            </div>
            <div className="mt-4 grid gap-3 text-sm text-gray-600 lg:grid-cols-3">
              <div className="rounded-xl border bg-white p-3"><div className="font-medium text-gray-900">Workspace brand preview</div><div className="mt-1">{workspaceBrandName} via Dispatch Spot</div></div>
              <div className="rounded-xl border bg-white p-3"><div className="font-medium text-gray-900">Reply address preview</div><div className="mt-1">{workspaceReplyToPreview || notificationReadiness?.replyTo || 'Platform default reply-to'}</div></div>
              <div className="rounded-xl border bg-white p-3"><div className="font-medium text-gray-900">Reply address mode</div><div className="mt-1">{notificationReadiness?.replyToGovernanceMode === 'WORKSPACE_REPLY_TO_ALLOWED' ? 'Company reply address allowed' : 'Platform reply address only'}</div></div>
            </div>
            <div className="mt-4 rounded-xl border bg-slate-50 p-3 text-sm text-gray-600"><div className="font-medium text-gray-900">Email branding direction</div><div className="mt-1">{notificationReadiness?.brandingMode === 'PLATFORM_SENDER_WITH_WORKSPACE_BRANDING' ? 'Company branding can show while Dispatch Spot keeps sending safe.' : 'Platform sender only.'}</div></div>
          </section>

          <section className="rounded-2xl border bg-white p-6 shadow-sm">
            <h2 className="text-lg font-semibold">Recent sign-in code activity</h2>
            <p className="mt-1 text-sm text-gray-500">These recent events help support check whether sign-in codes are working.</p>
            <div className="mt-6 space-y-3">
              {challengeAudit.length ? challengeAudit.slice(0, 5).map((event) => {
                const statusLabel = event.status.replace(/_/g, ' ');
                const detailParts = [
                  `Resends: ${event.resendCount}`,
                  `Failed attempts: ${event.failedAttemptCount}`,
                  event.usedAt ? `Used: ${new Date(event.usedAt).toLocaleString()}` : null,
                  event.lockedAt ? `Locked: ${new Date(event.lockedAt).toLocaleString()}` : null,
                  !event.usedAt && !event.lockedAt ? `Expires: ${new Date(event.expiresAt).toLocaleString()}` : null,
                ].filter(Boolean).join(' · ');

                return (
                <div key={event.id} className="rounded-xl border bg-slate-50 px-4 py-3 text-sm text-slate-700">
                  <div className="flex flex-wrap items-center justify-between gap-3">
                    <div className="font-medium uppercase tracking-wide text-slate-900">{statusLabel}</div>
                    <div className="text-xs text-slate-500">{new Date(event.createdAt).toLocaleString()}</div>
                  </div>
                  <div className="mt-1 text-xs text-slate-500">{detailParts || 'Current account event'}</div>
                </div>
                );
              }) : <div className="rounded-xl border bg-slate-50 px-4 py-3 text-sm text-slate-500">No recent sign-in code activity is available for this account yet.</div>}
            </div>
          </section>
        </div>
      </details>
    </div>
  );
}
