import { useState } from 'react';
import { useParams, Link, useNavigate } from 'react-router-dom';
import { useContact, useDeals, useDeleteContact } from '../hooks';
import { contactsApi } from '../api';
import { ContactFormModal } from './ContactFormModal';
import { ActivityFormModal } from '../activities/ActivityFormModal';
import { Modal } from '../../components/Modal';
import { CustomFieldsDisplay } from '../CustomFieldsDisplay';
import { EmailsTab } from './EmailsTab';
import { CalendarTab } from './CalendarTab';
import type { Contact, Activity, ActivityType } from '../types';
import { CONTACT_SOURCE_LABELS, ENTITY_STATUS_LABELS } from '../types';
import styles from './ContactDetailPage.module.css';

type M365Tab = 'emails' | 'calendar';

const CONTACT_TYPE_LABELS: Record<string, string> = {
  PERSON: 'Person',
  ORGANIZATION: 'Organisation',
};

const ACTIVITY_TYPE_LABELS: Record<ActivityType, string> = {
  NOTE: 'Notiz',
  CALL: 'Anruf',
  EMAIL: 'E-Mail',
  MEETING: 'Meeting',
  TASK: 'Aufgabe',
  FOLLOWUP: 'Follow-Up',
};

function activityIcon(type: ActivityType): React.ReactNode {
  const s = {
    width: 14,
    height: 14,
    stroke: 'currentColor',
    fill: 'none',
    strokeWidth: 1.5,
    strokeLinecap: 'round' as const,
    strokeLinejoin: 'round' as const,
  };
  switch (type) {
    case 'NOTE':
      return (
        <svg viewBox="0 0 16 16" {...s}>
          <path d="M12 1l3 3-9 9H3v-3z" />
        </svg>
      );
    case 'CALL':
      return (
        <svg viewBox="0 0 16 16" {...s}>
          <path d="M1 3a2 2 0 012-2h1.5l2 3.5-1.5 1a7.5 7.5 0 004 4l1-1.5L13.5 10H15a2 2 0 01-2 2h-1A10 10 0 011 4V3z" />
        </svg>
      );
    case 'EMAIL':
      return (
        <svg viewBox="0 0 16 16" {...s}>
          <rect x="1" y="3" width="14" height="10" rx="1" />
          <path d="M1 4l7 5 7-5" />
        </svg>
      );
    case 'MEETING':
      return (
        <svg viewBox="0 0 16 16" {...s}>
          <rect x="2" y="3" width="12" height="11" rx="1" />
          <path d="M5 1v3M11 1v3M2 7h12" />
        </svg>
      );
    case 'TASK':
      return (
        <svg viewBox="0 0 16 16" {...s}>
          <path d="M4 8l3 3 5-6" />
          <rect x="1" y="1" width="14" height="14" rx="2" />
        </svg>
      );
    default:
      return null;
  }
}

function contactDisplayName(c: Contact): string {
  if (c.type === 'ORGANIZATION') return c.companyName ?? '—';
  return [c.firstName, c.lastName].filter(Boolean).join(' ') || '—';
}

function formatDate(iso: string): string {
  return new Date(iso).toLocaleDateString('de-DE', {
    day: '2-digit',
    month: '2-digit',
    year: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  });
}

const currencyFormatter = new Intl.NumberFormat('de-DE', {
  style: 'currency',
  currency: 'EUR',
});

// LinkedIn icon SVG
function LinkedInIcon() {
  return (
    <svg
      width="13"
      height="13"
      viewBox="0 0 16 16"
      fill="currentColor"
      style={{ display: 'inline', verticalAlign: 'middle', marginRight: 4 }}
    >
      <path d="M0 1.146C0 .513.526 0 1.175 0h13.65C15.474 0 16 .513 16 1.146v13.708c0 .633-.526 1.146-1.175 1.146H1.175C.526 16 0 15.487 0 14.854V1.146zm4.943 12.248V6.169H2.542v7.225h2.401zm-1.2-8.212c.837 0 1.358-.554 1.358-1.248-.015-.709-.52-1.248-1.342-1.248-.822 0-1.359.54-1.359 1.248 0 .694.521 1.248 1.327 1.248h.016zm4.908 8.212V9.359c0-.216.016-.432.08-.586.175-.431.573-.878 1.242-.878.877 0 1.228.67 1.228 1.652v3.847h2.4V9.25c0-2.22-1.184-3.252-2.764-3.252-1.274 0-1.845.7-2.165 1.193v.025h-.016a5.54 5.54 0 0 1 .016-.025V6.169h-2.4c.03.678 0 7.225 0 7.225h2.4z" />
    </svg>
  );
}

