'use client';

/**
 * Dealer Detail Modal
 *
 * Shows dealer contact info, site info, and activity/notes.
 * Opens when clicking the dealer info cell in the admin table.
 */

import React, { useState, useEffect, useCallback } from 'react';
import { Modal } from '@/components/ui/Modal';
import {
  FileText,
  Phone,
  Mail,
  Lock,
  Unlock,
  Globe,
  BarChart3,
  CreditCard,
  Trash2,
  // Support session action icons
  Settings,
  FileEdit,
  FileX,
  Building2,
  Link,
  Upload,
  Menu,
  GlobeLock,
  ShieldCheck,
  Power,
  GlobeIcon,
  // Migration/grandfathering icons
  Info,
  Star,
  // Edit mode icons
  Pencil,
  // GSC / SEO icons
  CheckCircle,
  AlertTriangle,
  RefreshCw,
} from 'lucide-react';
import { STATUS_CHANGE_REASONS } from '@/lib/status-transitions';
import { getDealerSiteUrl } from '@/lib/dealer-site-url';
import { getCanonicalUrl } from '@/lib/seo-utils';
import { JobTypePill } from './JobTypePill';
import styles from './DealerDetailModal.module.css';

// Helper to get human-readable reason label
const getReasonLabel = (reason: string): string => {
  const found = STATUS_CHANGE_REASONS.find((r) => r.value === reason);
  return found?.label || reason;
};

interface MigrationMatch {
  dealerNumber: string;
  contactEmail: string;
  customDomain: string | null;
  matchedOn: 'email' | 'dealerNumber' | 'both';
}

interface GscJob {
  id: string;
  type: string;
  status: string;
  lastError: string | null;
  attempts: number;
  updatedAt: string;
  completedAt: string | null;
}

interface DealerDetail {
  id: string;
  businessName: string | null;
  subdomain: string | null;
  domain: string;
  domainPrefix: string;
  customDomain: string | null;
  customDomainStatus: string;
  subscriptionTier: string;
  status: string;
  dealerNumber: string | null;
  phone: string;
  address: string;
  city: string;
  state: string;
  zip: string;
  country: string;
  contactName: string | null;
  contactEmail: string | null;
  stripeCustomerId: string;
  stripeSubscriptionId: string | null;
  hasLeadForm: boolean;
  hasGrandfatheredCustomDomain: boolean;
  createdAt: string;
  updatedAt: string;
  lastPublishedAt: string | null;
  // GSC / SEO fields
  gscVerificationToken: string | null;
  gscPropertyRegisteredAt: string | null;
  gscLastInspectedAt: string | null;
  gscLastIndexStatus: string | null;
  gscLastSubmittedAt: string | null;
  gscPreflightHealthyAt: string | null;
  gscPreflightError: string | null;
  user: {
    id: string;
    email: string;
    name: string | null;
    role: string;
    createdAt: string;
  };
  stats: {
    pages: number;
    leads: number;
    pageViews: number;
    notes: number;
    recentActivity: number;
  };
  migrationMatches?: MigrationMatch[];
}

interface ActivityItem {
  id: string;
  type: 'note' | 'action';
  timestamp: string;
  adminId: string;
  adminName: string | null;
  adminEmail: string;
  noteType?: string;
  content?: string;
  isEditable?: boolean;
  action?: string;
  details?: Record<string, unknown>;
  reason?: string;
}

interface DealerDetailModalProps {
  isOpen: boolean;
  onClose: () => void;
  dealerId: string | null;
}

interface EditForm {
  email: string;
  businessName: string;
  contactName: string;
  phone: string;
  dealerNumber: string;
  address: string;
  city: string;
  state: string;
  zip: string;
  country: string;
  subdomain: string;
  customDomain: string;
  reason: string;
}

// Map action types to Lucide icons
const ActionIcon = ({ action }: { action: string }) => {
  const iconProps = { size: 16, className: styles.actionIconSvg };
  switch (action) {
    // Admin actions
    case 'start_impersonation':
      return <Lock {...iconProps} />;
    case 'end_impersonation':
      return <Unlock {...iconProps} />;
    case 'update_subdomain':
      return <Globe {...iconProps} />;
    case 'change_email':
      return <Mail {...iconProps} />;
    case 'update_dealer_info':
      return <Building2 {...iconProps} />;
    case 'status_change':
    case 'change_status':
      return <BarChart3 {...iconProps} />;
    case 'tier_change':
      return <CreditCard {...iconProps} />;
    case 'note_deleted':
      return <Trash2 {...iconProps} />;
    // Support session actions
    case 'support_updated_settings':
      return <Settings {...iconProps} />;
    case 'support_edited_page':
      return <FileEdit {...iconProps} />;
    case 'support_deleted_page':
      return <FileX {...iconProps} />;
    case 'support_updated_business_info':
      return <Building2 {...iconProps} />;
    case 'support_updated_links':
      return <Link {...iconProps} />;
    case 'support_published_changes':
      return <Upload {...iconProps} />;
    case 'support_edited_navigation':
    case 'support_deleted_navigation':
      return <Menu {...iconProps} />;
    case 'support_configured_custom_domain':
      return <GlobeLock {...iconProps} />;
    case 'support_verified_custom_domain':
      return <ShieldCheck {...iconProps} />;
    case 'support_activated_custom_domain':
      return <Power {...iconProps} />;
    case 'support_removed_custom_domain':
      return <GlobeIcon {...iconProps} />;
    // Grandfathered custom domain toggle
    case 'toggle_grandfathered_custom_domain':
      return <Star {...iconProps} />;
    default:
      return <FileText {...iconProps} />;
  }
};

