import { useState, useCallback } from 'react';
import { Link, Navigate } from 'react-router-dom';
import { useAuth } from '../../auth/AuthContext';
import {
  useCrmSettings,
  type CrmModuleKey,
} from './CrmSettingsContext';
import {
  useIndustries,
  useCreateIndustry,
  useUpdateIndustry,
  useDeleteIndustry,
  useAccountTypes,
  useCreateAccountType,
  useUpdateAccountType,
  useDeleteAccountType,
  useRelationshipTypes,
  useCreateRelationshipType,
  useUpdateRelationshipType,
  useDeleteRelationshipType,
  useDealTypes,
  useCreateDealType,
  useUpdateDealType,
  useDeleteDealType,
  useCustomFieldDefs,
  useCreateCustomFieldDef,
  useUpdateCustomFieldDef,
  useDeleteCustomFieldDef,
  useEnrichmentConfig,
  useSetEnrichmentConfig,
} from '../hooks';
import type {
  Industry,
  AccountType,
  RelationshipType,
  DealType,
  CustomFieldDef,
  CustomFieldEntityType,
  CustomFieldType,
  CustomFieldOption,
} from '../types';
import {
  CUSTOM_FIELD_ENTITY_TYPE_LABELS,
  CUSTOM_FIELD_TYPE_LABELS,
} from '../types';
import { LexwareSyncContent } from '../lexware/LexwareSyncPage';
import { ImportPage } from '../import/ImportPage';
import styles from './CrmSettingsPage.module.css';

// ============================================================
//  Module definitions (UI-Beschreibung je Modul)
// ============================================================

interface ModuleDef {
  key: CrmModuleKey;
  name: string;
  description: string;
  icon: React.ReactNode;
}

const iconProps = {
  width: 18,
  height: 18,
  viewBox: '0 0 16 16',
  fill: 'none',
  stroke: 'currentColor',
  strokeWidth: 1.5,
  strokeLinecap: 'round' as const,
  strokeLinejoin: 'round' as const,
};

const MODULES: ModuleDef[] = [
  {
    key: 'contacts',
    name: 'Kontakte',
    description: 'Kontaktverwaltung (Personen & Organisationen)',
    icon: (
      <svg {...iconProps}>
        <circle cx="8" cy="5" r="3" />
        <path d="M2 14c0-2.5 2.5-4.5 6-4.5s6 2 6 4.5" />
      </svg>
    ),
  },
  {
    key: 'companies',
    name: 'Unternehmen',
    description: 'Unternehmensverwaltung mit Verknüpfung zu Kontakten & Vorgängen',
    icon: (
      <svg {...iconProps}>
        <rect x="2" y="6" width="12" height="9" rx="1" />
        <path d="M5 6V3a1 1 0 011-1h4a1 1 0 011 1v3" />
        <path d="M5 9h2v2H5zM9 9h2v2H9z" />
      </svg>
    ),
  },
  {
    key: 'deals',
    name: 'Vorgänge',
    description: 'Vorgänge & Sales-Pipeline-Tracking',
    icon: (
      <svg {...iconProps}>
        <path d="M2 2h3l2 9h6l2-6H6" />
        <circle cx="7" cy="14" r="1" />
        <circle cx="13" cy="14" r="1" />
      </svg>
    ),
  },
  {
    key: 'pipelines',
    name: 'Pipelines',
    description: 'Pipeline-Konfiguration & Stufen-Management',
    icon: (
      <svg {...iconProps}>
        <rect x="1" y="2" width="14" height="3" rx="0.5" />
        <rect x="1" y="7" width="10" height="3" rx="0.5" />
        <rect x="1" y="12" width="6" height="3" rx="0.5" />
      </svg>
    ),
  },
  {
    key: 'lexware',
    name: 'Lexware Office',
    description: 'Lexware-Kontaktverknüpfung & Belegansicht auf Detail-Seiten',
    icon: (
      <svg {...iconProps}>
        <rect x="1" y="3" width="14" height="10" rx="1" />
        <path d="M4 7h8M4 10h5" />
        <circle cx="12" cy="10" r="1" />
      </svg>
    ),
  },
];

// ============================================================
//  Kleine SVG-Icons
// ============================================================

const PlusIcon = () => (
  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.5">
    <path d="M7 2v10M2 7h10" />
  </svg>
);

const PencilIcon = () => (
  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
    <path d="M10 2l2 2-8 8H2v-2l8-8z" />
  </svg>
);

const TrashIcon = () => (
  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
    <path d="M2 4h10M5 4V2.5a.5.5 0 01.5-.5h3a.5.5 0 01.5.5V4M11 4v7.5a1 1 0 01-1 1H4a1 1 0 01-1-1V4" />
  </svg>
);

const ArrowUpIcon = () => (
  <svg width="10" height="10" viewBox="0 0 10 10" fill="none" stroke="currentColor" strokeWidth="1.5">
    <path d="M5 8V2M2.5 4.5L5 2l2.5 2.5" />
  </svg>
);

const ArrowDownIcon = () => (
  <svg width="10" height="10" viewBox="0 0 10 10" fill="none" stroke="currentColor" strokeWidth="1.5">
    <path d="M5 2v6M2.5 5.5L5 8l2.5-2.5" />
  </svg>
);

// ============================================================
//  IndustriesConfig
// ============================================================