export function ContactDetailPage() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const { data, isLoading, error } = useContact(id!);
  const { data: dealsData } = useDeals({ contactId: id, pageSize: 50 });
  const deleteMutation = useDeleteContact();

  const [isEditOpen, setEditOpen] = useState(false);
  const [isActivityOpen, setActivityOpen] = useState(false);
  const [isDeleteOpen, setDeleteOpen] = useState(false);
  const [m365Tab, setM365Tab] = useState<M365Tab>('emails');
  const [outlookExpanded, setOutlookExpanded] = useState(false);
  const [pushStatus, setPushStatus] = useState<'idle' | 'loading' | 'success' | 'error'>('idle');

  // Aktivitäten-Filter
  const [actTypeFilter, setActTypeFilter] = useState<ActivityType | 'ALL'>('ALL');
  const [actDateFrom, setActDateFrom] = useState('');
  const [actDateTo, setActDateTo] = useState('');

  if (isLoading) return <p>Laden…</p>;
  if (error || !data)
    return (
      <p style={{ color: 'var(--color-error)' }}>
        Kontakt konnte nicht geladen werden
      </p>
    );

  const contact = data.data;
  const allActivities: Activity[] = contact.activities ?? [];
  const deals = dealsData?.data ?? [];

  // Gefilterte Aktivitäten
  const activities = allActivities.filter((act) => {
    if (actTypeFilter !== 'ALL' && act.type !== actTypeFilter) return false;
    if (actDateFrom) {
      const actDate = new Date(act.createdAt).toISOString().slice(0, 10);
      if (actDate < actDateFrom) return false;
    }
    if (actDateTo) {
      const actDate = new Date(act.createdAt).toISOString().slice(0, 10);
      if (actDate > actDateTo) return false;
    }
    return true;
  });

  const isFilterActive = actTypeFilter !== 'ALL' || actDateFrom !== '' || actDateTo !== '';

  function resetFilters() {
    setActTypeFilter('ALL');
    setActDateFrom('');
    setActDateTo('');
  }

  async function handlePushToOutlook() {
    setPushStatus('loading');
    try {
      await contactsApi.pushToOutlook(contact.id);
      setPushStatus('success');
      setTimeout(() => setPushStatus('idle'), 3000);
    } catch {
      setPushStatus('error');
      setTimeout(() => setPushStatus('idle'), 3000);
    }
  }

  return (
    <div style={{ maxWidth: '960px', margin: '0 auto' }}>
      {/* Back link */}
      <Link to="/crm/contacts" className={styles.backLink}>
        <svg
          width="14"
          height="14"
          viewBox="0 0 14 14"
          fill="none"
          stroke="currentColor"
          strokeWidth="1.5"
        >
          <path d="M9 2L4 7l5 5" />
        </svg>
        Zurück zu Kontakte
      </Link>

      {/* ── Header ── */}
      <div className={styles.header}>
        <div className={styles.headerLeft}>
          <div className={styles.nameRow}>
            <h1 className={styles.name}>
              {contactDisplayName(contact)}
              {contact.company && (
                <span className={styles.nameCompany}>
                  {' '}({contact.company.name})
                </span>
              )}
            </h1>
            <span
              className={
                contact.isActive ? styles.badgeActive : styles.badgeInactive
              }
            >
              {contact.isActive ? 'Aktiv' : 'Inaktiv'}
            </span>
          </div>
          {contact.position && (
            <p className={styles.subtitle}>{contact.position}</p>
          )}
        </div>
        <div style={{ display: 'flex', gap: '0.5rem', flexShrink: 0 }}>
          <button
            onClick={() => setEditOpen(true)}
            style={{
              padding: '0.375rem 0.75rem',
              fontSize: '0.8125rem',
              background: 'transparent',
              border: '1px solid var(--color-border)',
              borderRadius: 'var(--radius-sm)',
              cursor: 'pointer',
              color: 'var(--color-text-secondary)',
            }}
          >
            Bearbeiten
          </button>
          <button
            onClick={() => setDeleteOpen(true)}
            style={{
              padding: '0.375rem 0.75rem',
              fontSize: '0.8125rem',
              background: 'transparent',
              border: '1px solid #fecaca',
              borderRadius: 'var(--radius-sm)',
              cursor: 'pointer',
              color: 'var(--color-error)',
            }}
          >
            Löschen
          </button>
        </div>
      </div>

      {/* ── Kontaktdaten ── */}
      <div>
        <div>
          {/* Contact data card */}
          <div className={styles.card}>
            <h2 className={styles.cardTitle}>Kontaktdaten</h2>

            {/* Two sub-columns — always show all Allgemein fields */}
            <div className={styles.infoColumns}>
              {/* Left: Kommunikation */}
              <div className={styles.infoGrid}>
                <span className={styles.infoLabel}>E-Mail</span>
                <span className={styles.infoValue}>
                  {contact.email ? (
                    <a href={`mailto:${contact.email}`} style={{ color: 'var(--color-primary)' }}>
                      {contact.email}
                    </a>
                  ) : <span className={styles.empty}>—</span>}
                </span>

                <span className={styles.infoLabel}>Telefon</span>
                <span className={styles.infoValue}>
                  {contact.phone ?? <span className={styles.empty}>—</span>}
                </span>

                <span className={styles.infoLabel}>Mobil</span>
                <span className={styles.infoValue}>
                  {contact.mobile ? (
                    <a href={`tel:${contact.mobile}`} style={{ color: 'var(--color-primary)' }}>
                      {contact.mobile}
                    </a>
                  ) : <span className={styles.empty}>—</span>}
                </span>

                <span className={styles.infoLabel}>LinkedIn</span>
                <span className={styles.infoValue}>
                  {contact.linkedinUrl ? (
                    <a
                      href={contact.linkedinUrl}
                      target="_blank"
                      rel="noopener noreferrer"
                      style={{ color: 'var(--color-primary)' }}
                    >
                      <LinkedInIcon />
                      {contact.linkedinUrl.replace(
                        /^https?:\/\/(www\.)?linkedin\.com\/in\//,
                        '',
                      )}
                    </a>
                  ) : <span className={styles.empty}>—</span>}
                </span>

                {contact.website && (
                  <>
                    <span className={styles.infoLabel}>Website</span>
                    <span className={styles.infoValue}>
                      <a
                        href={contact.website}
                        target="_blank"
                        rel="noopener noreferrer"
                        style={{ color: 'var(--color-primary)' }}
                      >
                        {contact.website}
                      </a>
                    </span>
                  </>
                )}
              </div>

              {/* Right: Kontext */}
              <div className={styles.infoGrid}>
                <span className={styles.infoLabel}>Typ</span>
                <span className={styles.infoValue}>
                  {CONTACT_TYPE_LABELS[contact.type] ?? contact.type}
                </span>

                <span className={styles.infoLabel}>Unternehmen</span>
                <span className={styles.infoValue}>
                  {contact.company ? (
                    <>
                      <Link
                        to={`/crm/companies/${contact.company.id}`}
                        style={{ color: 'var(--color-primary)' }}
                      >
                        {contact.company.name}
                      </Link>
                      {contact.company.industry && (
                        <span style={{ color: 'var(--color-text-muted)', marginLeft: '0.5rem', fontSize: '0.8125rem' }}>
                          ({contact.company.industry})
                        </span>
                      )}
                    </>
                  ) : contact.companyName ? (
                    <span>{contact.companyName}</span>
                  ) : <span className={styles.empty}>—</span>}
                </span>

                <span className={styles.infoLabel}>Position</span>
                <span className={styles.infoValue}>
                  {contact.position ?? <span className={styles.empty}>—</span>}
                </span>

                <span className={styles.infoLabel}>Abteilung</span>
                <span className={styles.infoValue}>
                  {contact.department ?? <span className={styles.empty}>—</span>}
                </span>

                <span className={styles.infoLabel}>Status</span>
                <span
                  className={styles.infoValue}
                  style={{
                    color: contact.status === 'BLOCKED'
                      ? '#991b1b'
                      : contact.status === 'INACTIVE'
                      ? 'var(--color-text-muted)'
                      : 'var(--color-text)',
                  }}
                >
                  {ENTITY_STATUS_LABELS[contact.status] ?? contact.status}
                </span>

                {contact.birthday && (
                  <>
                    <span className={styles.infoLabel}>Geburtsdatum</span>
                    <span className={styles.infoValue}>
                      {new Date(contact.birthday).toLocaleDateString('de-DE')}
                    </span>
                  </>
                )}
                {contact.source && (
                  <>
                    <span className={styles.infoLabel}>Quelle</span>
                    <span className={styles.infoValue}>
                      {CONTACT_SOURCE_LABELS[contact.source] ?? contact.source}
                    </span>
                  </>
                )}
              </div>
            </div>

            {/* Address — full-width below sub-columns */}
            {(contact.street || contact.zip || contact.city || contact.state) && (
              <div className={styles.addressRow}>
                <div className={styles.infoGrid}>
                  <span className={styles.infoLabel}>Adresse</span>
                  <span className={styles.infoValue}>
                    {contact.street && <>{contact.street}<br /></>}
                    {contact.zip} {contact.city}
                    {contact.state && <>, {contact.state}</>}
                    {contact.country && contact.country !== 'DE' && <><br />{contact.country}</>}
                  </span>
                </div>
              </div>
            )}
          </div>

          {/* Notizen & Tags card */}
          {((contact.tags && contact.tags.length > 0) ||
            contact.notes ||
            (contact.customFields && contact.customFields.length > 0)) && (
            <div className={styles.card} style={{ marginTop: '1.5rem' }}>
              <h2 className={styles.cardTitle}>Notizen &amp; Tags</h2>

              {contact.tags && contact.tags.length > 0 && (
                <div
                  style={{
                    marginBottom: contact.notes ? '1rem' : 0,
                  }}
                >
                  <div className={styles.tags}>
                    {contact.tags.map((tag) => (
                      <span key={tag} className={styles.tag}>
                        {tag}
                      </span>
                    ))}
                  </div>
                </div>
              )}

              {contact.notes && (
                <p
                  className={styles.notesText}
                  style={{ marginTop: contact.tags?.length ? '0.75rem' : 0 }}
                >
                  {contact.notes}
                </p>
              )}

              {contact.customFields && contact.customFields.length > 0 && (
                <div style={{ marginTop: '1rem' }}>
                  <CustomFieldsDisplay fields={contact.customFields} />
                </div>
              )}
            </div>
          )}

          {/* Linked deals */}
          {deals.length > 0 && (
            <div className={styles.card} style={{ marginTop: '1.5rem' }}>
              <h2 className={styles.cardTitle}>
                Verknüpfte Vorgänge ({deals.length})
              </h2>
              <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                <thead>
                  <tr style={{ borderBottom: '1px solid var(--color-border)' }}>
                    <th
                      style={{
                        padding: '0.5rem 0',
                        textAlign: 'left',
                        fontSize: '0.75rem',
                        color: 'var(--color-text-muted)',
                        textTransform: 'uppercase',
                      }}
                    >
                      Titel
                    </th>
                    <th
                      style={{
                        padding: '0.5rem 0',
                        textAlign: 'left',
                        fontSize: '0.75rem',
                        color: 'var(--color-text-muted)',
                        textTransform: 'uppercase',
                      }}
                    >
                      Stage
                    </th>
                    <th
                      style={{
                        padding: '0.5rem 0',
                        textAlign: 'right',
                        fontSize: '0.75rem',
                        color: 'var(--color-text-muted)',
                        textTransform: 'uppercase',
                      }}
                    >
                      Wert
                    </th>
                  </tr>
                </thead>
                <tbody>
                  {deals.map((deal) => (
                    <tr
                      key={deal.id}
                      style={{
                        borderBottom: '1px solid var(--color-border)',
                        cursor: 'pointer',
                      }}
                      onClick={() => navigate(`/crm/deals/${deal.id}`)}
                    >
                      <td
                        style={{ padding: '0.5rem 0', fontSize: '0.875rem' }}
                      >
                        {deal.title}
                      </td>
                      <td style={{ padding: '0.5rem 0' }}>
                        {deal.stage && (
                          <span
                            style={{
                              display: 'inline-flex',
                              alignItems: 'center',
                              gap: '0.375rem',
                              fontSize: '0.8125rem',
                            }}
                          >
                            <span
                              style={{
                                width: 8,
                                height: 8,
                                borderRadius: '50%',
                                background: deal.stage.color,
                                display: 'inline-block',
                              }}
                            />
                            {deal.stage.name}
                          </span>
                        )}
                      </td>
                      <td
                        style={{
                          padding: '0.5rem 0',
                          textAlign: 'right',
                          fontSize: '0.875rem',
                          fontWeight: 500,
                        }}
                      >
                        {deal.value
                          ? currencyFormatter.format(parseFloat(deal.value))
                          : '—'}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}

        </div>
      </div>

      {/* ── Aktivitäten (full width below) ── */}
      <div className={styles.card} style={{ marginTop: '1.5rem' }}>
        {/* Karten-Header */}
        <div
          style={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
            marginBottom: '1rem',
          }}
        >
          <h2 className={styles.cardTitle} style={{ margin: 0 }}>
            Aktivitäten
            {allActivities.length > 0 && (
              <span
                style={{
                  marginLeft: '0.5rem',
                  fontSize: '0.8125rem',
                  fontWeight: 400,
                  color: 'var(--color-text-muted)',
                }}
              >
                ({allActivities.length})
              </span>
            )}
          </h2>
          <button
            onClick={() => setActivityOpen(true)}
            style={{
              padding: '0.25rem 0.625rem',
              fontSize: '0.8125rem',
              background: 'var(--color-primary)',
              color: 'white',
              border: 'none',
              borderRadius: 'var(--radius-sm)',
              cursor: 'pointer',
              fontWeight: 500,
            }}
          >
            + Neu
          </button>
        </div>

        {/* Filter-Leiste */}
        {allActivities.length > 0 && (
          <div className={styles.activityFilterBar}>
            <span className={styles.activityFilterLabel}>Typ:</span>
            <select
              className={styles.activityFilterSelect}
              value={actTypeFilter}
              onChange={(e) =>
                setActTypeFilter(e.target.value as ActivityType | 'ALL')
              }
            >
              <option value="ALL">Alle</option>
              {(Object.keys(ACTIVITY_TYPE_LABELS) as ActivityType[]).map(
                (t) => (
                  <option key={t} value={t}>
                    {ACTIVITY_TYPE_LABELS[t]}
                  </option>
                ),
              )}
            </select>

            <span className={styles.activityFilterLabel}>Von:</span>
            <input
              type="date"
              className={styles.activityFilterDate}
              value={actDateFrom}
              onChange={(e) => setActDateFrom(e.target.value)}
            />

            <span className={styles.activityFilterLabel}>Bis:</span>
            <input
              type="date"
              className={styles.activityFilterDate}
              value={actDateTo}
              onChange={(e) => setActDateTo(e.target.value)}
            />

            {isFilterActive && (
              <button
                type="button"
                className={styles.activityFilterReset}
                onClick={resetFilters}
              >
                × Filter zurücksetzen
              </button>
            )}

            <span className={styles.activityFilterCount}>
              {activities.length} von {allActivities.length}
            </span>
          </div>
        )}

        {/* Zeitstrahl */}
        {activities.length === 0 ? (
          <p className={styles.timelineEmpty}>
            {isFilterActive
              ? 'Keine Aktivitäten für den gewählten Filter'
              : 'Keine Aktivitäten vorhanden'}
          </p>
        ) : (
          <div className={styles.timeline}>
            {activities.map((act) => {
              const iconClass = {
                NOTE: styles.timelineIconNote,
                CALL: styles.timelineIconCall,
                EMAIL: styles.timelineIconEmail,
                MEETING: styles.timelineIconMeeting,
                TASK: styles.timelineIconTask,
                FOLLOWUP: styles.timelineIconFollowup,
              }[act.type] ?? '';

              const badgeClass = {
                NOTE: styles.timelineBadgeNote,
                CALL: styles.timelineBadgeCall,
                EMAIL: styles.timelineBadgeEmail,
                MEETING: styles.timelineBadgeMeeting,
                TASK: styles.timelineBadgeTask,
                FOLLOWUP: styles.timelineBadgeFollowup,
              }[act.type] ?? '';

              return (
                <div key={act.id} className={styles.timelineItem}>
                  <div className={`${styles.timelineIcon} ${iconClass}`}>
                    {activityIcon(act.type)}
                  </div>
                  <div className={styles.timelineContent}>
                    <div className={styles.timelineSubject}>{act.subject}</div>
                    <div className={styles.timelineMeta}>
                      <span
                        className={`${styles.timelineTypeBadge} ${badgeClass}`}
                      >
                        {ACTIVITY_TYPE_LABELS[act.type]}
                      </span>
                      <span className={styles.timelineDate}>
                        {formatDate(act.createdAt)}
                      </span>
                    </div>
                    {act.description && (
                      <div className={styles.timelineDesc}>
                        {act.description}
                      </div>
                    )}
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </div>

      {/* ── Outlook Daten ── */}
      {contact.email && (
        <div className={styles.card} style={{ marginTop: '1.5rem' }}>
          {/* Karten-Header: Titel + Outlook-Push-Button + Toggle */}
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'space-between',
              gap: '0.75rem',
            }}
          >
            <button
              type="button"
              onClick={() => setOutlookExpanded((v) => !v)}
              style={{
                display: 'flex',
                alignItems: 'center',
                gap: '0.5rem',
                background: 'transparent',
                border: 'none',
                cursor: 'pointer',
                padding: 0,
                color: 'var(--color-text)',
              }}
            >
              <h2 className={styles.cardTitle} style={{ margin: 0 }}>
                Outlook Daten
              </h2>
              <svg
                width="16"
                height="16"
                viewBox="0 0 16 16"
                fill="none"
                stroke="currentColor"
                strokeWidth="1.75"
                strokeLinecap="round"
                strokeLinejoin="round"
                style={{
                  color: 'var(--color-text-muted)',
                  transform: outlookExpanded ? 'rotate(180deg)' : 'rotate(0deg)',
                  transition: 'transform 0.2s',
                  flexShrink: 0,
                }}
              >
                <path d="M3 6l5 5 5-5" />
              </svg>
            </button>

            <div style={{ display: 'flex', gap: '0.5rem', alignItems: 'center', flexShrink: 0 }}>
              {pushStatus === 'success' && (
                <span style={{ fontSize: '0.8125rem', color: '#16a34a' }}>
                  ✓ In Outlook gespeichert
                </span>
              )}
              {pushStatus === 'error' && (
                <span style={{ fontSize: '0.8125rem', color: 'var(--color-error)' }}>
                  Fehler beim Speichern
                </span>
              )}
              <button
                type="button"
                onClick={handlePushToOutlook}
                disabled={pushStatus === 'loading'}
                title="Kontakt in Outlook-Kontakte kopieren / aktualisieren"
                style={{
                  padding: '0.25rem 0.625rem',
                  fontSize: '0.8125rem',
                  background: 'transparent',
                  border: '1px solid var(--color-border)',
                  borderRadius: 'var(--radius-sm)',
                  cursor: pushStatus === 'loading' ? 'wait' : 'pointer',
                  color: 'var(--color-text-secondary)',
                  display: 'flex',
                  alignItems: 'center',
                  gap: '0.375rem',
                  opacity: pushStatus === 'loading' ? 0.6 : 1,
                  whiteSpace: 'nowrap',
                }}
              >
                <svg width="13" height="13" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5">
                  <path d="M2 12l4-4-4-4M8 12h6" />
                </svg>
                {pushStatus === 'loading' ? 'Speichern…' : 'In Outlook speichern'}
              </button>
            </div>
          </div>

          {/* Tabs + Inhalt (nur wenn ausgeklappt) */}
          {outlookExpanded && (
            <div style={{ marginTop: '1rem' }}>
              <div style={{ display: 'flex', gap: '0.5rem', borderBottom: '1px solid var(--color-border)', paddingBottom: '0', marginBottom: '0.75rem' }}>
                {(['emails', 'calendar'] as M365Tab[]).map((tab) => {
                  const labels: Record<M365Tab, string> = { emails: 'E-Mails', calendar: 'Kalender' };
                  return (
                    <button
                      key={tab}
                      type="button"
                      onClick={() => setM365Tab(tab)}
                      style={{
                        padding: '0.375rem 0.75rem',
                        background: 'transparent',
                        border: 'none',
                        borderBottom: m365Tab === tab ? '2px solid var(--color-primary)' : '2px solid transparent',
                        fontSize: '0.875rem',
                        fontWeight: m365Tab === tab ? 600 : 400,
                        color: m365Tab === tab ? 'var(--color-primary)' : 'var(--color-text-secondary)',
                        cursor: 'pointer',
                        marginBottom: '-1px',
                        transition: 'all 0.15s',
                      }}
                    >
                      {labels[tab]}
                    </button>
                  );
                })}
              </div>

              {m365Tab === 'emails' && <EmailsTab contactId={contact.id} />}
              {m365Tab === 'calendar' && <CalendarTab contactId={contact.id} />}
            </div>
          )}
        </div>
      )}

      {/* ── Modals ── */}
      <ContactFormModal
        isOpen={isEditOpen}
        onClose={() => setEditOpen(false)}
        contact={contact}
        onSuccess={() => setEditOpen(false)}
      />

      <ActivityFormModal
        isOpen={isActivityOpen}
        onClose={() => setActivityOpen(false)}
        contactId={contact.id}
        onSuccess={() => setActivityOpen(false)}
      />

      {/* Delete confirmation */}
      <Modal
        isOpen={isDeleteOpen}
        onClose={() => setDeleteOpen(false)}
        title="Kontakt löschen"
        maxWidth="420px"
      >
        <p
          style={{
            fontSize: '0.9375rem',
            color: 'var(--color-text)',
            marginBottom: '0.5rem',
          }}
        >
          Soll der Kontakt{' '}
          <strong>{contactDisplayName(contact)}</strong> wirklich gelöscht
          werden?
        </p>
        <p
          style={{
            fontSize: '0.8125rem',
            color: 'var(--color-error)',
            marginBottom: '1.5rem',
          }}
        >
          Alle Aktivitäten werden ebenfalls gelöscht.
        </p>
        <div
          style={{
            display: 'flex',
            justifyContent: 'flex-end',
            gap: '0.75rem',
          }}
        >
          <button
            onClick={() => setDeleteOpen(false)}
            disabled={deleteMutation.isPending}
            style={{
              padding: '0.5rem 1rem',
              background: 'transparent',
              border: '1px solid var(--color-border)',
              borderRadius: 'var(--radius-sm)',
              fontSize: '0.875rem',
              cursor: 'pointer',
              color: 'var(--color-text-secondary)',
            }}
          >
            Abbrechen
          </button>
          <button
            onClick={() =>
              deleteMutation.mutate(contact.id, {
                onSuccess: () => navigate('/crm/contacts'),
              })
            }
            disabled={deleteMutation.isPending}
            style={{
              padding: '0.5rem 1rem',
              background: 'var(--color-error)',
              color: 'white',
              border: 'none',
              borderRadius: 'var(--radius-sm)',
              fontSize: '0.875rem',
              fontWeight: 600,
              cursor: deleteMutation.isPending ? 'wait' : 'pointer',
              opacity: deleteMutation.isPending ? 0.7 : 1,
            }}
          >
            {deleteMutation.isPending ? 'Löschen…' : 'Endgültig löschen'}
          </button>
        </div>
      </Modal>
    </div>
  );
}