// Map note types to Lucide icons
const NoteTypeIcon = ({ noteType }: { noteType: string }) => {
  const iconProps = { size: 16, className: styles.noteIconSvg };
  switch (noteType) {
    case 'support_call':
      return <Phone {...iconProps} />;
    case 'email_sent':
      return <Mail {...iconProps} />;
    default:
      return <FileText {...iconProps} />;
  }
};

const NOTE_TYPE_LABELS: Record<string, string> = {
  manual: 'Note',
  support_call: 'Support Call',
  email_sent: 'Email Sent',
  internal: 'Internal',
};

// Actions to hide from timeline (redundant info)
const HIDDEN_ACTIONS = ['note_added'];

function buildEditForm(dealer: DealerDetail): EditForm {
  return {
    email: dealer.user.email,
    businessName: dealer.businessName || '',
    contactName: dealer.contactName || dealer.user.name || '',
    phone: dealer.phone || '',
    dealerNumber: dealer.dealerNumber || '',
    address: dealer.address || '',
    city: dealer.city || '',
    state: dealer.state || '',
    zip: dealer.zip || '',
    country: dealer.country || '',
    subdomain: dealer.subdomain || '',
    customDomain: dealer.customDomain || '',
    reason: '',
  };
}

interface DealerPerformance {
  traffic: { current: number; previous: number; changePercent: number };
  inquiries: { current: number; previous: number; changePercent: number };
  clicks: { current: number };
}

function TrendValue({ value, changePercent }: { value: number; changePercent: number }) {
  // Neutral dash at exactly 0 so a new dealer with no history doesn't show a
  // misleading ↑ on every metric.
  const trendClass =
    changePercent === 0
      ? styles.perfTrendFlat
      : changePercent > 0
        ? styles.perfTrendUp
        : styles.perfTrendDown;
  const arrow = changePercent === 0 ? '–' : changePercent > 0 ? '↑' : '↓';
  return (
    <span className={styles.perfValue}>
      {value.toLocaleString()}
      <span className={trendClass}>
        {' '}
        {changePercent === 0 ? arrow : `${arrow}${Math.abs(changePercent).toFixed(1)}%`}
      </span>
    </span>
  );
}