function IndustriesConfig() {
  const { data } = useIndustries();
  const createMut = useCreateIndustry();
  const updateMut = useUpdateIndustry();
  const deleteMut = useDeleteIndustry();

  const industries: Industry[] = data?.data ?? [];

  const [editId, setEditId] = useState<string | null>(null);
  const [addMode, setAddMode] = useState(false);
  const [name, setName] = useState('');
  const [color, setColor] = useState('#6B7280');

  const startAdd = useCallback(() => {
    setEditId(null);
    setName('');
    setColor('#6B7280');
    setAddMode(true);
  }, []);

  const startEdit = useCallback((item: Industry) => {
    setAddMode(false);
    setEditId(item.id);
    setName(item.name);
    setColor(item.color);
  }, []);

  const cancel = useCallback(() => {
    setEditId(null);
    setAddMode(false);
    setName('');
    setColor('#6B7280');
  }, []);

  const handleSave = useCallback(() => {
    if (!name.trim()) return;
    if (addMode) {
      createMut.mutate(
        { name: name.trim(), color },
        { onSuccess: cancel },
      );
    } else if (editId) {
      updateMut.mutate(
        { id: editId, data: { name: name.trim(), color } },
        { onSuccess: cancel },
      );
    }
  }, [addMode, editId, name, color, createMut, updateMut, cancel]);

  const handleDelete = useCallback(
    (id: string) => {
      if (window.confirm('Branche wirklich löschen?')) {
        deleteMut.mutate(id);
      }
    },
    [deleteMut],
  );

  const handleSort = useCallback(
    (item: Industry, direction: 'up' | 'down') => {
      const newOrder =
        direction === 'up'
          ? Math.max(0, item.sortOrder - 1)
          : item.sortOrder + 1;
      updateMut.mutate({ id: item.id, data: { sortOrder: newOrder } });
    },
    [updateMut],
  );

  const isSaving = createMut.isPending || updateMut.isPending;

  return (
    <div className={styles.card}>
      <div className={styles.configHeader}>
        <div>
          <h2 className={styles.cardTitle}>Branchen</h2>
          <p className={styles.cardDesc} style={{ marginBottom: 0 }}>
            Branchen-Kategorien für Unternehmen. Farben werden als Badge angezeigt.
          </p>
        </div>
        <button className={styles.addBtn} onClick={startAdd} disabled={addMode}>
          <PlusIcon /> Hinzufügen
        </button>
      </div>

      <table className={styles.configTable}>
        <thead>
          <tr>
            <th style={{ width: 40 }}>#</th>
            <th>Name</th>
            <th style={{ width: 60 }}>Farbe</th>
            <th style={{ width: 100, textAlign: 'right' }}>Aktionen</th>
          </tr>
        </thead>
        <tbody>
          {addMode && (
            <tr>
              <td>—</td>
              <td>
                <div className={styles.inlineForm}>
                  <input
                    className={styles.inlineInput}
                    style={{ flex: 1 }}
                    value={name}
                    onChange={(e) => setName(e.target.value)}
                    placeholder="Branchenname"
                    autoFocus
                    onKeyDown={(e) => {
                      if (e.key === 'Enter') handleSave();
                      if (e.key === 'Escape') cancel();
                    }}
                  />
                </div>
              </td>
              <td>
                <input
                  type="color"
                  className={styles.colorInput}
                  value={color}
                  onChange={(e) => setColor(e.target.value)}
                />
              </td>
              <td>
                <div className={styles.actionsCell}>
                  <button className={styles.saveBtn} onClick={handleSave} disabled={!name.trim() || isSaving}>
                    Speichern
                  </button>
                  <button className={styles.cancelBtn} onClick={cancel}>
                    Abbrechen
                  </button>
                </div>
              </td>
            </tr>
          )}
          {industries.length === 0 && !addMode && (
            <tr>
              <td colSpan={4} className={styles.emptyRow}>
                Noch keine Branchen definiert
              </td>
            </tr>
          )}
          {industries.map((item, idx) =>
            editId === item.id ? (
              <tr key={item.id}>
                <td>{idx + 1}</td>
                <td>
                  <div className={styles.inlineForm}>
                    <input
                      className={styles.inlineInput}
                      style={{ flex: 1 }}
                      value={name}
                      onChange={(e) => setName(e.target.value)}
                      autoFocus
                      onKeyDown={(e) => {
                        if (e.key === 'Enter') handleSave();
                        if (e.key === 'Escape') cancel();
                      }}
                    />
                  </div>
                </td>
                <td>
                  <input
                    type="color"
                    className={styles.colorInput}
                    value={color}
                    onChange={(e) => setColor(e.target.value)}
                  />
                </td>
                <td>
                  <div className={styles.actionsCell}>
                    <button className={styles.saveBtn} onClick={handleSave} disabled={!name.trim() || isSaving}>
                      Speichern
                    </button>
                    <button className={styles.cancelBtn} onClick={cancel}>
                      Abbrechen
                    </button>
                  </div>
                </td>
              </tr>
            ) : (
              <tr key={item.id}>
                <td>
                  <div className={styles.sortBtns}>
                    <button
                      className={styles.sortBtn}
                      onClick={() => handleSort(item, 'up')}
                      disabled={idx === 0}
                      title="Nach oben"
                    >
                      <ArrowUpIcon />
                    </button>
                    <button
                      className={styles.sortBtn}
                      onClick={() => handleSort(item, 'down')}
                      disabled={idx === industries.length - 1}
                      title="Nach unten"
                    >
                      <ArrowDownIcon />
                    </button>
                  </div>
                </td>
                <td>{item.name}</td>
                <td>
                  <span
                    className={styles.colorDot}
                    style={{ backgroundColor: item.color }}
                    title={item.color}
                  />
                </td>
                <td>
                  <div className={styles.actionsCell}>
                    <button
                      className={styles.iconBtn}
                      onClick={() => startEdit(item)}
                      title="Bearbeiten"
                    >
                      <PencilIcon />
                    </button>
                    <button
                      className={`${styles.iconBtn} ${styles.iconBtnDanger}`}
                      onClick={() => handleDelete(item.id)}
                      title="Löschen"
                    >
                      <TrashIcon />
                    </button>
                  </div>
                </td>
              </tr>
            ),
          )}
        </tbody>
      </table>
    </div>
  );
}

// ============================================================
//  Generic ConfigList (for AccountTypes & RelationshipTypes)
// ============================================================

interface ConfigListItem {
  id: string;
  name: string;
  sortOrder: number;
  _count?: Record<string, number>;
}

interface ConfigListProps<T extends ConfigListItem> {
  title: string;
  description: string;
  items: T[];
  deleteConfirmText: string;
  emptyText: string;
  onCreate: (data: { name: string; sortOrder?: number }) => void;
  onUpdate: (id: string, data: { name?: string; sortOrder?: number }) => void;
  onDelete: (id: string) => void;
  isCreating: boolean;
  isUpdating: boolean;
}

function ConfigList<T extends ConfigListItem>({
  title,
  description,
  items,
  deleteConfirmText,
  emptyText,
  onCreate,
  onUpdate,
  onDelete,
  isCreating,
  isUpdating,
}: ConfigListProps<T>) {
  const [editId, setEditId] = useState<string | null>(null);
  const [addMode, setAddMode] = useState(false);
  const [name, setName] = useState('');

  const startAdd = useCallback(() => {
    setEditId(null);
    setName('');
    setAddMode(true);
  }, []);

  const startEdit = useCallback((item: T) => {
    setAddMode(false);
    setEditId(item.id);
    setName(item.name);
  }, []);

  const cancel = useCallback(() => {
    setEditId(null);
    setAddMode(false);
    setName('');
  }, []);

  const handleSave = useCallback(() => {
    if (!name.trim()) return;
    if (addMode) {
      onCreate({ name: name.trim() });
      cancel();
    } else if (editId) {
      onUpdate(editId, { name: name.trim() });
      cancel();
    }
  }, [addMode, editId, name, onCreate, onUpdate, cancel]);

  const handleDelete = useCallback(
    (id: string) => {
      if (window.confirm(deleteConfirmText)) {
        onDelete(id);
      }
    },
    [onDelete, deleteConfirmText],
  );

  const handleSort = useCallback(
    (item: T, direction: 'up' | 'down') => {
      const newOrder =
        direction === 'up'
          ? Math.max(0, item.sortOrder - 1)
          : item.sortOrder + 1;
      onUpdate(item.id, { sortOrder: newOrder });
    },
    [onUpdate],
  );

  const isSaving = isCreating || isUpdating;

  return (
    <div className={styles.card}>
      <div className={styles.configHeader}>
        <div>
          <h2 className={styles.cardTitle}>{title}</h2>
          <p className={styles.cardDesc} style={{ marginBottom: 0 }}>
            {description}
          </p>
        </div>
        <button className={styles.addBtn} onClick={startAdd} disabled={addMode}>
          <PlusIcon /> Hinzufügen
        </button>
      </div>

      <table className={styles.configTable}>
        <thead>
          <tr>
            <th style={{ width: 40 }}>#</th>
            <th>Name</th>
            <th style={{ width: 100, textAlign: 'right' }}>Aktionen</th>
          </tr>
        </thead>
        <tbody>
          {addMode && (
            <tr>
              <td>—</td>
              <td>
                <div className={styles.inlineForm}>
                  <input
                    className={styles.inlineInput}
                    style={{ flex: 1 }}
                    value={name}
                    onChange={(e) => setName(e.target.value)}
                    placeholder="Name eingeben"
                    autoFocus
                    onKeyDown={(e) => {
                      if (e.key === 'Enter') handleSave();
                      if (e.key === 'Escape') cancel();
                    }}
                  />
                </div>
              </td>
              <td>
                <div className={styles.actionsCell}>
                  <button className={styles.saveBtn} onClick={handleSave} disabled={!name.trim() || isSaving}>
                    Speichern
                  </button>
                  <button className={styles.cancelBtn} onClick={cancel}>
                    Abbrechen
                  </button>
                </div>
              </td>
            </tr>
          )}
          {items.length === 0 && !addMode && (
            <tr>
              <td colSpan={3} className={styles.emptyRow}>
                {emptyText}
              </td>
            </tr>
          )}
          {items.map((item, idx) =>
            editId === item.id ? (
              <tr key={item.id}>
                <td>{idx + 1}</td>
                <td>
                  <div className={styles.inlineForm}>
                    <input
                      className={styles.inlineInput}
                      style={{ flex: 1 }}
                      value={name}
                      onChange={(e) => setName(e.target.value)}
                      autoFocus
                      onKeyDown={(e) => {
                        if (e.key === 'Enter') handleSave();
                        if (e.key === 'Escape') cancel();
                      }}
                    />
                  </div>
                </td>
                <td>
                  <div className={styles.actionsCell}>
                    <button className={styles.saveBtn} onClick={handleSave} disabled={!name.trim() || isSaving}>
                      Speichern
                    </button>
                    <button className={styles.cancelBtn} onClick={cancel}>
                      Abbrechen
                    </button>
                  </div>
                </td>
              </tr>
            ) : (
              <tr key={item.id}>
                <td>
                  <div className={styles.sortBtns}>
                    <button
                      className={styles.sortBtn}
                      onClick={() => handleSort(item, 'up')}
                      disabled={idx === 0}
                      title="Nach oben"
                    >
                      <ArrowUpIcon />
                    </button>
                    <button
                      className={styles.sortBtn}
                      onClick={() => handleSort(item, 'down')}
                      disabled={idx === items.length - 1}
                      title="Nach unten"
                    >
                      <ArrowDownIcon />
                    </button>
                  </div>
                </td>
                <td>{item.name}</td>
                <td>
                  <div className={styles.actionsCell}>
                    <button
                      className={styles.iconBtn}
                      onClick={() => startEdit(item)}
                      title="Bearbeiten"
                    >
                      <PencilIcon />
                    </button>
                    <button
                      className={`${styles.iconBtn} ${styles.iconBtnDanger}`}
                      onClick={() => handleDelete(item.id)}
                      title="Löschen"
                    >
                      <TrashIcon />
                    </button>
                  </div>
                </td>
              </tr>
            ),
          )}
        </tbody>
      </table>
    </div>
  );
}

// ============================================================
//  AccountTypesConfig
// ============================================================

function AccountTypesConfig() {
  const { data } = useAccountTypes();
  const createMut = useCreateAccountType();
  const updateMut = useUpdateAccountType();
  const deleteMut = useDeleteAccountType();

  const items: AccountType[] = data?.data ?? [];

  return (
    <ConfigList
      title="Kontotypen"
      description="Kontotypen zur Klassifizierung von Unternehmen (z.B. Interessent, Endkunde, Partner)."
      items={items}
      deleteConfirmText="Kontotyp wirklich löschen?"
      emptyText="Noch keine Kontotypen definiert"
      onCreate={(d) => createMut.mutate(d)}
      onUpdate={(id, d) => updateMut.mutate({ id, data: d })}
      onDelete={(id) => deleteMut.mutate(id)}
      isCreating={createMut.isPending}
      isUpdating={updateMut.isPending}
    />
  );
}

// ============================================================
//  RelationshipTypesConfig
// ============================================================

function RelationshipTypesConfig() {
  const { data } = useRelationshipTypes();
  const createMut = useCreateRelationshipType();
  const updateMut = useUpdateRelationshipType();
  const deleteMut = useDeleteRelationshipType();

  const items: RelationshipType[] = data?.data ?? [];

  return (
    <ConfigList
      title="Beziehungstypen"
      description="Beziehungstypen für Unternehmensverknüpfungen (z.B. Muttergesellschaft, Abrechnungspartner)."
      items={items}
      deleteConfirmText="Beziehungstyp wirklich löschen?"
      emptyText="Noch keine Beziehungstypen definiert"
      onCreate={(d) => createMut.mutate(d)}
      onUpdate={(id, d) => updateMut.mutate({ id, data: d })}
      onDelete={(id) => deleteMut.mutate(id)}
      isCreating={createMut.isPending}
      isUpdating={updateMut.isPending}
    />
  );
}

// ============================================================
//  DealTypesConfig (Vorgangsart)
// ============================================================