export function DealerDetailModal({ isOpen, onClose, dealerId }: DealerDetailModalProps) {
  const [dealer, setDealer] = useState<DealerDetail | null>(null);
  const [gscJobs, setGscJobs] = useState<GscJob[]>([]);
  const [activity, setActivity] = useState<ActivityItem[]>([]);
  const [performance, setPerformance] = useState<DealerPerformance | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [newNote, setNewNote] = useState('');
  const [noteType, setNoteType] = useState<string>('manual');
  const [isAddingNote, setIsAddingNote] = useState(false);
  // Edit mode state
  const [isEditing, setIsEditing] = useState(false);
  const [isSaving, setIsSaving] = useState(false);
  const [editForm, setEditForm] = useState<EditForm>({
    email: '',
    businessName: '',
    contactName: '',
    phone: '',
    dealerNumber: '',
    address: '',
    city: '',
    state: '',
    zip: '',
    country: '',
    subdomain: '',
    customDomain: '',
    reason: '',
  });
  const [editErrors, setEditErrors] = useState<Record<string, string>>({});
  const [editGeneralError, setEditGeneralError] = useState('');
  // Grandfathered toggle state
  const [isTogglingGrandfathered, setIsTogglingGrandfathered] = useState(false);
  const [grandfatheredReason, setGrandfatheredReason] = useState('');
  // GSC action in-flight guard — prevents double-submit on rapid clicks
  const [isGscActioning, setIsGscActioning] = useState(false);
  // GSC action error — surfaces HTTP errors from the reindex endpoint to the admin
  const [gscActionError, setGscActionError] = useState('');

  const fetchDealerDetail = useCallback(async () => {
    if (!dealerId) return;
    setIsLoading(true);
    try {
      const [detailRes, activityRes, perfRes] = await Promise.all([
        fetch(`/api/admin/dealers/${dealerId}/detail`),
        fetch(`/api/admin/dealers/${dealerId}/activity`),
        fetch(`/api/admin/dealers/${dealerId}/stats`),
      ]);

      if (detailRes.ok) {
        const data = await detailRes.json();
        setDealer(data.dealer);
        setGscJobs(data.gscJobs || []);
      }
      if (activityRes.ok) {
        const data = await activityRes.json();
        setActivity(data.activity);
      }
      if (perfRes.ok) {
        setPerformance(await perfRes.json());
      } else {
        // Non-2xx (deleted dealer, transient 500) leaves the section hidden;
        // surface it in the console so it isn't indistinguishable from a
        // dealer that simply has no traffic.
        console.warn(`Dealer performance stats unavailable (HTTP ${perfRes.status}) for ${dealerId}`);
      }
    } catch (error) {
      console.error('Failed to fetch dealer details:', error);
    } finally {
      setIsLoading(false);
    }
  }, [dealerId]);

  useEffect(() => {
    if (isOpen && dealerId) {
      fetchDealerDetail();
    }
  }, [isOpen, dealerId, fetchDealerDetail]);

  // Reset state when modal closes
  useEffect(() => {
    if (!isOpen) {
      setDealer(null);
      setGscJobs([]);
      setActivity([]);
      setPerformance(null);
      setNewNote('');
      setNoteType('manual');
      setIsEditing(false);
      setEditErrors({});
      setEditGeneralError('');
      setIsGscActioning(false);
      setGscActionError('');
    }
  }, [isOpen]);

  const handleStartEdit = () => {
    if (!dealer) return;
    setEditForm(buildEditForm(dealer));
    setEditErrors({});
    setEditGeneralError('');
    setIsEditing(true);
  };

  const handleCancelEdit = () => {
    setIsEditing(false);
    setEditErrors({});
    setEditGeneralError('');
  };

  const handleEditChange = (field: keyof EditForm, value: string) => {
    setEditForm((prev) => ({ ...prev, [field]: value }));
    // Clear field error on change
    if (editErrors[field]) {
      setEditErrors((prev) => {
        const next = { ...prev };
        delete next[field];
        return next;
      });
    }
  };

  const handleSave = async () => {
    if (!dealerId || !dealer) return;

    // Determine what changed
    const emailChanged = editForm.email.trim() !== dealer.user.email;
    const subdomainChanged = editForm.subdomain.trim() !== (dealer.subdomain || '');
    const infoFields = [
      'businessName',
      'contactName',
      'phone',
      'dealerNumber',
      'address',
      'city',
      'state',
      'zip',
      'country',
      'customDomain',
    ] as const;

    const changedInfo: Record<string, string> = {};
    for (const field of infoFields) {
      const currentValue =
        field === 'contactName'
          ? dealer.contactName || dealer.user.name || ''
          : (dealer[field as keyof DealerDetail] as string) || '';
      if (editForm[field] !== currentValue) {
        changedInfo[field] = editForm[field];
      }
    }

    const infoChanged = Object.keys(changedInfo).length > 0;

    // Nothing changed — just exit edit mode
    if (!emailChanged && !infoChanged && !subdomainChanged) {
      setIsEditing(false);
      return;
    }

    setIsSaving(true);
    setEditErrors({});
    setEditGeneralError('');

    type ApiResult = {
      type: 'email' | 'info' | 'subdomain';
      ok: boolean;
      data: Record<string, unknown>;
    };
    const promises: Promise<ApiResult>[] = [];

    if (emailChanged) {
      promises.push(
        fetch(`/api/admin/dealers/${dealerId}/email`, {
          method: 'PATCH',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            newEmail: editForm.email.trim(),
            reason: editForm.reason.trim() || undefined,
          }),
        }).then(async (res) => ({
          type: 'email' as const,
          ok: res.ok,
          data: await res.json(),
        }))
      );
    }

    if (subdomainChanged) {
      promises.push(
        fetch(`/api/admin/dealers/${dealerId}/subdomain`, {
          method: 'PATCH',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            subdomain: editForm.subdomain.trim(),
            reason: editForm.reason.trim() || undefined,
          }),
        }).then(async (res) => ({
          type: 'subdomain' as const,
          ok: res.ok,
          data: await res.json(),
        }))
      );
    }

    if (infoChanged) {
      promises.push(
        fetch(`/api/admin/dealers/${dealerId}/info`, {
          method: 'PATCH',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            ...changedInfo,
            reason: editForm.reason.trim() || undefined,
          }),
        }).then(async (res) => ({
          type: 'info' as const,
          ok: res.ok,
          data: await res.json(),
        }))
      );
    }

    try {
      const results = await Promise.all(promises);
      const newErrors: Record<string, string> = {};
      let hasError = false;

      for (const result of results) {
        if (!result.ok) {
          hasError = true;
          if (result.type === 'email') {
            newErrors.email = (result.data.error as string) || 'Failed to update email';
          } else if (result.type === 'subdomain') {
            newErrors.subdomain = (result.data.error as string) || 'Failed to update subdomain';
          } else {
            // Info endpoint may return fieldErrors and/or a general error
            const fieldErrors = result.data.fieldErrors as Record<string, string> | undefined;
            if (fieldErrors) {
              Object.assign(newErrors, fieldErrors);
            }
            if (result.data.error && !fieldErrors) {
              setEditGeneralError((result.data.error as string) || 'Failed to update dealer info');
            }
          }
        }
      }

      if (hasError) {
        setEditErrors(newErrors);
      } else {
        setIsEditing(false);
        fetchDealerDetail();
      }
    } catch (error) {
      console.error('Failed to save:', error);
      setEditGeneralError('Network error. Please try again.');
    } finally {
      setIsSaving(false);
    }
  };

  const handleAddNote = async () => {
    if (!dealerId || !newNote.trim()) return;
    setIsAddingNote(true);
    try {
      const res = await fetch(`/api/admin/dealers/${dealerId}/notes`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ content: newNote, noteType }),
      });
      if (res.ok) {
        setNewNote('');
        fetchDealerDetail(); // Refresh activity
      }
    } catch (error) {
      console.error('Failed to add note:', error);
    } finally {
      setIsAddingNote(false);
    }
  };

  const handleToggleGrandfathered = async (enabled: boolean) => {
    if (!dealerId) return;
    setIsTogglingGrandfathered(true);
    try {
      const res = await fetch(`/api/admin/dealers/${dealerId}/grandfathered-custom-domain`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          enabled,
          reason: grandfatheredReason.trim() || undefined,
        }),
      });
      if (res.ok) {
        setGrandfatheredReason('');
        fetchDealerDetail(); // Refresh dealer data and activity
      }
    } catch (error) {
      console.error('Failed to toggle grandfathered access:', error);
    } finally {
      setIsTogglingGrandfathered(false);
    }
  };

  const formatDate = (dateStr: string) => {
    return new Date(dateStr).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
    });
  };

  const formatDateTime = (dateStr: string) => {
    return new Date(dateStr).toLocaleString('en-US', {
      month: 'short',
      day: 'numeric',
      hour: 'numeric',
      minute: '2-digit',
    });
  };

  const formatRelativeHours = (dateStr: string): string => {
    const diffMs = Date.now() - new Date(dateStr).getTime();
    const diffH = Math.round(diffMs / (1000 * 60 * 60));
    if (diffH < 1) return 'just now';
    if (diffH === 1) return '1h ago';
    if (diffH < 24) return `${diffH}h ago`;
    const diffD = Math.round(diffH / 24);
    if (diffD === 1) return '1d ago';
    return `${diffD}d ago`;
  };

  const handleGscAction = async () => {
    if (!dealerId || isGscActioning) return;
    setIsGscActioning(true);
    setGscActionError('');
    try {
      const res = await fetch(`/api/admin/dealers/${dealerId}/reindex-gsc`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
      });
      if (!res.ok) {
        const body = await res.json().catch(() => ({}));
        setGscActionError((body.error as string) || `Reindex failed (${res.status})`);
        return;
      }
      fetchDealerDetail();
    } catch (error) {
      console.error('Failed to trigger GSC action:', error);
      setGscActionError('Reindex failed: network error');
    } finally {
      setIsGscActioning(false);
    }
  };

  const getActionDescription = (item: ActivityItem): string => {
    if (!item.action) return '';
    const details = item.details || {};
    switch (item.action) {
      case 'start_impersonation':
        return 'Started support session';
      case 'end_impersonation':
        return 'Ended support session';
      case 'update_subdomain':
        return `Changed subdomain: ${details.oldSubdomain || 'none'} → ${details.newSubdomain}`;
      case 'change_email':
        return `Changed login email: ${details.oldEmail} → ${details.newEmail}`;
      case 'update_dealer_info': {
        const changes = details.changes as
          | Record<string, { old: string | null; new: string }>
          | undefined;
        if (changes) {
          const entries = Object.entries(changes);
          if (entries.length <= 3) {
            return `Updated: ${entries.map(([f, v]) => `${f}: ${v.old || '(empty)'} → ${v.new}`).join(', ')}`;
          }
          // Too many fields — show first 2 with count
          const shown = entries.slice(0, 2);
          return `Updated: ${shown.map(([f, v]) => `${f}: ${v.old || '(empty)'} → ${v.new}`).join(', ')} +${entries.length - 2} more`;
        }
        return 'Updated dealer info';
      }
      case 'status_change':
      case 'change_status': {
        // API stores previousStatus/newStatus
        const oldStatus = details.previousStatus || details.oldStatus || 'unknown';
        const newStatus = details.newStatus || 'unknown';
        return `Changed status: ${oldStatus} → ${newStatus}`;
      }
      case 'tier_change':
        return `Changed tier: ${details.oldTier} → ${details.newTier}`;
      case 'note_deleted':
        return 'Deleted a note';
      // Support session actions (taken while impersonating)
      case 'support_updated_settings':
        return 'Updated lead form settings';
      case 'support_edited_page':
        return `Edited page: ${details.pageTitle || details.pageSlug || 'unknown'}`;
      case 'support_deleted_page':
        return 'Deleted page';
      case 'support_updated_business_info':
        return 'Updated business info';
      case 'support_updated_links':
        return 'Updated quick links';
      case 'support_published_changes':
        return `Published ${details.totalPages || 0} page(s)`;
      case 'support_edited_navigation':
        return `Edited navigation: ${details.label || 'item'}`;
      case 'support_deleted_navigation':
        return `Deleted navigation: ${details.label || 'item'}`;
      case 'support_configured_custom_domain':
        return `Configured custom domain: ${details.domain || 'unknown'}`;
      case 'support_verified_custom_domain':
        return `Verified custom domain: ${details.domain || 'unknown'}`;
      case 'support_activated_custom_domain':
        return `Activated custom domain: ${details.domain || 'unknown'}`;
      case 'support_removed_custom_domain':
        return `Removed custom domain: ${details.domain || 'unknown'}`;
      case 'toggle_grandfathered_custom_domain': {
        const newVal = details.newValue;
        return newVal
          ? 'Granted grandfathered custom domain access'
          : 'Revoked grandfathered custom domain access';
      }
      default:
        // Fallback: replace underscores with spaces, capitalize first letter
        return item.action.replace(/_/g, ' ').replace(/^\w/, (c) => c.toUpperCase());
    }
  };

  if (!isOpen) return null;

  return (
    <Modal
      isOpen={isOpen}
      onClose={onClose}
      size="wide"
      title={dealer?.businessName || dealer?.user.name || 'Dealer Details'}
    >
      <div className={styles.container}>
        {isLoading ? (
          <div className={styles.loading}>
            <div className={styles.spinner}></div>
            <span>Loading dealer details...</span>
          </div>
        ) : dealer ? (
          <>
            {/* Edit Bar */}
            <div className={styles.editBar}>
              {isEditing ? (
                <>
                  <div className={styles.editBarLeft}>
                    <span className={styles.editingLabel}>Editing</span>
                  </div>
                  <div className={styles.editBarRight}>
                    <button
                      onClick={handleCancelEdit}
                      disabled={isSaving}
                      className={styles.cancelButton}
                    >
                      Cancel
                    </button>
                    <button onClick={handleSave} disabled={isSaving} className={styles.saveButton}>
                      {isSaving ? 'Saving...' : 'Save Changes'}
                    </button>
                  </div>
                </>
              ) : (
                <>
                  <div className={styles.editBarLeft} />
                  <div className={styles.editBarRight}>
                    <button onClick={handleStartEdit} className={styles.editButton}>
                      <Pencil size={14} />
                      Edit
                    </button>
                  </div>
                </>
              )}
            </div>

            {editGeneralError && <div className={styles.editGeneralError}>{editGeneralError}</div>}

            {/* Info Sections */}
            <div className={styles.infoGrid}>
              {/* Contact Info */}
              <section className={styles.section}>
                <h3 className={styles.sectionTitle}>Contact Information</h3>
                <dl className={styles.infoList}>
                  {isEditing && (
                    <div className={styles.infoItem}>
                      <dt>Business Name</dt>
                      <dd>
                        <div className={styles.editFieldGroup}>
                          <input
                            type="text"
                            value={editForm.businessName}
                            onChange={(e) => handleEditChange('businessName', e.target.value)}
                            placeholder="Business name"
                            className={`${styles.editInput} ${editErrors.businessName ? styles.editInputError : ''}`}
                          />
                          {editErrors.businessName && (
                            <span className={styles.fieldError}>{editErrors.businessName}</span>
                          )}
                        </div>
                      </dd>
                    </div>
                  )}
                  <div className={styles.infoItem}>
                    <dt>Email</dt>
                    <dd>
                      {isEditing ? (
                        <div className={styles.editFieldGroup}>
                          <input
                            type="email"
                            value={editForm.email}
                            onChange={(e) => handleEditChange('email', e.target.value)}
                            placeholder="Login email"
                            className={`${styles.editInput} ${editErrors.email ? styles.editInputError : ''}`}
                          />
                          {editErrors.email && (
                            <span className={styles.fieldError}>{editErrors.email}</span>
                          )}
                        </div>
                      ) : (
                        dealer.user.email
                      )}
                    </dd>
                  </div>
                  <div className={styles.infoItem}>
                    <dt>Contact Name</dt>
                    <dd>
                      {isEditing ? (
                        <div className={styles.editFieldGroup}>
                          <input
                            type="text"
                            value={editForm.contactName}
                            onChange={(e) => handleEditChange('contactName', e.target.value)}
                            placeholder="Contact name"
                            className={`${styles.editInput} ${editErrors.contactName ? styles.editInputError : ''}`}
                          />
                          {editErrors.contactName && (
                            <span className={styles.fieldError}>{editErrors.contactName}</span>
                          )}
                        </div>
                      ) : (
                        dealer.contactName || dealer.user.name || '—'
                      )}
                    </dd>
                  </div>
                  <div className={styles.infoItem}>
                    <dt>Phone</dt>
                    <dd>
                      {isEditing ? (
                        <div className={styles.editFieldGroup}>
                          <input
                            type="tel"
                            value={editForm.phone}
                            onChange={(e) => handleEditChange('phone', e.target.value)}
                            placeholder="Phone number"
                            className={`${styles.editInput} ${editErrors.phone ? styles.editInputError : ''}`}
                          />
                          {editErrors.phone && (
                            <span className={styles.fieldError}>{editErrors.phone}</span>
                          )}
                        </div>
                      ) : (
                        dealer.phone || '—'
                      )}
                    </dd>
                  </div>
                  <div className={styles.infoItem}>
                    <dt>ZO Number</dt>
                    <dd>
                      {isEditing ? (
                        <div className={styles.editFieldGroup}>
                          <input
                            type="text"
                            value={editForm.dealerNumber}
                            onChange={(e) => handleEditChange('dealerNumber', e.target.value)}
                            placeholder="Dealer/ZO number"
                            className={`${styles.editInput} ${editErrors.dealerNumber ? styles.editInputError : ''}`}
                          />
                          {editErrors.dealerNumber && (
                            <span className={styles.fieldError}>{editErrors.dealerNumber}</span>
                          )}
                        </div>
                      ) : dealer.dealerNumber ? (
                        `#${dealer.dealerNumber}`
                      ) : (
                        '—'
                      )}
                    </dd>
                  </div>
                  <div className={styles.infoItem}>
                    <dt>Address</dt>
                    <dd>
                      {isEditing ? (
                        <div className={styles.editFieldGroup}>
                          <input
                            type="text"
                            value={editForm.address}
                            onChange={(e) => handleEditChange('address', e.target.value)}
                            placeholder="Street address"
                            className={`${styles.editInput} ${editErrors.address ? styles.editInputError : ''}`}
                          />
                          {editErrors.address && (
                            <span className={styles.fieldError}>{editErrors.address}</span>
                          )}
                          <input
                            type="text"
                            value={editForm.city}
                            onChange={(e) => handleEditChange('city', e.target.value)}
                            placeholder="City"
                            className={`${styles.editInput} ${editErrors.city ? styles.editInputError : ''}`}
                          />
                          {editErrors.city && (
                            <span className={styles.fieldError}>{editErrors.city}</span>
                          )}
                          <div className={styles.addressRow}>
                            <input
                              type="text"
                              value={editForm.state}
                              onChange={(e) => handleEditChange('state', e.target.value)}
                              placeholder="ST"
                              maxLength={2}
                              className={`${styles.editInput} ${styles.editInputShort} ${editErrors.state ? styles.editInputError : ''}`}
                            />
                            <input
                              type="text"
                              value={editForm.zip}
                              onChange={(e) => handleEditChange('zip', e.target.value)}
                              placeholder="Zip code"
                              className={`${styles.editInput} ${editErrors.zip ? styles.editInputError : ''}`}
                            />
                          </div>
                          {(editErrors.state || editErrors.zip) && (
                            <span className={styles.fieldError}>
                              {editErrors.state || editErrors.zip}
                            </span>
                          )}
                          <input
                            type="text"
                            value={editForm.country}
                            onChange={(e) => handleEditChange('country', e.target.value)}
                            placeholder="Country"
                            className={`${styles.editInput} ${editErrors.country ? styles.editInputError : ''}`}
                          />
                          {editErrors.country && (
                            <span className={styles.fieldError}>{editErrors.country}</span>
                          )}
                        </div>
                      ) : dealer.address ? (
                        <>
                          {dealer.address}
                          <br />
                          {dealer.city}, {dealer.state} {dealer.zip}
                          <br />
                          {dealer.country}
                        </>
                      ) : (
                        '—'
                      )}
                    </dd>
                  </div>
                  {isEditing && (
                    <div className={styles.infoItem}>
                      <dt>Reason</dt>
                      <dd>
                        <input
                          type="text"
                          value={editForm.reason}
                          onChange={(e) => handleEditChange('reason', e.target.value)}
                          placeholder="Reason for changes (optional)"
                          className={styles.editInput}
                        />
                      </dd>
                    </div>
                  )}
                </dl>
              </section>

              {/* Site Info */}
              <section className={styles.section}>
                <h3 className={styles.sectionTitle}>Site Information</h3>
                <dl className={styles.infoList}>
                  <div className={styles.infoItem}>
                    <dt>Subdomain</dt>
                    <dd>
                      {isEditing ? (
                        <div className={styles.editFieldGroup}>
                          <input
                            type="text"
                            value={editForm.subdomain}
                            onChange={(e) => handleEditChange('subdomain', e.target.value)}
                            placeholder="subdomain"
                            className={`${styles.editInput} ${editErrors.subdomain ? styles.editInputError : ''}`}
                          />
                          {editErrors.subdomain && (
                            <span className={styles.fieldError}>{editErrors.subdomain}</span>
                          )}
                        </div>
                      ) : dealer.subdomain ? (
                        <a
                          href={getDealerSiteUrl(dealer) ?? '#'}
                          target="_blank"
                          rel="noopener noreferrer"
                          className={styles.link}
                        >
                          {dealer.subdomain}.{dealer.domainPrefix}.
                          {dealer.domain === 'ca' ? 'ca' : 'com'}
                        </a>
                      ) : (
                        <span className={styles.notSet}>Not set</span>
                      )}
                    </dd>
                  </div>
                  <div className={styles.infoItem}>
                    <dt>Custom Domain</dt>
                    <dd>
                      {isEditing ? (
                        <div className={styles.editFieldGroup}>
                          <input
                            type="text"
                            value={editForm.customDomain}
                            onChange={(e) => handleEditChange('customDomain', e.target.value)}
                            placeholder="example.com"
                            className={`${styles.editInput} ${editErrors.customDomain ? styles.editInputError : ''}`}
                          />
                          {editErrors.customDomain && (
                            <span className={styles.fieldError}>{editErrors.customDomain}</span>
                          )}
                        </div>
                      ) : dealer.customDomain ? (
                        <>
                          <a
                            href={`https://${dealer.customDomain}`}
                            target="_blank"
                            rel="noopener noreferrer"
                            className={styles.link}
                          >
                            {dealer.customDomain}
                          </a>
                          <span className={styles.domainStatus}>({dealer.customDomainStatus})</span>
                        </>
                      ) : (
                        <span className={styles.notSet}>None</span>
                      )}
                    </dd>
                  </div>
                  {/* Migration Match Info Box - shown if matches found and no custom domain */}
                  {dealer.migrationMatches && dealer.migrationMatches.length > 0 && (
                    <div className={styles.migrationMatchBox}>
                      <div className={styles.migrationMatchHeader}>
                        <Info size={16} />
                        <span>
                          {dealer.subscriptionTier.toLowerCase() === 'starter'
                            ? 'Potential Migration Match Found'
                            : 'Suggested Custom Domain from Migration'}
                        </span>
                      </div>
                      <ul className={styles.migrationMatchList}>
                        {dealer.migrationMatches.map((match, idx) => (
                          <li key={idx}>
                            {match.matchedOn === 'both' && (
                              <>Both email and ZO# match MigrationDealer #{match.dealerNumber}</>
                            )}
                            {match.matchedOn === 'email' && (
                              <>Email matches MigrationDealer #{match.dealerNumber}</>
                            )}
                            {match.matchedOn === 'dealerNumber' && (
                              <>ZO# matches MigrationDealer (email: {match.contactEmail})</>
                            )}
                            {match.customDomain && (
                              <span className={styles.migrationDomain}>
                                {dealer.subscriptionTier.toLowerCase() === 'starter'
                                  ? ` (old domain: ${match.customDomain})`
                                  : ` - ${match.customDomain}`}
                              </span>
                            )}
                          </li>
                        ))}
                      </ul>
                      {dealer.subscriptionTier.toLowerCase() !== 'starter' && (
                        <p className={styles.migrationNote}>
                          This dealer has custom domain access. They can configure this domain in
                          their settings.
                        </p>
                      )}
                    </div>
                  )}
                  {/* Grandfathered Custom Domain Access - only for Starter tier, only in edit mode */}
                  {dealer.subscriptionTier.toLowerCase() === 'starter' && isEditing && (
                    <>
                      <div className={styles.infoItem}>
                        <dt>Grandfathered Access</dt>
                        <dd className={styles.grandfatheredRow}>
                          <span
                            className={
                              dealer.hasGrandfatheredCustomDomain ? styles.yesValue : styles.noValue
                            }
                          >
                            {dealer.hasGrandfatheredCustomDomain ? 'Yes' : 'No'}
                          </span>
                          <button
                            onClick={() =>
                              handleToggleGrandfathered(!dealer.hasGrandfatheredCustomDomain)
                            }
                            disabled={isTogglingGrandfathered}
                            className={styles.toggleButton}
                          >
                            {isTogglingGrandfathered
                              ? 'Updating...'
                              : dealer.hasGrandfatheredCustomDomain
                                ? 'Revoke'
                                : 'Grant'}
                          </button>
                        </dd>
                      </div>
                      {/* Reason input - show when about to toggle ON */}
                      {!dealer.hasGrandfatheredCustomDomain && (
                        <div className={styles.infoItem}>
                          <dt></dt>
                          <dd>
                            <input
                              type="text"
                              value={grandfatheredReason}
                              onChange={(e) => setGrandfatheredReason(e.target.value)}
                              placeholder="Reason for granting (optional)"
                              className={styles.reasonInput}
                            />
                          </dd>
                        </div>
                      )}
                    </>
                  )}
                  {/* SSL / Reachability row */}
                  <div className={styles.infoItem}>
                    <dt>SSL / Reachability</dt>
                    <dd>
                      {dealer.gscPreflightError ? (
                        <span className={styles.preflightError}>
                          <AlertTriangle size={14} className={styles.preflightIcon} />
                          {dealer.gscPreflightError}
                          {dealer.gscPreflightHealthyAt && (
                            <span className={styles.preflightMeta}>
                              {' '}
                              (last healthy {formatDate(dealer.gscPreflightHealthyAt)})
                            </span>
                          )}
                        </span>
                      ) : dealer.gscPreflightHealthyAt ? (
                        <span className={styles.preflightHealthy}>
                          <CheckCircle size={14} className={styles.preflightIcon} />
                          Healthy (checked {formatRelativeHours(dealer.gscPreflightHealthyAt)})
                        </span>
                      ) : (
                        <span className={styles.notSet}>Not checked</span>
                      )}
                    </dd>
                  </div>
                  <div className={styles.infoItem}>
                    <dt>Last Published</dt>
                    <dd>
                      {dealer.lastPublishedAt ? (
                        formatDate(dealer.lastPublishedAt)
                      ) : (
                        <span className={styles.notSet}>Never</span>
                      )}
                    </dd>
                  </div>
                  <div className={styles.infoItem}>
                    <dt>Member Since</dt>
                    <dd>{formatDate(dealer.createdAt)}</dd>
                  </div>
                </dl>
              </section>
            </div>

            {/* Indexing & SEO Section */}
            <section className={styles.gscSection}>
              <h3 className={styles.sectionTitle}>Indexing &amp; SEO</h3>
              <div className={styles.gscGrid}>
                {/* Left column: status info */}
                <dl className={styles.infoList}>
                  <div className={styles.infoItem}>
                    <dt>Canonical URL</dt>
                    <dd>
                      <a
                        href={getCanonicalUrl(dealer, '')}
                        target="_blank"
                        rel="noopener noreferrer"
                        className={styles.link}
                      >
                        {getCanonicalUrl(dealer, '')}
                      </a>
                    </dd>
                  </div>
                  <div className={styles.infoItem}>
                    <dt>Index Status</dt>
                    <dd>
                      {dealer.gscLastIndexStatus ? (
                        <span
                          className={
                            dealer.gscLastIndexStatus === 'indexed'
                              ? styles.statusIndexed
                              : dealer.gscLastIndexStatus === 'error'
                                ? styles.statusError
                                : styles.statusNotIndexed
                          }
                        >
                          {dealer.gscLastIndexStatus}
                        </span>
                      ) : (
                        <span className={styles.notSet}>Unknown</span>
                      )}
                      {dealer.gscLastInspectedAt && (
                        <span className={styles.gscMeta}>
                          {' '}
                          (inspected {formatRelativeHours(dealer.gscLastInspectedAt)})
                        </span>
                      )}
                    </dd>
                  </div>
                  <div className={styles.infoItem}>
                    <dt>Sitemap Submitted</dt>
                    <dd>
                      {dealer.gscLastSubmittedAt ? (
                        <span className={styles.gscMeta}>
                          {formatDate(dealer.gscLastSubmittedAt)}
                        </span>
                      ) : (
                        <span className={styles.notSet}>Never</span>
                      )}
                    </dd>
                  </div>
                  {dealer.customDomain && dealer.gscPropertyRegisteredAt && (
                    <div className={styles.infoItem}>
                      <dt>Custom Domain Property</dt>
                      <dd className={styles.gscMeta}>
                        Registered {formatDate(dealer.gscPropertyRegisteredAt)}
                      </dd>
                    </div>
                  )}
                </dl>

                {/* Right column: actions */}
                <div className={styles.gscActions}>
                  <button
                    onClick={handleGscAction}
                    disabled={isGscActioning}
                    className={styles.gscActionButton}
                    title="Resubmit sitemap, request URL inspection, and reschedule indexing jobs"
                  >
                    <RefreshCw
                      size={14}
                      className={isGscActioning ? styles.spinningIcon : undefined}
                    />
                    {isGscActioning ? 'Queuing…' : 'Reindex Now'}
                  </button>
                  {/* TODO: re-enable Deep Audit button when issue #865 (per-dealer
                      deep diagnostic endpoint) lands. The button was previously
                      disabled with "Coming soon"; commented out to avoid dead UI.
                      See: https://github.com/aimclear/amsoil-dlp/issues/865
                  <button
                    disabled
                    className={`${styles.gscActionButton} ${styles.gscActionDisabled}`}
                    title="Coming soon"
                  >
                    Deep Audit
                  </button>
                  */}
                </div>
              </div>

              {/* GSC action error — surfaces HTTP errors to the admin */}
              {gscActionError && <div className={styles.editGeneralError}>{gscActionError}</div>}

              {/* Recent GSC Jobs */}
              {gscJobs.length > 0 && (
                <div className={styles.gscJobsTable}>
                  <table className={styles.jobTable}>
                    <thead>
                      <tr>
                        <th>Type</th>
                        <th>Status</th>
                        <th>Attempts</th>
                        <th>Error</th>
                        <th>Completed</th>
                      </tr>
                    </thead>
                    <tbody>
                      {gscJobs.map((job) => (
                        <tr key={job.id}>
                          <td>
                            <JobTypePill type={job.type} />
                          </td>
                          <td>
                            <span
                              className={
                                job.status === 'completed'
                                  ? styles.jobStatusCompleted
                                  : job.status === 'failed'
                                    ? styles.jobStatusFailed
                                    : job.status === 'running'
                                      ? styles.jobStatusRunning
                                      : styles.jobStatusPending
                              }
                            >
                              {job.status}
                            </span>
                          </td>
                          <td className={styles.jobMeta}>{job.attempts}</td>
                          <td className={styles.jobError}>
                            {job.lastError
                              ? job.lastError.length > 60
                                ? `${job.lastError.slice(0, 60)}…`
                                : job.lastError
                              : '—'}
                          </td>
                          <td className={styles.jobMeta}>
                            {job.completedAt ? formatDate(job.completedAt) : '—'}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}
            </section>

            {/* Site Performance Section */}
            {performance?.traffic && (
              <section className={styles.perfSection}>
                <h3 className={styles.sectionTitle}>Site Performance — Last 30 Days</h3>
                <dl className={styles.perfGrid}>
                  <div className={styles.perfItem}>
                    <dt>Traffic</dt>
                    <dd>
                      <TrendValue
                        value={performance.traffic.current}
                        changePercent={performance.traffic.changePercent}
                      />
                    </dd>
                  </div>
                  <div className={styles.perfItem}>
                    <dt>Inquiries</dt>
                    <dd>
                      <TrendValue
                        value={performance.inquiries.current}
                        changePercent={performance.inquiries.changePercent}
                      />
                    </dd>
                  </div>
                  <div className={styles.perfItem}>
                    <dt>Link Clicks</dt>
                    <dd>
                      <span className={styles.perfValue}>
                        {performance.clicks.current.toLocaleString()}
                      </span>
                    </dd>
                  </div>
                </dl>
              </section>
            )}

            {/* Activity & Notes Section */}
            <section className={styles.activitySection}>
              <h3 className={styles.sectionTitle}>Activity & Notes</h3>

              {/* Add Note Form */}
              <div className={styles.addNoteForm}>
                <div className={styles.noteFormRow}>
                  <select
                    value={noteType}
                    onChange={(e) => setNoteType(e.target.value)}
                    className={styles.select}
                  >
                    <option value="manual">Note</option>
                    <option value="support_call">Support Call</option>
                    <option value="email_sent">Email Sent</option>
                    <option value="internal">Internal</option>
                  </select>
                  <button
                    onClick={handleAddNote}
                    disabled={isAddingNote || !newNote.trim()}
                    className={styles.addNoteButton}
                  >
                    {isAddingNote ? 'Adding...' : 'Add Note'}
                  </button>
                </div>
                <textarea
                  value={newNote}
                  onChange={(e) => setNewNote(e.target.value)}
                  placeholder="Add a note about this dealer..."
                  className={styles.noteInput}
                  rows={3}
                />
              </div>

              {/* Activity Timeline */}
              <div className={styles.timeline}>
                {activity.filter(
                  (item) => !(item.type === 'action' && HIDDEN_ACTIONS.includes(item.action || ''))
                ).length === 0 ? (
                  <div className={styles.emptyActivity}>No activity yet</div>
                ) : (
                  activity
                    .filter(
                      (item) =>
                        !(item.type === 'action' && HIDDEN_ACTIONS.includes(item.action || ''))
                    )
                    .map((item) => {
                      // Determine CSS classes for timeline item
                      const getTimelineItemClass = () => {
                        const classes = [styles.timelineItem];
                        if (item.type === 'note') {
                          classes.push(styles.noteItem);
                        } else {
                          classes.push(styles.actionItem);
                          // Highlight dangerous status changes
                          if (item.action === 'status_change' || item.action === 'change_status') {
                            const newStatus = (item.details as Record<string, unknown>)?.newStatus;
                            if (newStatus === 'cancelled') {
                              classes.push(styles.cancelledAction);
                            } else if (newStatus === 'suspended') {
                              classes.push(styles.suspendedAction);
                            }
                          }
                        }
                        return classes.join(' ');
                      };

                      return (
                        <div key={item.id} className={getTimelineItemClass()}>
                          <div className={styles.timelineIcon}>
                            {item.type === 'note' ? (
                              <NoteTypeIcon noteType={item.noteType || 'manual'} />
                            ) : (
                              <ActionIcon action={item.action || ''} />
                            )}
                          </div>
                          <div className={styles.timelineContent}>
                            <div className={styles.timelineHeader}>
                              <span className={styles.timelineTime}>
                                {formatDateTime(item.timestamp)}
                              </span>
                              {item.type === 'note' && item.noteType && (
                                <span className={styles.noteTypeTag}>
                                  {NOTE_TYPE_LABELS[item.noteType] || item.noteType}
                                </span>
                              )}
                              {item.type === 'action' && (
                                <span className={styles.autoTag}>auto</span>
                              )}
                            </div>
                            <div className={styles.timelineBody}>
                              {item.type === 'note' ? (
                                <p>{item.content}</p>
                              ) : (
                                <>
                                  <p>{getActionDescription(item)}</p>
                                  {item.reason && (
                                    <p className={styles.reasonText}>
                                      Reason: {getReasonLabel(item.reason)}
                                    </p>
                                  )}
                                  {(item.details as Record<string, unknown>)?.notes && (
                                    <p className={styles.notesText}>
                                      {String((item.details as Record<string, unknown>).notes)}
                                    </p>
                                  )}
                                </>
                              )}
                            </div>
                            <div className={styles.timelineFooter}>
                              by {item.adminName || item.adminEmail}
                            </div>
                          </div>
                        </div>
                      );
                    })
                )}
              </div>
            </section>
          </>
        ) : (
          <div className={styles.error}>Failed to load dealer details</div>
        )}
      </div>
    </Modal>
  );
}