function DealTypesConfig() {
  const { data } = useDealTypes();
  const createMut = useCreateDealType();
  const updateMut = useUpdateDealType();
  const deleteMut = useDeleteDealType();

  const items: DealType[] = data?.data ?? [];

  const [editId, setEditId] = useState<string | null>(null);
  const [addMode, setAddMode] = useState(false);
  const [name, setName] = useState('');
  const [color, setColor] = useState('#6B7280');
  const [isProjectType, setIsProjectType] = useState(false);

  const startAdd = useCallback(() => {
    setEditId(null);
    setName('');
    setColor('#6B7280');
    setIsProjectType(false);
    setAddMode(true);
  }, []);

  const startEdit = useCallback((item: DealType) => {
    setAddMode(false);
    setEditId(item.id);
    setName(item.name);
    setColor(item.color);
    setIsProjectType(item.isProjectType ?? false);
  }, []);

  const cancel = useCallback(() => {
    setEditId(null);
    setAddMode(false);
    setName('');
    setColor('#6B7280');
    setIsProjectType(false);
  }, []);

  const handleSave = useCallback(() => {
    if (!name.trim()) return;
    if (addMode) {
      createMut.mutate(
        { name: name.trim(), color, isProjectType },
        { onSuccess: cancel },
      );
    } else if (editId) {
      updateMut.mutate(
        { id: editId, data: { name: name.trim(), color, isProjectType } },
        { onSuccess: cancel },
      );
    }
  }, [addMode, editId, name, color, isProjectType, createMut, updateMut, cancel]);

  const handleDelete = useCallback(
    (id: string) => {
      if (window.confirm('Vorgangsart wirklich löschen?')) {
        deleteMut.mutate(id);
      }
    },
    [deleteMut],
  );

  const handleSort = useCallback(
    (item: DealType, direction: 'up' | 'down') => {
      const newOrder =
        direction === 'up'
          ? Math.max(0, item.sortOrder - 1)
          : item.sortOrder + 1;
      updateMut.mutate({ id: item.id, data: { sortOrder: newOrder } });
    },
    [updateMut],
  );

  const isSaving = createMut.isPending || updateMut.isPending;

  return (
    <div className={styles.card}>
      <div className={styles.configHeader}>
        <div>
          <h2 className={styles.cardTitle}>Vorgangsarten</h2>
          <p className={styles.cardDesc} style={{ marginBottom: 0 }}>
            Kategorien für Vorgänge (z.B. Neukunde, Nachkauf, Partneranfrage). Farben werden als Badge angezeigt.
          </p>
        </div>
        <button className={styles.addBtn} onClick={startAdd} disabled={addMode}>
          <PlusIcon /> Hinzufügen
        </button>
      </div>

      <table className={styles.configTable}>
        <thead>
          <tr>
            <th style={{ width: 40 }}>#</th>
            <th>Name</th>
            <th style={{ width: 60 }}>Farbe</th>
            <th style={{ width: 110, textAlign: 'center' }} title="Zeigt Projektanfrage-Felder im Vorgangs-Formular">Projektanfrage</th>
            <th style={{ width: 100, textAlign: 'right' }}>Aktionen</th>
          </tr>
        </thead>
        <tbody>
          {addMode && (
            <tr>
              <td>—</td>
              <td>
                <div className={styles.inlineForm}>
                  <input
                    className={styles.inlineInput}
                    style={{ flex: 1 }}
                    value={name}
                    onChange={(e) => setName(e.target.value)}
                    placeholder="Vorgangsart-Name"
                    autoFocus
                    onKeyDown={(e) => {
                      if (e.key === 'Enter') handleSave();
                      if (e.key === 'Escape') cancel();
                    }}
                  />
                </div>
              </td>
              <td>
                <input
                  type="color"
                  className={styles.colorInput}
                  value={color}
                  onChange={(e) => setColor(e.target.value)}
                />
              </td>
              <td style={{ textAlign: 'center' }}>
                <input
                  type="checkbox"
                  checked={isProjectType}
                  onChange={(e) => setIsProjectType(e.target.checked)}
                  title="Als Projektanfrage-Typ markieren"
                />
              </td>
              <td>
                <div className={styles.actionsCell}>
                  <button className={styles.saveBtn} onClick={handleSave} disabled={!name.trim() || isSaving}>
                    Speichern
                  </button>
                  <button className={styles.cancelBtn} onClick={cancel}>
                    Abbrechen
                  </button>
                </div>
              </td>
            </tr>
          )}
          {items.length === 0 && !addMode && (
            <tr>
              <td colSpan={5} className={styles.emptyRow}>
                Noch keine Vorgangsarten definiert
              </td>
            </tr>
          )}
          {items.map((item, idx) =>
            editId === item.id ? (
              <tr key={item.id}>
                <td>{idx + 1}</td>
                <td>
                  <div className={styles.inlineForm}>
                    <input
                      className={styles.inlineInput}
                      style={{ flex: 1 }}
                      value={name}
                      onChange={(e) => setName(e.target.value)}
                      autoFocus
                      onKeyDown={(e) => {
                        if (e.key === 'Enter') handleSave();
                        if (e.key === 'Escape') cancel();
                      }}
                    />
                  </div>
                </td>
                <td>
                  <input
                    type="color"
                    className={styles.colorInput}
                    value={color}
                    onChange={(e) => setColor(e.target.value)}
                  />
                </td>
                <td style={{ textAlign: 'center' }}>
                  <input
                    type="checkbox"
                    checked={isProjectType}
                    onChange={(e) => setIsProjectType(e.target.checked)}
                    title="Als Projektanfrage-Typ markieren"
                  />
                </td>
                <td>
                  <div className={styles.actionsCell}>
                    <button className={styles.saveBtn} onClick={handleSave} disabled={!name.trim() || isSaving}>
                      Speichern
                    </button>
                    <button className={styles.cancelBtn} onClick={cancel}>
                      Abbrechen
                    </button>
                  </div>
                </td>
              </tr>
            ) : (
              <tr key={item.id}>
                <td>
                  <div className={styles.sortBtns}>
                    <button
                      className={styles.sortBtn}
                      onClick={() => handleSort(item, 'up')}
                      disabled={idx === 0}
                      title="Nach oben"
                    >
                      <ArrowUpIcon />
                    </button>
                    <button
                      className={styles.sortBtn}
                      onClick={() => handleSort(item, 'down')}
                      disabled={idx === items.length - 1}
                      title="Nach unten"
                    >
                      <ArrowDownIcon />
                    </button>
                  </div>
                </td>
                <td>{item.name}</td>
                <td>
                  <span
                    className={styles.colorDot}
                    style={{ backgroundColor: item.color }}
                    title={item.color}
                  />
                </td>
                <td style={{ textAlign: 'center' }}>
                  {item.isProjectType ? (
                    <span title="Projektanfrage-Typ" style={{ color: 'var(--color-primary)', fontSize: '1rem' }}>✓</span>
                  ) : (
                    <span style={{ color: 'var(--color-text-muted)', fontSize: '0.75rem' }}>—</span>
                  )}
                </td>
                <td>
                  <div className={styles.actionsCell}>
                    <button
                      className={styles.iconBtn}
                      onClick={() => startEdit(item)}
                      title="Bearbeiten"
                    >
                      <PencilIcon />
                    </button>
                    <button
                      className={`${styles.iconBtn} ${styles.iconBtnDanger}`}
                      onClick={() => handleDelete(item.id)}
                      title="Löschen"
                    >
                      <TrashIcon />
                    </button>
                  </div>
                </td>
              </tr>
            ),
          )}
        </tbody>
      </table>
    </div>
  );
}

// ============================================================
//  CustomFieldsConfig (Phase 2.1)
// ============================================================

const ENTITY_TYPES: CustomFieldEntityType[] = ['PERSON', 'COMPANY', 'DEAL'];
const FIELD_TYPES: CustomFieldType[] = [
  'TEXT', 'TEXTAREA', 'NUMBER', 'DATE', 'DROPDOWN', 'MULTI_SELECT', 'CHECKBOX', 'URL',
];

const needsOptions = (ft: CustomFieldType) => ft === 'DROPDOWN' || ft === 'MULTI_SELECT';

function CustomFieldsConfig() {
  const [entityFilter, setEntityFilter] = useState<CustomFieldEntityType>('PERSON');
  const { data, isLoading } = useCustomFieldDefs(entityFilter);
  const createMut = useCreateCustomFieldDef();
  const updateMut = useUpdateCustomFieldDef();
  const deleteMut = useDeleteCustomFieldDef();

  const defs: CustomFieldDef[] = data?.data ?? [];

  // Add mode state
  const [addMode, setAddMode] = useState(false);
  const [newLabel, setNewLabel] = useState('');
  const [newFieldType, setNewFieldType] = useState<CustomFieldType>('TEXT');
  const [newRequired, setNewRequired] = useState(false);
  const [newOptions, setNewOptions] = useState<CustomFieldOption[]>([]);
  const [newOptionValue, setNewOptionValue] = useState('');
  const [newOptionLabel, setNewOptionLabel] = useState('');

  // Edit mode state
  const [editId, setEditId] = useState<string | null>(null);
  const [editLabel, setEditLabel] = useState('');
  const [editRequired, setEditRequired] = useState(false);
  const [editOptions, setEditOptions] = useState<CustomFieldOption[]>([]);
  const [editOptionValue, setEditOptionValue] = useState('');
  const [editOptionLabel, setEditOptionLabel] = useState('');

  const resetAdd = useCallback(() => {
    setAddMode(false);
    setNewLabel('');
    setNewFieldType('TEXT');
    setNewRequired(false);
    setNewOptions([]);
    setNewOptionValue('');
    setNewOptionLabel('');
  }, []);

  const resetEdit = useCallback(() => {
    setEditId(null);
    setEditLabel('');
    setEditRequired(false);
    setEditOptions([]);
    setEditOptionValue('');
    setEditOptionLabel('');
  }, []);

  const startEdit = useCallback((def: CustomFieldDef) => {
    setAddMode(false);
    setEditId(def.id);
    setEditLabel(def.label);
    setEditRequired(def.isRequired);
    setEditOptions(def.options ?? []);
  }, []);

  const handleCreate = useCallback(() => {
    if (!newLabel.trim()) return;
    const payload: {
      entityType: CustomFieldEntityType;
      label: string;
      fieldType: CustomFieldType;
      isRequired: boolean;
      options?: CustomFieldOption[];
    } = {
      entityType: entityFilter,
      label: newLabel.trim(),
      fieldType: newFieldType,
      isRequired: newRequired,
    };
    if (needsOptions(newFieldType) && newOptions.length > 0) {
      payload.options = newOptions;
    }
    createMut.mutate(payload, { onSuccess: resetAdd });
  }, [entityFilter, newLabel, newFieldType, newRequired, newOptions, createMut, resetAdd]);

  const handleUpdate = useCallback(() => {
    if (!editId || !editLabel.trim()) return;
    const def = defs.find((d) => d.id === editId);
    if (!def) return;
    const payload: { label: string; isRequired: boolean; options?: CustomFieldOption[] } = {
      label: editLabel.trim(),
      isRequired: editRequired,
    };
    if (needsOptions(def.fieldType)) {
      payload.options = editOptions;
    }
    updateMut.mutate({ id: editId, data: payload }, { onSuccess: resetEdit });
  }, [editId, editLabel, editRequired, editOptions, defs, updateMut, resetEdit]);

  const handleDelete = useCallback(
    (id: string) => {
      if (window.confirm('Benutzerdefiniertes Feld wirklich loeschen? Alle gespeicherten Werte werden ebenfalls geloescht!')) {
        deleteMut.mutate(id);
      }
    },
    [deleteMut],
  );

  const handleSort = useCallback(
    (def: CustomFieldDef, direction: 'up' | 'down') => {
      const newPos = direction === 'up' ? Math.max(0, def.position - 1) : def.position + 1;
      updateMut.mutate({ id: def.id, data: { position: newPos } });
    },
    [updateMut],
  );

  const addNewOption = useCallback(() => {
    if (!newOptionValue.trim() || !newOptionLabel.trim()) return;
    setNewOptions((prev) => [...prev, { value: newOptionValue.trim(), label: newOptionLabel.trim() }]);
    setNewOptionValue('');
    setNewOptionLabel('');
  }, [newOptionValue, newOptionLabel]);

  const addEditOption = useCallback(() => {
    if (!editOptionValue.trim() || !editOptionLabel.trim()) return;
    setEditOptions((prev) => [...prev, { value: editOptionValue.trim(), label: editOptionLabel.trim() }]);
    setEditOptionValue('');
    setEditOptionLabel('');
  }, [editOptionValue, editOptionLabel]);

  const isSaving = createMut.isPending || updateMut.isPending;

  const optionBadgeStyle: React.CSSProperties = {
    display: 'inline-flex',
    alignItems: 'center',
    gap: '0.25rem',
    padding: '0.125rem 0.5rem',
    background: 'var(--color-bg)',
    border: '1px solid var(--color-border)',
    borderRadius: '9999px',
    fontSize: '0.75rem',
    color: 'var(--color-text-secondary)',
  };

  const optionRemoveStyle: React.CSSProperties = {
    background: 'none',
    border: 'none',
    cursor: 'pointer',
    fontSize: '0.875rem',
    lineHeight: 1,
    color: 'var(--color-text-muted)',
    padding: 0,
  };

  return (
    <div className={styles.card}>
      <div className={styles.configHeader}>
        <div>
          <h2 className={styles.cardTitle}>Benutzerdefinierte Felder</h2>
          <p className={styles.cardDesc} style={{ marginBottom: 0 }}>
            Individuelle Datenfelder fuer Kontakte, Unternehmen und Vorgaenge.
          </p>
        </div>
        <button className={styles.addBtn} onClick={() => { resetEdit(); setAddMode(true); }} disabled={addMode}>
          <PlusIcon /> Neues Feld
        </button>
      </div>

      {/* Entity-Typ Filter */}
      <div style={{ display: 'flex', gap: '0.25rem', marginBottom: '1rem' }}>
        {ENTITY_TYPES.map((et) => (
          <button
            key={et}
            onClick={() => { setEntityFilter(et); resetAdd(); resetEdit(); }}
            style={{
              padding: '0.375rem 0.75rem',
              fontSize: '0.8125rem',
              fontWeight: 500,
              border: '1px solid',
              borderColor: entityFilter === et ? 'var(--color-primary)' : 'var(--color-border)',
              borderRadius: 'var(--radius-sm)',
              background: entityFilter === et ? 'var(--color-primary)' : 'transparent',
              color: entityFilter === et ? 'white' : 'var(--color-text-secondary)',
              cursor: 'pointer',
              transition: 'all 0.15s',
            }}
          >
            {CUSTOM_FIELD_ENTITY_TYPE_LABELS[et]}
          </button>
        ))}
      </div>

      {/* Add form */}
      {addMode && (
        <div style={{
          padding: '1rem',
          marginBottom: '1rem',
          background: 'var(--color-bg)',
          borderRadius: 'var(--radius-sm)',
          border: '1px solid var(--color-border)',
        }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '0.75rem', marginBottom: '0.75rem' }}>
            <div>
              <label style={{ fontSize: '0.8125rem', fontWeight: 500, display: 'block', marginBottom: '0.25rem' }}>
                Bezeichnung *
              </label>
              <input
                className={styles.inlineInput}
                style={{ width: '100%' }}
                value={newLabel}
                onChange={(e) => setNewLabel(e.target.value)}
                placeholder="z.B. Kundennummer"
                autoFocus
              />
            </div>
            <div>
              <label style={{ fontSize: '0.8125rem', fontWeight: 500, display: 'block', marginBottom: '0.25rem' }}>
                Feldtyp *
              </label>
              <select
                className={styles.inlineInput}
                style={{ width: '100%', cursor: 'pointer' }}
                value={newFieldType}
                onChange={(e) => setNewFieldType(e.target.value as CustomFieldType)}
              >
                {FIELD_TYPES.map((ft) => (
                  <option key={ft} value={ft}>{CUSTOM_FIELD_TYPE_LABELS[ft]}</option>
                ))}
              </select>
            </div>
          </div>

          <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', marginBottom: '0.75rem' }}>
            <label style={{ display: 'flex', alignItems: 'center', gap: '0.375rem', fontSize: '0.8125rem', cursor: 'pointer' }}>
              <input
                type="checkbox"
                checked={newRequired}
                onChange={(e) => setNewRequired(e.target.checked)}
              />
              Pflichtfeld
            </label>
          </div>

          {/* Options editor for DROPDOWN / MULTI_SELECT */}
          {needsOptions(newFieldType) && (
            <div style={{ marginBottom: '0.75rem' }}>
              <label style={{ fontSize: '0.8125rem', fontWeight: 500, display: 'block', marginBottom: '0.375rem' }}>
                Optionen
              </label>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.25rem', marginBottom: '0.5rem' }}>
                {newOptions.map((opt, i) => (
                  <span key={i} style={optionBadgeStyle}>
                    {opt.label}
                    <button style={optionRemoveStyle} onClick={() => setNewOptions((prev) => prev.filter((_, j) => j !== i))}>
                      &times;
                    </button>
                  </span>
                ))}
                {newOptions.length === 0 && (
                  <span style={{ fontSize: '0.8125rem', color: 'var(--color-text-muted)', fontStyle: 'italic' }}>
                    Noch keine Optionen
                  </span>
                )}
              </div>
              <div style={{ display: 'flex', gap: '0.5rem', alignItems: 'center' }}>
                <input
                  className={styles.inlineInput}
                  value={newOptionValue}
                  onChange={(e) => setNewOptionValue(e.target.value)}
                  placeholder="Wert"
                  style={{ width: 120 }}
                  onKeyDown={(e) => { if (e.key === 'Enter') addNewOption(); }}
                />
                <input
                  className={styles.inlineInput}
                  value={newOptionLabel}
                  onChange={(e) => setNewOptionLabel(e.target.value)}
                  placeholder="Anzeige-Name"
                  style={{ flex: 1 }}
                  onKeyDown={(e) => { if (e.key === 'Enter') addNewOption(); }}
                />
                <button
                  className={styles.saveBtn}
                  onClick={addNewOption}
                  disabled={!newOptionValue.trim() || !newOptionLabel.trim()}
                  style={{ padding: '0.375rem 0.625rem', fontSize: '0.75rem' }}
                >
                  +
                </button>
              </div>
            </div>
          )}

          <div style={{ display: 'flex', gap: '0.5rem', justifyContent: 'flex-end' }}>
            <button className={styles.cancelBtn} onClick={resetAdd}>Abbrechen</button>
            <button
              className={styles.saveBtn}
              onClick={handleCreate}
              disabled={!newLabel.trim() || isSaving || (needsOptions(newFieldType) && newOptions.length === 0)}
            >
              {createMut.isPending ? 'Erstellen...' : 'Feld erstellen'}
            </button>
          </div>
        </div>
      )}

      {/* Table */}
      {isLoading ? (
        <p style={{ fontSize: '0.875rem', color: 'var(--color-text-muted)' }}>Laden...</p>
      ) : (
        <table className={styles.configTable}>
          <thead>
            <tr>
              <th style={{ width: 40 }}>#</th>
              <th>Bezeichnung</th>
              <th>Typ</th>
              <th style={{ width: 60 }}>Pflicht</th>
              <th style={{ width: 120, textAlign: 'right' }}>Aktionen</th>
            </tr>
          </thead>
          <tbody>
            {defs.length === 0 && !addMode && (
              <tr>
                <td colSpan={5} className={styles.emptyRow}>
                  Noch keine Felder fuer {CUSTOM_FIELD_ENTITY_TYPE_LABELS[entityFilter]} definiert
                </td>
              </tr>
            )}
            {defs.map((def, idx) =>
              editId === def.id ? (
                <tr key={def.id}>
                  <td>{idx + 1}</td>
                  <td colSpan={4}>
                    <div style={{
                      padding: '0.75rem',
                      background: 'var(--color-bg)',
                      borderRadius: 'var(--radius-sm)',
                      border: '1px solid var(--color-border)',
                    }}>
                      <div style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: '0.75rem', marginBottom: '0.5rem', alignItems: 'end' }}>
                        <div>
                          <label style={{ fontSize: '0.75rem', fontWeight: 500, display: 'block', marginBottom: '0.25rem' }}>
                            Bezeichnung
                          </label>
                          <input
                            className={styles.inlineInput}
                            style={{ width: '100%' }}
                            value={editLabel}
                            onChange={(e) => setEditLabel(e.target.value)}
                            autoFocus
                          />
                        </div>
                        <div style={{ display: 'flex', alignItems: 'center', gap: '0.375rem', paddingBottom: '0.25rem' }}>
                          <label style={{ display: 'flex', alignItems: 'center', gap: '0.25rem', fontSize: '0.8125rem', cursor: 'pointer' }}>
                            <input type="checkbox" checked={editRequired} onChange={(e) => setEditRequired(e.target.checked)} />
                            Pflicht
                          </label>
                        </div>
                      </div>
                      <div style={{ fontSize: '0.75rem', color: 'var(--color-text-muted)', marginBottom: '0.5rem' }}>
                        Typ: {CUSTOM_FIELD_TYPE_LABELS[def.fieldType]} (nicht aenderbar) &middot; Slug: {def.name}
                      </div>

                      {needsOptions(def.fieldType) && (
                        <div style={{ marginBottom: '0.75rem' }}>
                          <label style={{ fontSize: '0.75rem', fontWeight: 500, display: 'block', marginBottom: '0.375rem' }}>
                            Optionen
                          </label>
                          <div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.25rem', marginBottom: '0.5rem' }}>
                            {editOptions.map((opt, i) => (
                              <span key={i} style={optionBadgeStyle}>
                                {opt.label} ({opt.value})
                                <button style={optionRemoveStyle} onClick={() => setEditOptions((prev) => prev.filter((_, j) => j !== i))}>
                                  &times;
                                </button>
                              </span>
                            ))}
                          </div>
                          <div style={{ display: 'flex', gap: '0.5rem', alignItems: 'center' }}>
                            <input
                              className={styles.inlineInput}
                              value={editOptionValue}
                              onChange={(e) => setEditOptionValue(e.target.value)}
                              placeholder="Wert"
                              style={{ width: 120 }}
                              onKeyDown={(e) => { if (e.key === 'Enter') addEditOption(); }}
                            />
                            <input
                              className={styles.inlineInput}
                              value={editOptionLabel}
                              onChange={(e) => setEditOptionLabel(e.target.value)}
                              placeholder="Anzeige-Name"
                              style={{ flex: 1 }}
                              onKeyDown={(e) => { if (e.key === 'Enter') addEditOption(); }}
                            />
                            <button
                              className={styles.saveBtn}
                              onClick={addEditOption}
                              disabled={!editOptionValue.trim() || !editOptionLabel.trim()}
                              style={{ padding: '0.375rem 0.625rem', fontSize: '0.75rem' }}
                            >
                              +
                            </button>
                          </div>
                        </div>
                      )}

                      <div style={{ display: 'flex', gap: '0.5rem', justifyContent: 'flex-end' }}>
                        <button className={styles.cancelBtn} onClick={resetEdit}>Abbrechen</button>
                        <button
                          className={styles.saveBtn}
                          onClick={handleUpdate}
                          disabled={!editLabel.trim() || isSaving}
                        >
                          {updateMut.isPending ? 'Speichern...' : 'Speichern'}
                        </button>
                      </div>
                    </div>
                  </td>
                </tr>
              ) : (
                <tr key={def.id}>
                  <td>
                    <div className={styles.sortBtns}>
                      <button className={styles.sortBtn} onClick={() => handleSort(def, 'up')} disabled={idx === 0} title="Nach oben">
                        <ArrowUpIcon />
                      </button>
                      <button className={styles.sortBtn} onClick={() => handleSort(def, 'down')} disabled={idx === defs.length - 1} title="Nach unten">
                        <ArrowDownIcon />
                      </button>
                    </div>
                  </td>
                  <td>
                    <div>
                      <span style={{ fontWeight: 500 }}>{def.label}</span>
                      <span style={{ color: 'var(--color-text-muted)', fontSize: '0.75rem', marginLeft: '0.5rem' }}>
                        ({def.name})
                      </span>
                    </div>
                    {def.options && def.options.length > 0 && (
                      <div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.25rem', marginTop: '0.25rem' }}>
                        {def.options.map((opt, i) => (
                          <span key={i} style={{ ...optionBadgeStyle, fontSize: '0.6875rem' }}>
                            {opt.label}
                          </span>
                        ))}
                      </div>
                    )}
                  </td>
                  <td>
                    <span style={{
                      display: 'inline-block',
                      padding: '0.125rem 0.375rem',
                      background: '#f3f4f6',
                      borderRadius: '4px',
                      fontSize: '0.75rem',
                      color: '#4b5563',
                    }}>
                      {CUSTOM_FIELD_TYPE_LABELS[def.fieldType]}
                    </span>
                  </td>
                  <td style={{ textAlign: 'center' }}>
                    {def.isRequired ? (
                      <span style={{ color: 'var(--color-primary)', fontWeight: 600, fontSize: '0.875rem' }}>Ja</span>
                    ) : (
                      <span style={{ color: 'var(--color-text-muted)', fontSize: '0.8125rem' }}>&mdash;</span>
                    )}
                  </td>
                  <td>
                    <div className={styles.actionsCell}>
                      <button className={styles.iconBtn} onClick={() => startEdit(def)} title="Bearbeiten">
                        <PencilIcon />
                      </button>
                      <button
                        className={`${styles.iconBtn} ${styles.iconBtnDanger}`}
                        onClick={() => handleDelete(def.id)}
                        title="Loeschen"
                      >
                        <TrashIcon />
                      </button>
                    </div>
                  </td>
                </tr>
              ),
            )}
          </tbody>
        </table>
      )}
    </div>
  );
}

// ============================================================
//  North Data Integration Config
// ============================================================

function NorthDataConfig() {
  const { data, isLoading } = useEnrichmentConfig();
  const setConfig = useSetEnrichmentConfig();
  const [apiKey, setApiKey] = useState('');
  const [editing, setEditing] = useState(false);

  const config = data?.data;

  return (
    <div className={styles.card}>
      <h2 className={styles.cardTitle}>North Data API</h2>
      <p className={styles.cardDesc}>
        Konfiguriere den API-Key für die Datenanreicherung über North Data. Damit
        können Unternehmensdaten (Handelsregister, USt-IdNr., Branche etc.) automatisch
        ergänzt werden.
      </p>

      {isLoading ? (
        <p style={{ fontSize: '0.875rem', color: 'var(--color-text-muted)' }}>Laden...</p>
      ) : (
        <div style={{ marginTop: '1rem' }}>
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              gap: '0.5rem',
              marginBottom: '0.75rem',
            }}
          >
            <span
              style={{
                width: 8,
                height: 8,
                borderRadius: '50%',
                background: config?.configured ? '#059669' : 'var(--color-text-muted)',
                display: 'inline-block',
              }}
            />
            <span style={{ fontSize: '0.875rem' }}>
              {config?.configured ? 'API-Key konfiguriert' : 'Nicht konfiguriert'}
            </span>
          </div>

          {editing ? (
            <div style={{ display: 'flex', gap: '0.5rem', alignItems: 'flex-end' }}>
              <div style={{ flex: 1 }}>
                <label
                  style={{
                    fontSize: '0.8125rem',
                    fontWeight: 500,
                    color: 'var(--color-text-muted)',
                    display: 'block',
                    marginBottom: '0.25rem',
                  }}
                >
                  API-Key
                </label>
                <input
                  type="password"
                  value={apiKey}
                  onChange={(e) => setApiKey(e.target.value)}
                  placeholder="North Data API Key eingeben"
                  style={{
                    width: '100%',
                    padding: '0.5rem 0.75rem',
                    border: '1px solid var(--color-border)',
                    borderRadius: 'var(--radius-sm)',
                    fontSize: '0.875rem',
                    background: 'var(--color-bg)',
                    color: 'var(--color-text)',
                    boxSizing: 'border-box',
                  }}
                />
              </div>
              <button
                onClick={() => {
                  if (!apiKey.trim()) return;
                  setConfig.mutate(apiKey.trim(), {
                    onSuccess: () => {
                      setApiKey('');
                      setEditing(false);
                    },
                  });
                }}
                disabled={!apiKey.trim() || setConfig.isPending}
                style={{
                  padding: '0.5rem 1rem',
                  background: 'var(--color-primary)',
                  color: 'white',
                  border: 'none',
                  borderRadius: 'var(--radius-sm)',
                  fontSize: '0.875rem',
                  fontWeight: 600,
                  cursor: !apiKey.trim() || setConfig.isPending ? 'not-allowed' : 'pointer',
                  opacity: !apiKey.trim() || setConfig.isPending ? 0.5 : 1,
                  whiteSpace: 'nowrap',
                }}
              >
                {setConfig.isPending ? 'Speichern...' : 'Speichern'}
              </button>
              <button
                onClick={() => {
                  setEditing(false);
                  setApiKey('');
                }}
                style={{
                  padding: '0.5rem 0.75rem',
                  background: 'transparent',
                  border: '1px solid var(--color-border)',
                  borderRadius: 'var(--radius-sm)',
                  fontSize: '0.875rem',
                  cursor: 'pointer',
                  color: 'var(--color-text-secondary)',
                }}
              >
                Abbrechen
              </button>
            </div>
          ) : (
            <button
              onClick={() => setEditing(true)}
              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)',
              }}
            >
              {config?.configured ? 'API-Key ändern' : 'API-Key eingeben'}
            </button>
          )}
        </div>
      )}
    </div>
  );
}

// ============================================================
//  Page Component
// ============================================================

type SettingsTab = 'module' | 'customfields' | 'lexware' | 'integrations' | 'import' | 'settings';

export function CrmSettingsPage() {
  const { user } = useAuth();
  const { settings, toggleModule, isModuleEnabled } = useCrmSettings();
  const [activeTab, setActiveTab] = useState<SettingsTab>('module');

  // Zugriffskontrolle: nur Admins
  if (
    user?.role !== 'PLATFORM_ADMIN' &&
    user?.role !== 'TENANT_ADMIN'
  ) {
    return <Navigate to="/" replace />;
  }

  const anyDisabled = Object.values(settings.modules).some(
    (m) => !m.enabled,
  );

  return (
    <div>
      {/* Zurück */}
      <Link to="/" 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 zum Dashboard
      </Link>

      {/* Header */}
      <h1 style={{ fontSize: '1.5rem', fontWeight: 600, marginBottom: '1.5rem' }}>
        CRM Einstellungen
      </h1>

      {/* Top-Level Tab Bar */}
      <div className={styles.settingsTabBar}>
        <button
          className={`${styles.settingsTab} ${activeTab === 'module' ? styles.settingsTabActive : ''}`}
          onClick={() => setActiveTab('module')}
        >
          <svg
            width="16"
            height="16"
            viewBox="0 0 16 16"
            fill="none"
            stroke="currentColor"
            strokeWidth="1.5"
            strokeLinecap="round"
            strokeLinejoin="round"
          >
            <rect x="2" y="2" width="5" height="5" rx="1" />
            <rect x="9" y="2" width="5" height="5" rx="1" />
            <rect x="2" y="9" width="5" height="5" rx="1" />
            <rect x="9" y="9" width="5" height="5" rx="1" />
          </svg>
          Module
        </button>
        <button
          className={`${styles.settingsTab} ${activeTab === 'customfields' ? styles.settingsTabActive : ''}`}
          onClick={() => setActiveTab('customfields')}
        >
          <svg
            width="16"
            height="16"
            viewBox="0 0 16 16"
            fill="none"
            stroke="currentColor"
            strokeWidth="1.5"
            strokeLinecap="round"
            strokeLinejoin="round"
          >
            <path d="M3 3h10v10H3z" />
            <path d="M6 6h4M6 8.5h4M6 11h2" />
          </svg>
          Eigene Felder
        </button>
        <button
          className={`${styles.settingsTab} ${activeTab === 'lexware' ? styles.settingsTabActive : ''}`}
          onClick={() => setActiveTab('lexware')}
        >
          <svg
            width="16"
            height="16"
            viewBox="0 0 16 16"
            fill="none"
            stroke="currentColor"
            strokeWidth="1.5"
            strokeLinecap="round"
            strokeLinejoin="round"
          >
            <path d="M1 8a7 7 0 0112.9-3.8M15 8a7 7 0 01-12.9 3.8" />
            <path d="M14 1v3.2h-3.2M2 15v-3.2h3.2" />
          </svg>
          Lexoffice Sync
        </button>
        <button
          className={`${styles.settingsTab} ${activeTab === 'integrations' ? styles.settingsTabActive : ''}`}
          onClick={() => setActiveTab('integrations')}
        >
          <svg
            width="16"
            height="16"
            viewBox="0 0 16 16"
            fill="none"
            stroke="currentColor"
            strokeWidth="1.5"
            strokeLinecap="round"
            strokeLinejoin="round"
          >
            <path d="M8 1v4M8 11v4M1 8h4M11 8h4" />
            <circle cx="8" cy="8" r="2" />
          </svg>
          Integrationen
        </button>
        <button
          className={`${styles.settingsTab} ${activeTab === 'import' ? styles.settingsTabActive : ''}`}
          onClick={() => setActiveTab('import')}
        >
          <svg
            width="16"
            height="16"
            viewBox="0 0 16 16"
            fill="none"
            stroke="currentColor"
            strokeWidth="1.5"
            strokeLinecap="round"
            strokeLinejoin="round"
          >
            <path d="M8 2v8M5 7l3 3 3-3" />
            <path d="M2 12h12" />
          </svg>
          Import
        </button>
        <button
          className={`${styles.settingsTab} ${activeTab === 'settings' ? styles.settingsTabActive : ''}`}
          onClick={() => setActiveTab('settings')}
        >
          <svg
            width="16"
            height="16"
            viewBox="0 0 16 16"
            fill="none"
            stroke="currentColor"
            strokeWidth="1.5"
            strokeLinecap="round"
            strokeLinejoin="round"
          >
            <circle cx="8" cy="8" r="2" />
            <path d="M8 1v2M8 13v2M1 8h2M13 8h2M3.05 3.05l1.41 1.41M11.54 11.54l1.41 1.41M3.05 12.95l1.41-1.41M11.54 4.46l1.41-1.41" />
          </svg>
          Weitere Einstellungen
        </button>
      </div>

      {/* ===== Tab Content ===== */}

      {/* Tab: Module */}
      {activeTab === 'module' && (
        <div className={styles.card}>
          <h2 className={styles.cardTitle}>Module</h2>
          <p className={styles.cardDesc}>
            Aktiviere oder deaktiviere einzelne CRM-Module. Deaktivierte Module
            werden aus dem Menü ausgeblendet.
          </p>

          <div className={styles.moduleList}>
            {MODULES.map((mod) => {
              const enabled = settings.modules[mod.key]?.enabled ?? true;
              return (
                <div key={mod.key} className={styles.moduleItem}>
                  <div
                    style={{
                      display: 'flex',
                      alignItems: 'center',
                      gap: '0.75rem',
                    }}
                  >
                    <span
                      style={{
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        width: 36,
                        height: 36,
                        borderRadius: 'var(--radius-sm)',
                        background: enabled
                          ? 'var(--color-primary-bg, #eff6ff)'
                          : 'var(--color-bg)',
                        color: enabled
                          ? 'var(--color-primary)'
                          : 'var(--color-text-muted)',
                        transition: 'background 0.2s, color 0.2s',
                      }}
                    >
                      {mod.icon}
                    </span>
                    <div className={styles.moduleInfo}>
                      <span
                        className={styles.moduleName}
                        style={{
                          opacity: enabled ? 1 : 0.5,
                          transition: 'opacity 0.2s',
                        }}
                      >
                        {mod.name}
                      </span>
                      <span className={styles.moduleDesc}>
                        {mod.description}
                      </span>
                    </div>
                  </div>
                  <label className={styles.toggle}>
                    <input
                      type="checkbox"
                      checked={enabled}
                      onChange={(e) =>
                        toggleModule(mod.key, e.target.checked)
                      }
                    />
                    <span className={styles.toggleTrack} />
                  </label>
                </div>
              );
            })}
          </div>

          {anyDisabled && (
            <div className={styles.warning}>
              <svg
                width="16"
                height="16"
                viewBox="0 0 16 16"
                fill="none"
                stroke="currentColor"
                strokeWidth="1.5"
                strokeLinecap="round"
                strokeLinejoin="round"
                style={{ flexShrink: 0, marginTop: 1 }}
              >
                <path d="M8 1L1 14h14L8 1z" />
                <path d="M8 6v3M8 11.5v.5" />
              </svg>
              <span>
                Deaktivierte Module werden aus dem Menü ausgeblendet.
                Bestehende Daten bleiben erhalten und sind nach Reaktivierung
                wieder verfügbar.
              </span>
            </div>
          )}
        </div>
      )}

      {/* Tab: Custom Fields */}
      {activeTab === 'customfields' && (
        <CustomFieldsConfig />
      )}

      {/* Tab: Lexoffice Sync */}
      {activeTab === 'lexware' && (
        <>
          {isModuleEnabled('lexware') ? (
            <LexwareSyncContent />
          ) : (
            <div className={styles.card}>
              <div className={styles.disabledHint}>
                <svg
                  width="20"
                  height="20"
                  viewBox="0 0 16 16"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="1.5"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                >
                  <circle cx="8" cy="8" r="7" />
                  <path d="M8 5v3M8 10.5v.5" />
                </svg>
                <div>
                  <strong>Lexware Office Modul deaktiviert</strong>
                  <p style={{ margin: '0.25rem 0 0', fontSize: '0.8125rem' }}>
                    Aktiviere das Lexware Office Modul im Tab &quot;Module&quot;,
                    um die Import/Export-Funktionen nutzen zu können.
                  </p>
                </div>
              </div>
            </div>
          )}
        </>
      )}

      {/* Tab: Integrationen */}
      {activeTab === 'integrations' && (
        <NorthDataConfig />
      )}

      {/* Tab: Import */}
      {activeTab === 'import' && (
        <div className={styles.card}>
          <ImportPage />
        </div>
      )}

      {/* Tab: Weitere Einstellungen */}
      {activeTab === 'settings' && (
        <>
          <DealTypesConfig />
          <IndustriesConfig />
          <AccountTypesConfig />
          <RelationshipTypesConfig />
        </>
      )}
    </div>
  );
}
