'use client'

import React, { useState, useEffect } from 'react'
import { useSDK } from '@/lib/sdk'
import {
  CompanyProfile,
  BusinessModel,
  OfferingType,
  TargetMarket,
  CompanySize,
  LegalForm,
  MachineBuilderProfile,
  MachineProductType,
  AIIntegrationType,
  HumanOversightLevel,
  CriticalSector,
  BUSINESS_MODEL_LABELS,
  OFFERING_TYPE_LABELS,
  TARGET_MARKET_LABELS,
  COMPANY_SIZE_LABELS,
  MACHINE_PRODUCT_TYPE_LABELS,
  AI_INTEGRATION_TYPE_LABELS,
  HUMAN_OVERSIGHT_LABELS,
  CRITICAL_SECTOR_LABELS,
} from '@/lib/sdk/types'

// =============================================================================
// WIZARD STEPS
// =============================================================================

const BASE_WIZARD_STEPS = [
  { id: 1, name: 'Basisinfos', description: 'Firmenname und Rechtsform' },
  { id: 2, name: 'Geschaeftsmodell', description: 'B2B, B2C und Angebote' },
  { id: 3, name: 'Firmengroesse', description: 'Mitarbeiter und Umsatz' },
  { id: 4, name: 'Standorte', description: 'Hauptsitz und Zielmaerkte' },
  { id: 5, name: 'Datenschutz', description: 'Rollen und KI-Nutzung' },
  { id: 6, name: 'Verarbeitung & KI', description: 'Verarbeitungstätigkeiten und KI-Systeme' },
  { id: 7, name: 'Rechtlicher Rahmen', description: 'Regulierungen und Prüfzyklen' },
]

const MACHINE_BUILDER_STEP = { id: 8, name: 'Produkt & Maschine', description: 'Software, KI und CE in Ihrem Produkt' }

function getWizardSteps(industry: string) {
  if (isMachineBuilderIndustry(industry)) {
    return [...BASE_WIZARD_STEPS, MACHINE_BUILDER_STEP]
  }
  return BASE_WIZARD_STEPS
}

// Keep WIZARD_STEPS for backwards compat in static references
const WIZARD_STEPS = BASE_WIZARD_STEPS

// =============================================================================
// LEGAL FORMS
// =============================================================================

const LEGAL_FORM_LABELS: Record<LegalForm, string> = {
  einzelunternehmen: 'Einzelunternehmen',
  gbr: 'GbR',
  ohg: 'OHG',
  kg: 'KG',
  gmbh: 'GmbH',
  ug: 'UG (haftungsbeschränkt)',
  ag: 'AG',
  gmbh_co_kg: 'GmbH & Co. KG',
  ev: 'e.V. (Verein)',
  stiftung: 'Stiftung',
  other: 'Sonstige',
}

// =============================================================================
// INDUSTRIES
// =============================================================================

const INDUSTRIES = [
  'Technologie / IT',
  'E-Commerce / Handel',
  'Finanzdienstleistungen',
  'Gesundheitswesen',
  'Bildung',
  'Beratung / Consulting',
  'Marketing / Agentur',
  'Produktion / Industrie',
  'Logistik / Transport',
  'Immobilien',
  'Maschinenbau',
  'Anlagenbau',
  'Automatisierung',
  'Robotik',
  'Messtechnik',
  'Sonstige',
]

const MACHINE_BUILDER_INDUSTRIES = [
  'Maschinenbau',
  'Anlagenbau',
  'Automatisierung',
  'Robotik',
  'Messtechnik',
]

const isMachineBuilderIndustry = (industry: string) =>
  MACHINE_BUILDER_INDUSTRIES.includes(industry)

// =============================================================================
// STEP COMPONENTS
// =============================================================================

function StepBasicInfo({
  data,
  onChange,
}: {
  data: Partial<CompanyProfile>
  onChange: (updates: Partial<CompanyProfile>) => void
}) {
  return (
    <div className="space-y-6">
      <div>
        <label className="block text-sm font-medium text-gray-700 mb-2">
          Firmenname <span className="text-red-500">*</span>
        </label>
        <input
          type="text"
          value={data.companyName || ''}
          onChange={e => onChange({ companyName: e.target.value })}
          placeholder="Ihre Firma (ohne Rechtsform)"
          className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
        />
      </div>

      <div>
        <label className="block text-sm font-medium text-gray-700 mb-2">
          Rechtsform <span className="text-red-500">*</span>
        </label>
        <select
          value={data.legalForm || ''}
          onChange={e => onChange({ legalForm: e.target.value as LegalForm })}
          className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
        >
          <option value="">Bitte wählen...</option>
          {Object.entries(LEGAL_FORM_LABELS).map(([value, label]) => (
            <option key={value} value={value}>
              {label}
            </option>
          ))}
        </select>
      </div>

      <div>
        <label className="block text-sm font-medium text-gray-700 mb-2">Branche</label>
        <select
          value={data.industry || ''}
          onChange={e => onChange({ industry: e.target.value })}
          className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
        >
          <option value="">Bitte wählen...</option>
          {INDUSTRIES.map(industry => (
            <option key={industry} value={industry}>
              {industry}
            </option>
          ))}
        </select>
      </div>

      <div>
        <label className="block text-sm font-medium text-gray-700 mb-2">Gründungsjahr</label>
        <input
          type="number"
          value={data.foundedYear || ''}
          onChange={e => {
            const val = parseInt(e.target.value)
            onChange({ foundedYear: isNaN(val) ? null : val })
          }}
          onFocus={e => {
            if (!data.foundedYear) onChange({ foundedYear: 2000 })
          }}
          placeholder="2020"
          min="1900"
          max={new Date().getFullYear()}
          className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
        />
      </div>
    </div>
  )
}

// URL fields shown when specific offerings are selected
const OFFERING_URL_CONFIG: Partial<Record<OfferingType, { label: string; placeholder: string; hint: string }>> = {
  website: { label: 'Website-Domain', placeholder: 'https://www.beispiel.de', hint: 'Ihre Unternehmenswebsite' },
  webshop: { label: 'Online-Shop URL', placeholder: 'https://shop.beispiel.de', hint: 'URL zu Ihrem Online-Shop' },
  app_mobile: { label: 'App-Store Links', placeholder: 'https://apps.apple.com/... oder https://play.google.com/...', hint: 'Apple App Store und/oder Google Play Store Link' },
  software_saas: { label: 'SaaS-Portal URL', placeholder: 'https://app.beispiel.de', hint: 'Login-/Registrierungsseite Ihres Kundenportals' },
  app_web: { label: 'Web-App URL', placeholder: 'https://app.beispiel.de', hint: 'URL zu Ihrer Web-Anwendung' },
}

// Step-specific explanations for "Warum diese Fragen?"
const STEP_EXPLANATIONS: Record<number, string> = {
  1: 'Rechtsform und Gründungsjahr bestimmen, welche Meldepflichten und Schwellenwerte für Ihr Unternehmen gelten (z.B. NIS2, AI Act).',
  2: 'Ihr Geschäftsmodell und Ihre Angebote bestimmen, welche DSGVO-Pflichten greifen: B2C erfordert z.B. strengere Einwilligungsregeln, Webshops brauchen Cookie-Banner und Datenschutzerklärungen, SaaS-Angebote eine Auftragsverarbeitung.',
  3: 'Die Unternehmensgröße bestimmt, ob Sie einen DSB benennen müssen (ab 20 MA), ob NIS2-Pflichten greifen und welche Audit-Anforderungen gelten.',
  4: 'Standorte und Zielmärkte bestimmen, welche nationalen Datenschutzgesetze zusätzlich zur DSGVO greifen (z.B. BDSG, DSG-AT, UK GDPR, CCPA).',
  5: 'Ob Sie Verantwortlicher oder Auftragsverarbeiter sind, bestimmt Ihre DSGVO-Pflichten grundlegend. KI-Nutzung löst zusätzliche AI-Act-Pflichten aus.',
  6: 'Ihre Verarbeitungstätigkeiten bilden die Grundlage für das Verarbeitungsverzeichnis (Art. 30 DSGVO). KI-Systeme werden für die AI-Act-Analyse erfasst — die Risikoeinstufung übernimmt unser Tool.',
  7: 'Regulierungsrahmen und Prüfzyklen definieren, welche Compliance-Module für Sie aktiviert werden und in welchem Rhythmus Audits stattfinden.',
  8: 'Als Maschinenbauer gelten zusätzliche Anforderungen: CE-Kennzeichnung, Maschinenverordnung, Produktsicherheit und ggf. Hochrisiko-KI im Sinne des AI Act.',
}

function StepBusinessModel({
  data,
  onChange,
}: {
  data: Partial<CompanyProfile>
  onChange: (updates: Partial<CompanyProfile>) => void
}) {
  const toggleOffering = (offering: OfferingType) => {
    const current = data.offerings || []
    if (current.includes(offering)) {
      // Remove offering and its URL
      const urls = { ...(data.offeringUrls || {}) }
      delete urls[offering]
      onChange({ offerings: current.filter(o => o !== offering), offeringUrls: urls })
    } else {
      onChange({ offerings: [...current, offering] })
    }
  }

  const updateOfferingUrl = (offering: string, url: string) => {
    onChange({ offeringUrls: { ...(data.offeringUrls || {}), [offering]: url } })
  }

  // Offerings that are selected and have URL config
  const selectedWithUrls = (data.offerings || []).filter(o => o in OFFERING_URL_CONFIG)

  return (
    <div className="space-y-8">
      <div>
        <label className="block text-sm font-medium text-gray-700 mb-4">
          Geschäftsmodell <span className="text-red-500">*</span>
        </label>
        <div className="grid grid-cols-4 gap-4">
          {Object.entries(BUSINESS_MODEL_LABELS).map(([value, { short }]) => (
            <button
              key={value}
              type="button"
              onClick={() => onChange({ businessModel: value as BusinessModel })}
              className={`p-4 rounded-xl border-2 text-center transition-all ${
                data.businessModel === value
                  ? 'border-purple-500 bg-purple-50 text-purple-700'
                  : 'border-gray-200 hover:border-purple-300'
              }`}
            >
              <div className="font-semibold">{short}</div>
            </button>
          ))}
        </div>
        {data.businessModel && (
          <p className="text-sm text-gray-500 mt-2">
            {BUSINESS_MODEL_LABELS[data.businessModel].description}
          </p>
        )}
      </div>

      <div>
        <label className="block text-sm font-medium text-gray-700 mb-4">
          Was bieten Sie an? <span className="text-gray-400">(Mehrfachauswahl möglich)</span>
        </label>
        <div className="grid grid-cols-2 gap-3">
          {Object.entries(OFFERING_TYPE_LABELS).map(([value, { label, description }]) => (
            <button
              key={value}
              type="button"
              onClick={() => toggleOffering(value as OfferingType)}
              className={`p-4 rounded-xl border-2 text-left transition-all ${
                (data.offerings || []).includes(value as OfferingType)
                  ? 'border-purple-500 bg-purple-50'
                  : 'border-gray-200 hover:border-purple-300'
              }`}
            >
              <div className="font-medium text-gray-900">{label}</div>
              <div className="text-sm text-gray-500">{description}</div>
            </button>
          ))}
        </div>
      </div>

      {/* URL fields for selected offerings */}
      {selectedWithUrls.length > 0 && (
        <div className="space-y-4">
          <label className="block text-sm font-medium text-gray-700">
            Zugehörige URLs
          </label>
          {selectedWithUrls.map(offering => {
            const config = OFFERING_URL_CONFIG[offering]!
            return (
              <div key={offering}>
                <label className="block text-sm text-gray-600 mb-1">{config.label}</label>
                <input
                  type="url"
                  value={(data.offeringUrls || {})[offering] || ''}
                  onChange={e => updateOfferingUrl(offering, e.target.value)}
                  placeholder={config.placeholder}
                  className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
                />
                <p className="text-xs text-gray-400 mt-1">{config.hint}</p>
              </div>
            )
          })}
        </div>
      )}
    </div>
  )
}

function StepCompanySize({
  data,
  onChange,
}: {
  data: Partial<CompanyProfile>
  onChange: (updates: Partial<CompanyProfile>) => void
}) {
  return (
    <div className="space-y-8">
      <div>
        <label className="block text-sm font-medium text-gray-700 mb-4">
          Unternehmensgröße <span className="text-red-500">*</span>
        </label>
        <div className="space-y-3">
          {Object.entries(COMPANY_SIZE_LABELS).map(([value, label]) => (
            <button
              key={value}
              type="button"
              onClick={() => onChange({ companySize: value as CompanySize })}
              className={`w-full p-4 rounded-xl border-2 text-left transition-all ${
                data.companySize === value
                  ? 'border-purple-500 bg-purple-50'
                  : 'border-gray-200 hover:border-purple-300'
              }`}
            >
              <div className="font-medium text-gray-900">{label}</div>
            </button>
          ))}
        </div>
      </div>

      <div>
        <label className="block text-sm font-medium text-gray-700 mb-2">Jahresumsatz</label>
        <select
          value={data.annualRevenue || ''}
          onChange={e => onChange({ annualRevenue: e.target.value })}
          className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
        >
          <option value="">Bitte wählen...</option>
          <option value="< 2 Mio">&lt; 2 Mio. Euro</option>
          <option value="2-10 Mio">2-10 Mio. Euro</option>
          <option value="10-50 Mio">10-50 Mio. Euro</option>
          <option value="> 50 Mio">&gt; 50 Mio. Euro</option>
        </select>
        {(data.companySize === 'medium' || data.companySize === 'large' || data.companySize === 'enterprise') && (
          <p className="text-xs text-amber-600 mt-2">
            Geben Sie den konsolidierten Konzernumsatz an, wenn der Compliance-Check für Mutter- und Tochtergesellschaften gelten soll.
            Für eine einzelne Einheit eines Konzerns geben Sie nur deren Umsatz an.
          </p>
        )}
      </div>
    </div>
  )
}

function StepLocations({
  data,
  onChange,
}: {
  data: Partial<CompanyProfile>
  onChange: (updates: Partial<CompanyProfile>) => void
}) {
  const toggleMarket = (market: TargetMarket) => {
    const current = data.targetMarkets || []
    if (current.includes(market)) {
      onChange({ targetMarkets: current.filter(m => m !== market) })
    } else {
      onChange({ targetMarkets: [...current, market] })
    }
  }

  const STATES_BY_COUNTRY: Record<string, { label: string; options: string[] }> = {
    DE: {
      label: 'Bundesland',
      options: [
        'Baden-Württemberg', 'Bayern', 'Berlin', 'Brandenburg', 'Bremen',
        'Hamburg', 'Hessen', 'Mecklenburg-Vorpommern', 'Niedersachsen',
        'Nordrhein-Westfalen', 'Rheinland-Pfalz', 'Saarland', 'Sachsen',
        'Sachsen-Anhalt', 'Schleswig-Holstein', 'Thüringen',
      ],
    },
    AT: {
      label: 'Bundesland',
      options: [
        'Burgenland', 'Kärnten', 'Niederösterreich', 'Oberösterreich',
        'Salzburg', 'Steiermark', 'Tirol', 'Vorarlberg', 'Wien',
      ],
    },
    CH: {
      label: 'Kanton',
      options: [
        'Aargau', 'Appenzell Ausserrhoden', 'Appenzell Innerrhoden',
        'Basel-Landschaft', 'Basel-Stadt', 'Bern', 'Freiburg', 'Genf',
        'Glarus', 'Graubünden', 'Jura', 'Luzern', 'Neuenburg', 'Nidwalden',
        'Obwalden', 'Schaffhausen', 'Schwyz', 'Solothurn', 'St. Gallen',
        'Tessin', 'Thurgau', 'Uri', 'Waadt', 'Wallis', 'Zug', 'Zürich',
      ],
    },
  }

  const countryStates = data.headquartersCountry ? STATES_BY_COUNTRY[data.headquartersCountry] : null
  const stateLabel = countryStates?.label || 'Region / Provinz'

  return (
    <div className="space-y-8">
      {/* Country */}
      <div>
        <label className="block text-sm font-medium text-gray-700 mb-2">
          Land des Hauptsitzes <span className="text-red-500">*</span>
        </label>
        <select
          value={data.headquartersCountry || ''}
          onChange={e => onChange({ headquartersCountry: e.target.value, headquartersCountryOther: '' })}
          className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
        >
          <option value="">Bitte wählen...</option>
          <option value="DE">Deutschland</option>
          <option value="AT">Österreich</option>
          <option value="CH">Schweiz</option>
          <option value="LI">Liechtenstein</option>
          <option value="LU">Luxemburg</option>
          <option value="NL">Niederlande</option>
          <option value="FR">Frankreich</option>
          <option value="IT">Italien</option>
          <option value="other">Anderes Land</option>
        </select>
      </div>

      {/* Other country free text */}
      {data.headquartersCountry === 'other' && (
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">Land (Freitext)</label>
          <input
            type="text"
            value={data.headquartersCountryOther || ''}
            onChange={e => onChange({ headquartersCountryOther: e.target.value })}
            placeholder="z.B. Vereinigtes Königreich"
            className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
          />
        </div>
      )}

      {/* Street + House Number */}
      <div>
        <label className="block text-sm font-medium text-gray-700 mb-2">Straße und Hausnummer</label>
        <input
          type="text"
          value={data.headquartersStreet || ''}
          onChange={e => onChange({ headquartersStreet: e.target.value })}
          placeholder="Musterstraße 42"
          className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
        />
      </div>

      {/* PLZ + City */}
      <div className="grid grid-cols-3 gap-4">
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">PLZ</label>
          <input
            type="text"
            value={data.headquartersZip || ''}
            onChange={e => onChange({ headquartersZip: e.target.value })}
            placeholder="10115"
            className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
          />
        </div>
        <div className="col-span-2">
          <label className="block text-sm font-medium text-gray-700 mb-2">Stadt</label>
          <input
            type="text"
            value={data.headquartersCity || ''}
            onChange={e => onChange({ headquartersCity: e.target.value })}
            placeholder="Berlin"
            className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
          />
        </div>
      </div>

      {/* State / Bundesland / Kanton */}
      <div>
        <label className="block text-sm font-medium text-gray-700 mb-2">{stateLabel}</label>
        {countryStates ? (
          <select
            value={data.headquartersState || ''}
            onChange={e => onChange({ headquartersState: e.target.value })}
            className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
          >
            <option value="">Bitte wählen...</option>
            {countryStates.options.map(s => (
              <option key={s} value={s}>{s}</option>
            ))}
          </select>
        ) : (
          <input
            type="text"
            value={data.headquartersState || ''}
            onChange={e => onChange({ headquartersState: e.target.value })}
            placeholder="Region / Provinz"
            className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
          />
        )}
      </div>

      <div>
        <label className="block text-sm font-medium text-gray-700 mb-4">
          Zielmärkte <span className="text-red-500">*</span>
          <span className="text-gray-400 font-normal ml-2">Wo verkaufen/operieren Sie?</span>
        </label>
        <div className="space-y-3">
          {Object.entries(TARGET_MARKET_LABELS).map(([value, { label, description }]) => (
            <button
              key={value}
              type="button"
              onClick={() => toggleMarket(value as TargetMarket)}
              className={`w-full p-4 rounded-xl border-2 text-left transition-all ${
                (data.targetMarkets || []).includes(value as TargetMarket)
                  ? 'border-purple-500 bg-purple-50'
                  : 'border-gray-200 hover:border-purple-300'
              }`}
            >
              <div className="font-medium text-gray-900">{label}</div>
              <div className="text-sm text-gray-500">{description}</div>
            </button>
          ))}
        </div>
      </div>
    </div>
  )
}

function StepDataProtection({
  data,
  onChange,
}: {
  data: Partial<CompanyProfile>
  onChange: (updates: Partial<CompanyProfile>) => void
}) {
  return (
    <div className="space-y-8">
      <div>
        <label className="block text-sm font-medium text-gray-700 mb-4">
          Datenschutz-Rolle nach DSGVO
        </label>
        <div className="space-y-3">
          <label className="flex items-start gap-4 p-4 rounded-xl border-2 border-gray-200 hover:border-purple-300 cursor-pointer">
            <input
              type="checkbox"
              checked={data.isDataController ?? true}
              onChange={e => onChange({ isDataController: e.target.checked })}
              className="mt-1 w-5 h-5 text-purple-600 rounded focus:ring-purple-500"
            />
            <div>
              <div className="font-medium text-gray-900">Verantwortlicher (Art. 4 Nr. 7 DSGVO)</div>
              <div className="text-sm text-gray-500">
                Wir entscheiden selbst über Zwecke und Mittel der Datenverarbeitung
              </div>
            </div>
          </label>

          <label className="flex items-start gap-4 p-4 rounded-xl border-2 border-gray-200 hover:border-purple-300 cursor-pointer">
            <input
              type="checkbox"
              checked={data.isDataProcessor ?? false}
              onChange={e => onChange({ isDataProcessor: e.target.checked })}
              className="mt-1 w-5 h-5 text-purple-600 rounded focus:ring-purple-500"
            />
            <div>
              <div className="font-medium text-gray-900">Auftragsverarbeiter (Art. 4 Nr. 8 DSGVO)</div>
              <div className="text-sm text-gray-500">
                Wir verarbeiten personenbezogene Daten im Auftrag anderer Unternehmen
              </div>
            </div>
          </label>
        </div>
      </div>

      <div>
        <label className="flex items-start gap-4 p-4 rounded-xl border-2 border-gray-200 hover:border-purple-300 cursor-pointer">
          <input
            type="checkbox"
            checked={data.usesAI ?? false}
            onChange={e => onChange({ usesAI: e.target.checked })}
            className="mt-1 w-5 h-5 text-purple-600 rounded focus:ring-purple-500"
          />
          <div>
            <div className="font-medium text-gray-900">Wir setzen KI/ML-Systeme ein</div>
            <div className="text-sm text-gray-500">
              Chatbots, Empfehlungssysteme, automatisierte Entscheidungen, etc.
            </div>
          </div>
        </label>
      </div>

      <div className="grid grid-cols-2 gap-6">
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            Datenschutzbeauftragter (Name)
          </label>
          <input
            type="text"
            value={data.dpoName || ''}
            onChange={e => onChange({ dpoName: e.target.value || null })}
            placeholder="Optional"
            className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
          />
        </div>
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">DSB E-Mail</label>
          <input
            type="email"
            value={data.dpoEmail || ''}
            onChange={e => onChange({ dpoEmail: e.target.value || null })}
            placeholder="dsb@firma.de"
            className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
          />
        </div>
      </div>
    </div>
  )
}

// =============================================================================
// STEP 6: VERARBEITUNGSTAETIGKEITEN & KI
// =============================================================================

// DSGVO-Standard Datenkategorien
const ALL_DATA_CATEGORIES = [
  { id: 'stammdaten', label: 'Stammdaten', desc: 'Name, Geburtsdatum, Geschlecht' },
  { id: 'kontaktdaten', label: 'Kontaktdaten', desc: 'E-Mail, Telefon, Adresse' },
  { id: 'vertragsdaten', label: 'Vertragsdaten', desc: 'Vertragsnummer, Laufzeit, Konditionen' },
  { id: 'zahlungsdaten', label: 'Zahlungs-/Bankdaten', desc: 'IBAN, Kreditkarte, Rechnungen' },
  { id: 'beschaeftigtendaten', label: 'Beschäftigtendaten', desc: 'Gehalt, Arbeitszeiten, Urlaub' },
  { id: 'kommunikation', label: 'Kommunikationsdaten', desc: 'E-Mail-Inhalte, Chat-Verläufe' },
  { id: 'nutzungsdaten', label: 'Nutzungs-/Logdaten', desc: 'IP-Adressen, Login-Zeiten, Klicks' },
  { id: 'standortdaten', label: 'Standortdaten', desc: 'GPS, Check-in, Lieferadressen' },
  { id: 'bilddaten', label: 'Bild-/Videodaten', desc: 'Fotos, Videoaufnahmen, Profilbilder' },
  { id: 'bewerberdaten', label: 'Bewerberdaten', desc: 'Lebenslauf, Zeugnisse, Anschreiben' },
] as const

const ALL_SPECIAL_CATEGORIES = [
  { id: 'gesundheit', label: 'Gesundheitsdaten', desc: 'Krankheitstage, Atteste, Diagnosen' },
  { id: 'biometrie', label: 'Biometrische Daten', desc: 'Fingerabdruck, Gesichtserkennung' },
  { id: 'religion', label: 'Religiöse Überzeugungen', desc: 'Konfession, Feiertage' },
  { id: 'gewerkschaft', label: 'Gewerkschaftszugehörigkeit', desc: 'Mitgliedschaft' },
  { id: 'genetik', label: 'Genetische Daten', desc: 'DNA, Erbkrankheiten' },
] as const

// Rechtsgrundlagen nach DSGVO Art. 6
const LEGAL_BASES = [
  { id: 'consent', label: 'Einwilligung (Art. 6 Abs. 1a)' },
  { id: 'contract', label: 'Vertragserfüllung (Art. 6 Abs. 1b)' },
  { id: 'legal', label: 'Rechtliche Verpflichtung (Art. 6 Abs. 1c)' },
  { id: 'interest', label: 'Berechtigtes Interesse (Art. 6 Abs. 1f)' },
] as const

// Verarbeitungstätigkeiten mit aktivitätsspezifischen Datenkategorien
interface ActivityTemplate {
  id: string
  name: string
  purpose: string
  primary_categories: string[]    // Sichtbar + vorausgewählt
  art9_relevant: string[]         // Art. 9 Kategorien die plausibel relevant sind
  default_legal_basis: string
}

interface ActivityDepartment {
  id: string
  name: string
  icon: string
  activities: ActivityTemplate[]
}

// ── Universelle Abteilungen (immer sichtbar) ──

const UNIVERSAL_DEPARTMENTS: ActivityDepartment[] = [
  {
    id: 'personal', name: 'Personal / HR', icon: '👥',
    activities: [
      { id: 'personalverwaltung', name: 'Personalverwaltung', purpose: 'Verwaltung von Beschäftigtendaten für das Arbeitsverhältnis', primary_categories: ['stammdaten', 'kontaktdaten', 'beschaeftigtendaten', 'zahlungsdaten'], art9_relevant: ['gesundheit', 'religion', 'gewerkschaft'], default_legal_basis: 'contract' },
      { id: 'lohnbuchhaltung', name: 'Lohn- und Gehaltsabrechnung', purpose: 'Berechnung und Auszahlung von Löhnen und Gehältern', primary_categories: ['beschaeftigtendaten', 'zahlungsdaten', 'stammdaten'], art9_relevant: ['gesundheit', 'religion'], default_legal_basis: 'legal' },
      { id: 'bewerbermanagement', name: 'Bewerbermanagement', purpose: 'Entgegennahme, Prüfung und Bearbeitung von Bewerbungen', primary_categories: ['bewerberdaten', 'stammdaten', 'kontaktdaten', 'kommunikation'], art9_relevant: ['gesundheit'], default_legal_basis: 'consent' },
      { id: 'arbeitszeiterfassung', name: 'Arbeitszeiterfassung', purpose: 'Erfassung und Dokumentation der Arbeitszeiten', primary_categories: ['beschaeftigtendaten'], art9_relevant: [], default_legal_basis: 'legal' },
      { id: 'weiterbildung', name: 'Fort- und Weiterbildung', purpose: 'Verwaltung von Schulungen und Weiterbildungsmaßnahmen', primary_categories: ['beschaeftigtendaten', 'stammdaten'], art9_relevant: [], default_legal_basis: 'contract' },
    ],
  },
  {
    id: 'finanzen', name: 'Finanzen / Buchhaltung', icon: '💰',
    activities: [
      { id: 'finanzbuchhaltung', name: 'Finanzbuchhaltung', purpose: 'Buchführung, Rechnungsstellung, steuerliche Dokumentation', primary_categories: ['stammdaten', 'zahlungsdaten', 'vertragsdaten', 'kontaktdaten'], art9_relevant: [], default_legal_basis: 'legal' },
      { id: 'zahlungsverkehr', name: 'Zahlungsverkehr', purpose: 'Abwicklung von ein- und ausgehenden Zahlungen', primary_categories: ['zahlungsdaten', 'stammdaten', 'kontaktdaten'], art9_relevant: [], default_legal_basis: 'contract' },
      { id: 'mahnwesen', name: 'Mahnwesen / Inkasso', purpose: 'Überwachung offener Forderungen und Mahnverfahren', primary_categories: ['stammdaten', 'kontaktdaten', 'zahlungsdaten', 'vertragsdaten'], art9_relevant: [], default_legal_basis: 'interest' },
      { id: 'reisekostenabrechnung', name: 'Reisekostenabrechnung', purpose: 'Abrechnung und Erstattung von Dienstreisekosten', primary_categories: ['beschaeftigtendaten', 'zahlungsdaten', 'standortdaten'], art9_relevant: [], default_legal_basis: 'contract' },
    ],
  },
  {
    id: 'vertrieb', name: 'Vertrieb / Sales', icon: '📈',
    activities: [
      { id: 'crm', name: 'CRM / Kundenverwaltung', purpose: 'Verwaltung von Kundenbeziehungen, Kontakthistorie, Verkaufschancen', primary_categories: ['stammdaten', 'kontaktdaten', 'kommunikation', 'vertragsdaten'], art9_relevant: [], default_legal_basis: 'contract' },
      { id: 'angebotserstellung', name: 'Angebotserstellung', purpose: 'Erstellung und Nachverfolgung von Angeboten', primary_categories: ['stammdaten', 'kontaktdaten', 'vertragsdaten'], art9_relevant: [], default_legal_basis: 'contract' },
      { id: 'vertragsmanagement', name: 'Vertragsmanagement', purpose: 'Verwaltung, Archivierung und Nachverfolgung von Verträgen', primary_categories: ['vertragsdaten', 'stammdaten', 'kontaktdaten'], art9_relevant: [], default_legal_basis: 'contract' },
    ],
  },
  {
    id: 'marketing', name: 'Marketing', icon: '📣',
    activities: [
      { id: 'newsletter', name: 'Newsletter / E-Mail-Marketing', purpose: 'Versand von Newslettern und E-Mail-Marketing an Abonnenten', primary_categories: ['kontaktdaten', 'nutzungsdaten', 'stammdaten'], art9_relevant: [], default_legal_basis: 'consent' },
      { id: 'website_tracking', name: 'Website-Tracking / Analytics', purpose: 'Analyse des Nutzerverhaltens auf der Website mittels Tracking-Tools', primary_categories: ['nutzungsdaten', 'standortdaten'], art9_relevant: [], default_legal_basis: 'consent' },
      { id: 'social_media', name: 'Social-Media-Marketing', purpose: 'Betrieb von Unternehmensprofilen und Werbekampagnen', primary_categories: ['kontaktdaten', 'nutzungsdaten', 'kommunikation'], art9_relevant: [], default_legal_basis: 'consent' },
      { id: 'consent_management', name: 'Consent-Management (Cookies)', purpose: 'Verwaltung der Einwilligungen für Cookies und Tracking', primary_categories: ['nutzungsdaten'], art9_relevant: [], default_legal_basis: 'consent' },
    ],
  },
  {
    id: 'it', name: 'IT / Administration', icon: '🖥️',
    activities: [
      { id: 'zugangsverwaltung', name: 'Zugangsverwaltung (IAM)', purpose: 'Verwaltung von Benutzerkonten, Passwörtern und Zugriffsrechten', primary_categories: ['beschaeftigtendaten', 'stammdaten', 'nutzungsdaten'], art9_relevant: ['biometrie'], default_legal_basis: 'contract' },
      { id: 'email_kommunikation', name: 'E-Mail-Kommunikation', purpose: 'Geschäftliche E-Mail-Korrespondenz', primary_categories: ['kontaktdaten', 'kommunikation', 'stammdaten'], art9_relevant: [], default_legal_basis: 'interest' },
      { id: 'datensicherung', name: 'Datensicherung / Backup', purpose: 'Sicherung von Unternehmensdaten zum Schutz vor Datenverlust', primary_categories: ['nutzungsdaten', 'beschaeftigtendaten'], art9_relevant: [], default_legal_basis: 'interest' },
      { id: 'website_betrieb', name: 'Website-Betrieb', purpose: 'Bereitstellung der Unternehmenswebsite und Kontaktformulare', primary_categories: ['nutzungsdaten', 'kontaktdaten'], art9_relevant: [], default_legal_basis: 'interest' },
      { id: 'it_sicherheit', name: 'IT-Sicherheit / Logging', purpose: 'Überwachung der IT-Sicherheit, Log-Analyse, Vorfallbehandlung', primary_categories: ['nutzungsdaten', 'beschaeftigtendaten'], art9_relevant: [], default_legal_basis: 'interest' },
    ],
  },
  {
    id: 'recht', name: 'Recht / Compliance', icon: '⚖️',
    activities: [
      { id: 'datenschutzanfragen', name: 'Betroffenenrechte (DSGVO)', purpose: 'Bearbeitung von Auskunfts-, Lösch- und Berichtigungsanfragen', primary_categories: ['stammdaten', 'kontaktdaten', 'kommunikation'], art9_relevant: [], default_legal_basis: 'legal' },
      { id: 'auftragsverarbeitung', name: 'Auftragsverarbeitung (AVV)', purpose: 'Dokumentation und Verwaltung von Auftragsverarbeitungsverhältnissen', primary_categories: ['stammdaten', 'kontaktdaten', 'vertragsdaten'], art9_relevant: [], default_legal_basis: 'legal' },
      { id: 'whistleblowing', name: 'Hinweisgebersystem', purpose: 'Entgegennahme und Bearbeitung von Meldungen nach HinSchG', primary_categories: ['stammdaten', 'kontaktdaten', 'kommunikation'], art9_relevant: [], default_legal_basis: 'legal' },
    ],
  },
]

// ── Abteilungen die je nach Kontext relevant sind ──

const OPTIONAL_DEPARTMENTS: ActivityDepartment[] = [
  {
    id: 'einkauf', name: 'Einkauf / Beschaffung', icon: '🛒',
    activities: [
      { id: 'lieferantenverwaltung', name: 'Lieferantenverwaltung', purpose: 'Erfassung und Pflege von Lieferantenstammdaten', primary_categories: ['stammdaten', 'kontaktdaten', 'vertragsdaten', 'zahlungsdaten'], art9_relevant: [], default_legal_basis: 'contract' },
      { id: 'bestellwesen', name: 'Bestellwesen', purpose: 'Abwicklung von Bestellungen bei Lieferanten', primary_categories: ['stammdaten', 'vertragsdaten', 'zahlungsdaten'], art9_relevant: [], default_legal_basis: 'contract' },
      { id: 'lieferantenbewertung', name: 'Lieferantenbewertung', purpose: 'Bewertung und Qualifizierung von Lieferanten', primary_categories: ['stammdaten', 'kontaktdaten'], art9_relevant: [], default_legal_basis: 'interest' },
    ],
  },
  {
    id: 'produktion', name: 'Produktion / Fertigung', icon: '🏭',
    activities: [
      { id: 'produktionsplanung', name: 'Produktionsplanung', purpose: 'Planung und Steuerung von Produktionsprozessen inkl. Personalzuordnung', primary_categories: ['beschaeftigtendaten', 'stammdaten'], art9_relevant: [], default_legal_basis: 'contract' },
      { id: 'qualitaetskontrolle', name: 'Qualitätskontrolle', purpose: 'Prüfung und Dokumentation der Produktqualität', primary_categories: ['beschaeftigtendaten', 'stammdaten'], art9_relevant: [], default_legal_basis: 'contract' },
      { id: 'arbeitssicherheit', name: 'Arbeitssicherheit / Arbeitsschutz', purpose: 'Dokumentation von Arbeitsschutzmaßnahmen, Unfällen, Gefährdungsbeurteilungen', primary_categories: ['beschaeftigtendaten'], art9_relevant: ['gesundheit'], default_legal_basis: 'legal' },
      { id: 'schichtplanung', name: 'Schichtplanung', purpose: 'Erstellung und Verwaltung von Schichtplänen', primary_categories: ['beschaeftigtendaten'], art9_relevant: [], default_legal_basis: 'contract' },
    ],
  },
  {
    id: 'logistik', name: 'Logistik / Versand', icon: '🚚',
    activities: [
      { id: 'versandabwicklung', name: 'Versandabwicklung', purpose: 'Verarbeitung von Empfänger- und Versanddaten für den Warenversand', primary_categories: ['stammdaten', 'kontaktdaten', 'standortdaten'], art9_relevant: [], default_legal_basis: 'contract' },
      { id: 'lieferverfolgung', name: 'Lieferverfolgung / Sendungstracking', purpose: 'Nachverfolgung von Sendungen und Zustellung', primary_categories: ['stammdaten', 'kontaktdaten', 'standortdaten'], art9_relevant: [], default_legal_basis: 'contract' },
      { id: 'lagerverwaltung', name: 'Lagerverwaltung', purpose: 'Verwaltung von Lagerbeständen und Warenbewegungen', primary_categories: ['stammdaten', 'beschaeftigtendaten'], art9_relevant: [], default_legal_basis: 'contract' },
      { id: 'retouren', name: 'Retourenmanagement', purpose: 'Bearbeitung von Warenrücksendungen', primary_categories: ['stammdaten', 'kontaktdaten', 'vertragsdaten'], art9_relevant: [], default_legal_basis: 'contract' },
    ],
  },
  {
    id: 'kundenservice', name: 'Kundenservice / Support', icon: '🎧',
    activities: [
      { id: 'ticketsystem', name: 'Ticketsystem / Support', purpose: 'Erfassung und Bearbeitung von Kundenanfragen und Supportfällen', primary_categories: ['stammdaten', 'kontaktdaten', 'kommunikation'], art9_relevant: [], default_legal_basis: 'contract' },
      { id: 'beschwerdemanagement', name: 'Beschwerdemanagement', purpose: 'Bearbeitung und Dokumentation von Kundenbeschwerden', primary_categories: ['stammdaten', 'kontaktdaten', 'kommunikation'], art9_relevant: [], default_legal_basis: 'contract' },
    ],
  },
  {
    id: 'facility', name: 'Facility Management', icon: '🏢',
    activities: [
      { id: 'zutrittskontrolle', name: 'Zutrittskontrolle', purpose: 'Kontrolle und Protokollierung des Zutritts zu Gebäuden und Räumen', primary_categories: ['beschaeftigtendaten', 'stammdaten', 'bilddaten'], art9_relevant: ['biometrie'], default_legal_basis: 'interest' },
      { id: 'videoueberwachung', name: 'Videoüberwachung', purpose: 'Überwachung von Gebäuden und Geländen mittels Videokameras', primary_categories: ['bilddaten', 'beschaeftigtendaten'], art9_relevant: ['biometrie'], default_legal_basis: 'interest' },
      { id: 'besuchermanagement', name: 'Besuchermanagement', purpose: 'Erfassung und Verwaltung von Besucherdaten', primary_categories: ['stammdaten', 'kontaktdaten'], art9_relevant: [], default_legal_basis: 'interest' },
    ],
  },
]

// ── Branchenspezifische Abteilungen ──

const INDUSTRY_DEPARTMENTS: Record<string, ActivityDepartment[]> = {
  'E-Commerce / Handel': [{
    id: 'ecommerce', name: 'E-Commerce / Webshop', icon: '🛍️',
    activities: [
      { id: 'bestellabwicklung', name: 'Bestellabwicklung (Webshop)', purpose: 'Verarbeitung von Kundenbestellungen im Online-Shop', primary_categories: ['stammdaten', 'kontaktdaten', 'zahlungsdaten', 'vertragsdaten'], art9_relevant: [], default_legal_basis: 'contract' },
      { id: 'kundenkonto', name: 'Kundenkonto-Verwaltung', purpose: 'Verwaltung registrierter Kundenkonten im Online-Shop', primary_categories: ['stammdaten', 'kontaktdaten', 'nutzungsdaten', 'zahlungsdaten'], art9_relevant: [], default_legal_basis: 'contract' },
      { id: 'webshop_analyse', name: 'Webshop-Analyse / Conversion', purpose: 'Analyse des Kaufverhaltens und Conversion-Rates', primary_categories: ['nutzungsdaten', 'standortdaten'], art9_relevant: [], default_legal_basis: 'consent' },
      { id: 'produktbewertungen', name: 'Produktbewertungen / Reviews', purpose: 'Verwaltung von Kundenrezensionen und Produktbewertungen', primary_categories: ['stammdaten', 'kontaktdaten', 'kommunikation'], art9_relevant: [], default_legal_basis: 'consent' },
    ],
  }],
  'Gesundheitswesen': [{
    id: 'gesundheit_dept', name: 'Medizin / Patientenversorgung', icon: '🏥',
    activities: [
      { id: 'patientenverwaltung', name: 'Patientenverwaltung', purpose: 'Verwaltung von Patientenstammdaten und Krankengeschichte', primary_categories: ['stammdaten', 'kontaktdaten', 'zahlungsdaten'], art9_relevant: ['gesundheit', 'genetik'], default_legal_basis: 'contract' },
      { id: 'terminplanung_med', name: 'Terminplanung (Patienten)', purpose: 'Vergabe und Verwaltung von Patiententerminen', primary_categories: ['stammdaten', 'kontaktdaten'], art9_relevant: ['gesundheit'], default_legal_basis: 'contract' },
      { id: 'kv_abrechnung', name: 'KV-Abrechnung', purpose: 'Abrechnung von Leistungen gegenüber Kassenärztlichen Vereinigungen', primary_categories: ['stammdaten', 'zahlungsdaten'], art9_relevant: ['gesundheit'], default_legal_basis: 'legal' },
      { id: 'med_dokumentation', name: 'Medizinische Dokumentation', purpose: 'Dokumentation von Diagnosen, Therapien und Behandlungsverläufen', primary_categories: ['stammdaten'], art9_relevant: ['gesundheit', 'genetik'], default_legal_basis: 'legal' },
    ],
  }],
  'Finanzdienstleistungen': [{
    id: 'finanz_dept', name: 'Regulatorik / Finanzaufsicht', icon: '🏦',
    activities: [
      { id: 'kyc', name: 'Know Your Customer (KYC)', purpose: 'Identifizierung und Verifizierung von Kunden gemäß GwG', primary_categories: ['stammdaten', 'kontaktdaten', 'bilddaten'], art9_relevant: [], default_legal_basis: 'legal' },
      { id: 'kontoverwaltung', name: 'Kontoverwaltung', purpose: 'Verwaltung von Kundenkonten und Kontobewegungen', primary_categories: ['stammdaten', 'kontaktdaten', 'zahlungsdaten'], art9_relevant: [], default_legal_basis: 'contract' },
      { id: 'geldwaeschepraevention', name: 'Geldwäscheprävention (AML)', purpose: 'Überwachung verdächtiger Transaktionen nach GwG', primary_categories: ['stammdaten', 'zahlungsdaten'], art9_relevant: [], default_legal_basis: 'legal' },
    ],
  }],
  'Bildung': [{
    id: 'bildung_dept', name: 'Bildung / Lehre', icon: '🎓',
    activities: [
      { id: 'schuelerverwaltung', name: 'Schüler-/Teilnehmerverwaltung', purpose: 'Verwaltung von Lernenden, Noten, Anwesenheit', primary_categories: ['stammdaten', 'kontaktdaten', 'nutzungsdaten'], art9_relevant: ['gesundheit', 'religion'], default_legal_basis: 'contract' },
      { id: 'lernplattform', name: 'Lernplattform / LMS', purpose: 'Bereitstellung und Nutzung digitaler Lernplattformen', primary_categories: ['stammdaten', 'nutzungsdaten', 'kommunikation'], art9_relevant: [], default_legal_basis: 'contract' },
      { id: 'pruefungsverwaltung', name: 'Prüfungsverwaltung', purpose: 'Verwaltung und Dokumentation von Prüfungen und Noten', primary_categories: ['stammdaten'], art9_relevant: [], default_legal_basis: 'contract' },
    ],
  }],
  'Immobilien': [{
    id: 'immobilien_dept', name: 'Immobilienverwaltung', icon: '🏠',
    activities: [
      { id: 'mieterverwaltung', name: 'Mieterverwaltung', purpose: 'Verwaltung von Mietverträgen und Mieterdaten', primary_categories: ['stammdaten', 'kontaktdaten', 'vertragsdaten', 'zahlungsdaten'], art9_relevant: [], default_legal_basis: 'contract' },
      { id: 'nebenkostenabrechnung', name: 'Nebenkostenabrechnung', purpose: 'Erstellung und Versand von Nebenkostenabrechnungen', primary_categories: ['stammdaten', 'zahlungsdaten'], art9_relevant: [], default_legal_basis: 'contract' },
    ],
  }],
}

// Compute which departments to show based on company context
function getRelevantDepartments(industry: string, businessModel: string | undefined, companySize: string | undefined): ActivityDepartment[] {
  const departments: ActivityDepartment[] = [...UNIVERSAL_DEPARTMENTS]

  // Always show optional departments — user can choose
  departments.push(...OPTIONAL_DEPARTMENTS)

  // Add industry-specific departments
  const industryDepts = INDUSTRY_DEPARTMENTS[industry]
  if (industryDepts) {
    departments.push(...industryDepts)
  }

  return departments
}

interface ProcessingActivity {
  id: string
  name: string
  purpose: string
  data_categories: string[]
  legal_basis: string
  department?: string
  custom?: boolean
}

interface AISystem {
  name: string
  vendor: string
  purpose: string
  processes_personal_data: boolean
}

// Helper: find template for an activity ID across all departments
function findTemplate(departments: ActivityDepartment[], activityId: string): ActivityTemplate | null {
  for (const dept of departments) {
    const t = dept.activities.find(a => a.id === activityId)
    if (t) return t
  }
  return null
}

function StepProcessingAndAI({
  data,
  onChange,
}: {
  data: Partial<CompanyProfile> & { processingSystems?: ProcessingActivity[]; aiSystems?: AISystem[] }
  onChange: (updates: Record<string, unknown>) => void
}) {
  const activities: ProcessingActivity[] = (data as any).processingSystems || []
  const aiSystems: AISystem[] = (data as any).aiSystems || []
  const industry = data.industry || ''
  const [expandedActivity, setExpandedActivity] = useState<string | null>(null)
  const [collapsedDepts, setCollapsedDepts] = useState<Set<string>>(new Set())
  const [showExtraCategories, setShowExtraCategories] = useState<Set<string>>(new Set())

  const departments = getRelevantDepartments(industry, data.businessModel, data.companySize)
  const activeIds = new Set(activities.map(a => a.id))

  const toggleActivity = (template: ActivityTemplate, deptId: string) => {
    if (activeIds.has(template.id)) {
      onChange({ processingSystems: activities.filter(a => a.id !== template.id) })
    } else {
      onChange({
        processingSystems: [...activities, {
          id: template.id,
          name: template.name,
          purpose: template.purpose,
          data_categories: [...template.primary_categories],
          legal_basis: template.default_legal_basis,
          department: deptId,
        }],
      })
    }
  }

  const updateActivity = (id: string, updates: Partial<ProcessingActivity>) => {
    onChange({
      processingSystems: activities.map(a => a.id === id ? { ...a, ...updates } : a),
    })
  }

  const toggleDataCategory = (activityId: string, categoryId: string) => {
    const activity = activities.find(a => a.id === activityId)
    if (!activity) return
    const cats = activity.data_categories.includes(categoryId)
      ? activity.data_categories.filter(c => c !== categoryId)
      : [...activity.data_categories, categoryId]
    updateActivity(activityId, { data_categories: cats })
  }

  const toggleDeptCollapse = (deptId: string) => {
    setCollapsedDepts(prev => {
      const next = new Set(prev)
      if (next.has(deptId)) next.delete(deptId); else next.add(deptId)
      return next
    })
  }

  const toggleExtraCategories = (activityId: string) => {
    setShowExtraCategories(prev => {
      const next = new Set(prev)
      if (next.has(activityId)) next.delete(activityId); else next.add(activityId)
      return next
    })
  }

  const addCustomActivity = () => {
    const id = `custom_${Date.now()}`
    onChange({
      processingSystems: [...activities, {
        id,
        name: '',
        purpose: '',
        data_categories: [],
        legal_basis: 'contract',
        custom: true,
      }],
    })
    setExpandedActivity(id)
  }

  const removeActivity = (id: string) => {
    onChange({ processingSystems: activities.filter(a => a.id !== id) })
    if (expandedActivity === id) setExpandedActivity(null)
  }

  // Count active activities per department
  const deptActivityCount = (dept: ActivityDepartment) =>
    dept.activities.filter(a => activeIds.has(a.id)).length

  // AI Systems
  const addAISystem = () => {
    onChange({ aiSystems: [...aiSystems, { name: '', vendor: '', purpose: '', processes_personal_data: false }] })
  }
  const removeAISystem = (i: number) => {
    onChange({ aiSystems: aiSystems.filter((_: AISystem, idx: number) => idx !== i) })
  }
  const updateAISystem = (i: number, updates: Partial<AISystem>) => {
    const updated = [...aiSystems]
    updated[i] = { ...updated[i], ...updates }
    onChange({ aiSystems: updated })
  }

  // Render activity detail panel (shared between template and custom)
  const renderActivityDetail = (activity: ProcessingActivity, template: ActivityTemplate | null) => {
    const primaryIds = new Set(template?.primary_categories || [])
    const art9Ids = new Set(template?.art9_relevant || [])
    const primaryCats = ALL_DATA_CATEGORIES.filter(c => primaryIds.has(c.id))
    const extraCats = ALL_DATA_CATEGORIES.filter(c => !primaryIds.has(c.id))
    const relevantArt9 = ALL_SPECIAL_CATEGORIES.filter(c => art9Ids.has(c.id))
    const otherArt9 = ALL_SPECIAL_CATEGORIES.filter(c => !art9Ids.has(c.id))
    const showingExtra = showExtraCategories.has(activity.id)
    // For custom activities, show all categories
    const isCustom = !template || activity.custom

    return (
      <div className="ml-4 mt-2 p-4 bg-gray-50 rounded-lg border border-gray-200 space-y-4">
        {/* Custom: name + purpose fields */}
        {isCustom && (
          <div className="grid grid-cols-1 gap-3">
            <input type="text" value={activity.name} onChange={e => updateActivity(activity.id, { name: e.target.value })} placeholder="Name der Verarbeitungstätigkeit" className="px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-purple-500 focus:border-transparent" />
            <input type="text" value={activity.purpose} onChange={e => updateActivity(activity.id, { purpose: e.target.value })} placeholder="Zweck der Verarbeitung" className="px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-purple-500 focus:border-transparent" />
          </div>
        )}

        {/* Primary Data Categories */}
        <div>
          <label className="block text-xs font-medium text-gray-600 mb-2">Betroffene Datenkategorien</label>
          <div className="grid grid-cols-2 gap-1.5">
            {(isCustom ? ALL_DATA_CATEGORIES : primaryCats).map(cat => (
              <label key={cat.id} className="flex items-center gap-2 text-xs p-1.5 rounded hover:bg-gray-100 cursor-pointer">
                <input type="checkbox" checked={activity.data_categories.includes(cat.id)} onChange={() => toggleDataCategory(activity.id, cat.id)} className="w-3.5 h-3.5 text-purple-600 rounded focus:ring-purple-500" />
                <span className="text-gray-700" title={cat.desc}>{cat.label}</span>
              </label>
            ))}
          </div>
        </div>

        {/* Extra categories (expandable, only for template-based) */}
        {!isCustom && extraCats.length > 0 && (
          <div>
            <button type="button" onClick={() => toggleExtraCategories(activity.id)} className="text-xs text-purple-600 hover:text-purple-800">
              {showingExtra ? '▾ Weitere Kategorien ausblenden' : `▸ Weitere ${extraCats.length} Kategorien anzeigen`}
            </button>
            {showingExtra && (
              <div className="grid grid-cols-2 gap-1.5 mt-2">
                {extraCats.map(cat => (
                  <label key={cat.id} className="flex items-center gap-2 text-xs p-1.5 rounded hover:bg-gray-100 cursor-pointer">
                    <input type="checkbox" checked={activity.data_categories.includes(cat.id)} onChange={() => toggleDataCategory(activity.id, cat.id)} className="w-3.5 h-3.5 text-purple-600 rounded focus:ring-purple-500" />
                    <span className="text-gray-500" title={cat.desc}>{cat.label}</span>
                  </label>
                ))}
              </div>
            )}
          </div>
        )}

        {/* Art. 9 Special Categories — only show if relevant for this activity */}
        {(isCustom ? ALL_SPECIAL_CATEGORIES.length > 0 : relevantArt9.length > 0) && (
          <div className="bg-red-50 rounded-lg p-3 border border-red-100">
            <label className="block text-xs font-medium text-red-700 mb-2">
              Besondere Kategorien (Art. 9 DSGVO)
              <span className="font-normal text-red-400 ml-1">— erfordern zusätzliche Rechtsgrundlage</span>
            </label>
            <div className="grid grid-cols-2 gap-1.5">
              {(isCustom ? ALL_SPECIAL_CATEGORIES : relevantArt9).map(cat => (
                <label key={cat.id} className="flex items-center gap-2 text-xs p-1.5 rounded hover:bg-red-100 cursor-pointer">
                  <input type="checkbox" checked={activity.data_categories.includes(cat.id)} onChange={() => toggleDataCategory(activity.id, cat.id)} className="w-3.5 h-3.5 text-red-600 rounded focus:ring-red-500" />
                  <span className="text-gray-700" title={cat.desc}>{cat.label}</span>
                </label>
              ))}
            </div>
            {/* Show remaining Art. 9 categories if expanded */}
            {!isCustom && otherArt9.length > 0 && showingExtra && (
              <div className="grid grid-cols-2 gap-1.5 mt-2 pt-2 border-t border-red-100">
                {otherArt9.map(cat => (
                  <label key={cat.id} className="flex items-center gap-2 text-xs p-1.5 rounded hover:bg-red-100 cursor-pointer">
                    <input type="checkbox" checked={activity.data_categories.includes(cat.id)} onChange={() => toggleDataCategory(activity.id, cat.id)} className="w-3.5 h-3.5 text-red-600 rounded focus:ring-red-500" />
                    <span className="text-gray-500" title={cat.desc}>{cat.label}</span>
                  </label>
                ))}
              </div>
            )}
          </div>
        )}

        {/* Legal Basis */}
        <div>
          <label className="block text-xs font-medium text-gray-600 mb-2">Rechtsgrundlage</label>
          <select value={activity.legal_basis} onChange={e => updateActivity(activity.id, { legal_basis: e.target.value })} className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-purple-500 focus:border-transparent">
            {LEGAL_BASES.map(lb => (
              <option key={lb.id} value={lb.id}>{lb.label}</option>
            ))}
          </select>
        </div>

        <button type="button" onClick={() => removeActivity(activity.id)} className="text-xs text-red-500 hover:text-red-700">
          Verarbeitungstätigkeit entfernen
        </button>
      </div>
    )
  }

  return (
    <div className="space-y-8">
      {/* Processing Activities grouped by department */}
      <div>
        <h3 className="text-sm font-medium text-gray-700 mb-1">Verarbeitungstätigkeiten</h3>
        <p className="text-xs text-gray-500 mb-4">
          Wählen Sie pro Abteilung aus, welche Verarbeitungen stattfinden. Diese bilden die Grundlage für Ihr Verarbeitungsverzeichnis (VVT) nach Art. 30 DSGVO.
        </p>

        <div className="space-y-4">
          {departments.map(dept => {
            const isCollapsed = collapsedDepts.has(dept.id)
            const activeCount = deptActivityCount(dept)

            return (
              <div key={dept.id} className="border border-gray-200 rounded-lg overflow-hidden">
                {/* Department header */}
                <button
                  type="button"
                  onClick={() => toggleDeptCollapse(dept.id)}
                  className="w-full flex items-center gap-3 px-4 py-3 bg-gray-50 hover:bg-gray-100 transition-colors text-left"
                >
                  <span className="text-base">{dept.icon}</span>
                  <span className="text-sm font-medium text-gray-900 flex-1">{dept.name}</span>
                  {activeCount > 0 && (
                    <span className="text-xs bg-purple-100 text-purple-700 px-2 py-0.5 rounded-full">
                      {activeCount} aktiv
                    </span>
                  )}
                  <svg className={`w-4 h-4 text-gray-400 transition-transform ${isCollapsed ? '' : 'rotate-180'}`} fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                  </svg>
                </button>

                {/* Department activities */}
                {!isCollapsed && (
                  <div className="p-3 space-y-2">
                    {dept.activities.map(template => {
                      const isActive = activeIds.has(template.id)
                      const activity = activities.find(a => a.id === template.id)
                      const isExpanded = expandedActivity === template.id

                      return (
                        <div key={template.id}>
                          <div
                            className={`flex items-center gap-3 p-3 rounded-lg border-2 cursor-pointer transition-all ${
                              isActive ? 'border-purple-500 bg-purple-50' : 'border-gray-100 hover:border-purple-300'
                            }`}
                            onClick={() => {
                              if (!isActive) {
                                toggleActivity(template, dept.id)
                                setExpandedActivity(template.id)
                              } else {
                                setExpandedActivity(isExpanded ? null : template.id)
                              }
                            }}
                          >
                            <input
                              type="checkbox"
                              checked={isActive}
                              onChange={e => { e.stopPropagation(); toggleActivity(template, dept.id) }}
                              className="w-4 h-4 text-purple-600 rounded focus:ring-purple-500 flex-shrink-0"
                            />
                            <div className="flex-1 min-w-0">
                              <span className="text-sm font-medium text-gray-900">{template.name}</span>
                              <p className="text-xs text-gray-500 truncate">{template.purpose}</p>
                            </div>
                            {isActive && (
                              <span className="text-xs text-purple-600 flex-shrink-0">
                                {activity?.data_categories.length || 0} Kat.
                              </span>
                            )}
                            {isActive && (
                              <svg className={`w-4 h-4 text-gray-400 transition-transform ${isExpanded ? 'rotate-180' : ''}`} fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                              </svg>
                            )}
                          </div>

                          {isActive && isExpanded && activity && renderActivityDetail(activity, template)}
                        </div>
                      )
                    })}
                  </div>
                )}
              </div>
            )
          })}
        </div>

        {/* Custom activities */}
        {activities.filter(a => a.custom).map(activity => (
          <div key={activity.id} className="mt-2">
            <div
              className="flex items-center gap-3 p-3 rounded-lg border-2 border-purple-500 bg-purple-50 cursor-pointer"
              onClick={() => setExpandedActivity(expandedActivity === activity.id ? null : activity.id)}
            >
              <span className="w-4 h-4 flex items-center justify-center text-purple-600 flex-shrink-0 text-sm">+</span>
              <div className="flex-1 min-w-0">
                <span className="text-sm font-medium text-gray-900">{activity.name || 'Neue Verarbeitungstätigkeit'}</span>
              </div>
              <svg className={`w-4 h-4 text-gray-400 transition-transform ${expandedActivity === activity.id ? 'rotate-180' : ''}`} fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
              </svg>
            </div>
            {expandedActivity === activity.id && renderActivityDetail(activity, null)}
          </div>
        ))}

        {/* Add custom activity button */}
        <button
          type="button"
          onClick={addCustomActivity}
          className="w-full mt-3 px-3 py-2 text-sm text-purple-700 bg-purple-50 border-2 border-dashed border-purple-200 rounded-lg hover:bg-purple-100 hover:border-purple-300 transition-colors"
        >
          + Eigene Verarbeitungstätigkeit hinzufügen
        </button>
      </div>

      {/* AI Systems — simplified */}
      <div className="border-t border-gray-200 pt-6">
        <div className="flex items-center justify-between mb-1">
          <h3 className="text-sm font-medium text-gray-700">KI-Systeme</h3>
          <button type="button" onClick={addAISystem} className="px-3 py-1.5 text-sm bg-purple-100 text-purple-700 rounded-lg hover:bg-purple-200">
            + KI-System
          </button>
        </div>
        <p className="text-xs text-gray-500 mb-4">
          Welche KI-Systeme setzen Sie ein? Die Risikoeinstufung nach AI Act ermittelt unser Tool automatisch.
        </p>

        {aiSystems.length === 0 && (
          <div className="text-center py-6 text-gray-400 border-2 border-dashed rounded-lg">
            Noch keine KI-Systeme — falls Sie keine einsetzen, einfach leer lassen
          </div>
        )}
        <div className="space-y-3">
          {aiSystems.map((ai: AISystem, i: number) => (
            <div key={i} className="border border-gray-200 rounded-lg p-4 space-y-3">
              <div className="flex justify-between items-center">
                <span className="text-xs font-medium text-gray-400">KI-System {i + 1}</span>
                <button type="button" onClick={() => removeAISystem(i)} className="text-red-400 hover:text-red-600 text-xs">Entfernen</button>
              </div>
              <div className="grid grid-cols-2 gap-3">
                <input type="text" value={ai.name} onChange={e => updateAISystem(i, { name: e.target.value })} placeholder="Name (z.B. ChatGPT, Copilot)" className="px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-purple-500 focus:border-transparent" />
                <input type="text" value={ai.vendor} onChange={e => updateAISystem(i, { vendor: e.target.value })} placeholder="Anbieter (z.B. OpenAI, Microsoft)" className="px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-purple-500 focus:border-transparent" />
              </div>
              <input type="text" value={ai.purpose} onChange={e => updateAISystem(i, { purpose: e.target.value })} placeholder="Einsatzzweck (z.B. Kundensupport, Code-Assistenz)" className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-purple-500 focus:border-transparent" />
              <label className="flex items-center gap-2 px-1">
                <input
                  type="checkbox"
                  checked={ai.processes_personal_data}
                  onChange={e => updateAISystem(i, { processes_personal_data: e.target.checked })}
                  className="w-4 h-4 text-purple-600 rounded focus:ring-purple-500"
                />
                <span className="text-sm text-gray-700">Verarbeitet personenbezogene Daten</span>
              </label>
            </div>
          ))}
        </div>
      </div>
    </div>
  )
}

// =============================================================================
// STEP 7: RECHTLICHER RAHMEN
// =============================================================================

function StepLegalFramework({
  data,
  onChange,
}: {
  data: Partial<CompanyProfile> & { subjectToNis2?: boolean; subjectToAiAct?: boolean; subjectToIso27001?: boolean; supervisoryAuthority?: string; reviewCycleMonths?: number; technicalContacts?: { name: string; role: string; email: string }[] }
  onChange: (updates: Record<string, unknown>) => void
}) {
  const contacts = (data as any).technicalContacts || []

  const addContact = () => {
    onChange({ technicalContacts: [...contacts, { name: '', role: '', email: '' }] })
  }
  const removeContact = (i: number) => {
    onChange({ technicalContacts: contacts.filter((_: { name: string; role: string; email: string }, idx: number) => idx !== i) })
  }
  const updateContact = (i: number, updates: Partial<{ name: string; role: string; email: string }>) => {
    const updated = [...contacts]
    updated[i] = { ...updated[i], ...updates }
    onChange({ technicalContacts: updated })
  }

  return (
    <div className="space-y-8">
      {/* Regulatory Flags */}
      <div>
        <h3 className="text-sm font-medium text-gray-700 mb-4">Regulatorischer Rahmen</h3>
        <div className="space-y-3">
          {[
            { key: 'subjectToNis2', label: 'NIS2-Richtlinie', desc: 'Ihr Unternehmen fällt unter die NIS2-Richtlinie (Netzwerk- und Informationssicherheit)' },
            { key: 'subjectToAiAct', label: 'EU AI Act', desc: 'Ihr Unternehmen setzt KI-Systeme ein, die unter den AI Act fallen' },
            { key: 'subjectToIso27001', label: 'ISO 27001', desc: 'Ihr Unternehmen strebt ISO 27001 Zertifizierung an oder ist bereits zertifiziert' },
          ].map(item => (
            <label
              key={item.key}
              className={`flex items-start gap-4 p-4 rounded-xl border-2 cursor-pointer transition-all ${
                (data as any)[item.key] ? 'border-purple-500 bg-purple-50' : 'border-gray-200 hover:border-purple-300'
              }`}
            >
              <input
                type="checkbox"
                checked={(data as any)[item.key] ?? false}
                onChange={e => onChange({ [item.key]: e.target.checked })}
                className="mt-1 w-5 h-5 text-purple-600 rounded focus:ring-purple-500"
              />
              <div>
                <div className="font-medium text-gray-900">{item.label}</div>
                <div className="text-sm text-gray-500">{item.desc}</div>
              </div>
            </label>
          ))}
        </div>
      </div>

      {/* Supervisory Authority & Review Cycle */}
      <div className="grid grid-cols-2 gap-6">
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">Aufsichtsbehörde</label>
          <select
            value={(data as any).supervisoryAuthority || ''}
            onChange={e => onChange({ supervisoryAuthority: e.target.value })}
            className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
          >
            <option value="">Bitte wählen...</option>
            <option value="LfDI BW">LfDI Baden-Württemberg</option>
            <option value="BayLDA">BayLDA Bayern</option>
            <option value="BlnBDI">BlnBDI Berlin</option>
            <option value="LDA BB">LDA Brandenburg</option>
            <option value="LfDI HB">LfDI Bremen</option>
            <option value="HmbBfDI">HmbBfDI Hamburg</option>
            <option value="HBDI">HBDI Hessen</option>
            <option value="LfDI MV">LfDI Mecklenburg-Vorpommern</option>
            <option value="LfD NI">LfD Niedersachsen</option>
            <option value="LDI NRW">LDI NRW</option>
            <option value="LfDI RP">LfDI Rheinland-Pfalz</option>
            <option value="UDZ SL">UDZ Saarland</option>
            <option value="SächsDSB">Sächsischer DSB</option>
            <option value="LfD LSA">LfD Sachsen-Anhalt</option>
            <option value="ULD SH">ULD Schleswig-Holstein</option>
            <option value="TLfDI">TLfDI Thüringen</option>
            <option value="BfDI">BfDI (Bund)</option>
          </select>
        </div>
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">Prüfzyklus (Monate)</label>
          <select
            value={(data as any).reviewCycleMonths || 12}
            onChange={e => onChange({ reviewCycleMonths: parseInt(e.target.value) })}
            className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
          >
            <option value={3}>Vierteljährlich (3 Monate)</option>
            <option value={6}>Halbjährlich (6 Monate)</option>
            <option value={12}>Jährlich (12 Monate)</option>
            <option value={24}>Zweijährlich (24 Monate)</option>
          </select>
        </div>
      </div>

      {/* Technical Contacts */}
      <div className="border-t border-gray-200 pt-6">
        <div className="flex items-center justify-between mb-4">
          <div>
            <h3 className="text-sm font-medium text-gray-700">Technische Ansprechpartner</h3>
            <p className="text-xs text-gray-500">CISO, IT-Manager, DSB etc.</p>
          </div>
          <button type="button" onClick={addContact} className="px-3 py-1.5 text-sm bg-purple-100 text-purple-700 rounded-lg hover:bg-purple-200">
            + Kontakt
          </button>
        </div>
        {contacts.length === 0 && (
          <div className="text-center py-4 text-gray-400 border-2 border-dashed rounded-lg text-sm">Noch keine Kontakte</div>
        )}
        <div className="space-y-3">
          {contacts.map((c: { name: string; role: string; email: string }, i: number) => (
            <div key={i} className="flex gap-3 items-center">
              <input type="text" value={c.name} onChange={e => updateContact(i, { name: e.target.value })} placeholder="Name" className="flex-1 px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-purple-500 focus:border-transparent" />
              <input type="text" value={c.role} onChange={e => updateContact(i, { role: e.target.value })} placeholder="Rolle (z.B. CISO)" className="flex-1 px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-purple-500 focus:border-transparent" />
              <input type="email" value={c.email} onChange={e => updateContact(i, { email: e.target.value })} placeholder="E-Mail" className="flex-1 px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-purple-500 focus:border-transparent" />
              <button type="button" onClick={() => removeContact(i)} className="text-red-400 hover:text-red-600 text-sm">X</button>
            </div>
          ))}
        </div>
      </div>
    </div>
  )
}

// =============================================================================
// STEP 8: PRODUKT & MASCHINE (nur fuer Maschinenbauer)
// =============================================================================

const EMPTY_MACHINE_BUILDER: MachineBuilderProfile = {
  productTypes: [],
  productDescription: '',
  productPride: '',
  containsSoftware: false,
  containsFirmware: false,
  containsAI: false,
  aiIntegrationType: [],
  hasSafetyFunction: false,
  safetyFunctionDescription: '',
  autonomousBehavior: false,
  humanOversightLevel: 'full',
  isNetworked: false,
  hasRemoteAccess: false,
  hasOTAUpdates: false,
  updateMechanism: '',
  exportMarkets: [],
  criticalSectorClients: false,
  criticalSectors: [],
  oemClients: false,
  ceMarkingRequired: false,
  existingCEProcess: false,
  hasRiskAssessment: false,
}

function StepMachineBuilder({
  data,
  onChange,
}: {
  data: Partial<CompanyProfile>
  onChange: (updates: Partial<CompanyProfile>) => void
}) {
  const mb = data.machineBuilder || EMPTY_MACHINE_BUILDER

  const updateMB = (updates: Partial<MachineBuilderProfile>) => {
    onChange({ machineBuilder: { ...mb, ...updates } })
  }

  const toggleProductType = (type: MachineProductType) => {
    const current = mb.productTypes || []
    if (current.includes(type)) {
      updateMB({ productTypes: current.filter(t => t !== type) })
    } else {
      updateMB({ productTypes: [...current, type] })
    }
  }

  const toggleAIType = (type: AIIntegrationType) => {
    const current = mb.aiIntegrationType || []
    if (current.includes(type)) {
      updateMB({ aiIntegrationType: current.filter(t => t !== type) })
    } else {
      updateMB({ aiIntegrationType: [...current, type] })
    }
  }

  const toggleCriticalSector = (sector: CriticalSector) => {
    const current = mb.criticalSectors || []
    if (current.includes(sector)) {
      updateMB({ criticalSectors: current.filter(s => s !== sector) })
    } else {
      updateMB({ criticalSectors: [...current, sector] })
    }
  }

  return (
    <div className="space-y-8">
      {/* Block 1: Erzaehlen Sie uns von Ihrer Anlage */}
      <div>
        <h3 className="text-lg font-semibold text-gray-900 mb-1">Erzaehlen Sie uns von Ihrer Anlage</h3>
        <p className="text-sm text-gray-500 mb-4">
          Je besser wir Ihr Produkt verstehen, desto praeziser koennen wir die relevanten Vorschriften identifizieren.
        </p>

        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              Was baut Ihr Unternehmen? <span className="text-red-500">*</span>
            </label>
            <textarea
              value={mb.productDescription}
              onChange={e => updateMB({ productDescription: e.target.value })}
              placeholder="z.B. Wir bauen automatisierte Pruefstaende fuer die Qualitaetskontrolle in der Automobilindustrie..."
              rows={3}
              className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              Was macht Ihre Anlage besonders?
            </label>
            <textarea
              value={mb.productPride}
              onChange={e => updateMB({ productPride: e.target.value })}
              placeholder="z.B. Unsere Anlage kann 500 Teile/Stunde mit 99.9% Erkennungsrate pruefen..."
              rows={2}
              className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-3">
              Produkttyp <span className="text-gray-400">(Mehrfachauswahl)</span>
            </label>
            <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
              {Object.entries(MACHINE_PRODUCT_TYPE_LABELS).map(([value, label]) => (
                <button
                  key={value}
                  type="button"
                  onClick={() => toggleProductType(value as MachineProductType)}
                  className={`px-4 py-3 rounded-lg border-2 text-sm font-medium transition-all ${
                    mb.productTypes.includes(value as MachineProductType)
                      ? 'border-purple-500 bg-purple-50 text-purple-700'
                      : 'border-gray-200 hover:border-purple-300 text-gray-700'
                  }`}
                >
                  {label}
                </button>
              ))}
            </div>
          </div>
        </div>
      </div>

      {/* Block 2: Software & KI */}
      <div className="border-t border-gray-200 pt-6">
        <h3 className="text-lg font-semibold text-gray-900 mb-4">Software & KI in Ihrem Produkt</h3>

        <div className="space-y-4">
          <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
            {[
              { key: 'containsSoftware', label: 'Enthaelt Software', desc: 'Anwendungssoftware in der Maschine' },
              { key: 'containsFirmware', label: 'Enthaelt Firmware', desc: 'Embedded Software / Steuerung' },
              { key: 'containsAI', label: 'Enthaelt KI/ML', desc: 'Kuenstliche Intelligenz / Machine Learning' },
            ].map(item => (
              <label
                key={item.key}
                className={`flex items-start gap-3 p-4 rounded-xl border-2 cursor-pointer transition-all ${
                  (mb as any)[item.key]
                    ? 'border-purple-500 bg-purple-50'
                    : 'border-gray-200 hover:border-purple-300'
                }`}
              >
                <input
                  type="checkbox"
                  checked={(mb as any)[item.key] ?? false}
                  onChange={e => updateMB({ [item.key]: e.target.checked } as any)}
                  className="mt-1 w-5 h-5 text-purple-600 rounded focus:ring-purple-500"
                />
                <div>
                  <div className="font-medium text-gray-900 text-sm">{item.label}</div>
                  <div className="text-xs text-gray-500">{item.desc}</div>
                </div>
              </label>
            ))}
          </div>

          {mb.containsAI && (
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-3">
                Art der KI-Integration
              </label>
              <div className="grid grid-cols-2 gap-3">
                {Object.entries(AI_INTEGRATION_TYPE_LABELS).map(([value, label]) => (
                  <button
                    key={value}
                    type="button"
                    onClick={() => toggleAIType(value as AIIntegrationType)}
                    className={`px-4 py-2 rounded-lg border text-sm transition-all ${
                      mb.aiIntegrationType.includes(value as AIIntegrationType)
                        ? 'border-purple-500 bg-purple-50 text-purple-700'
                        : 'border-gray-200 hover:border-purple-300 text-gray-700'
                    }`}
                  >
                    {label}
                  </button>
                ))}
              </div>
            </div>
          )}

          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <label className={`flex items-start gap-3 p-4 rounded-xl border-2 cursor-pointer transition-all ${
              mb.hasSafetyFunction ? 'border-red-400 bg-red-50' : 'border-gray-200 hover:border-gray-300'
            }`}>
              <input
                type="checkbox"
                checked={mb.hasSafetyFunction}
                onChange={e => updateMB({ hasSafetyFunction: e.target.checked })}
                className="mt-1 w-5 h-5 text-red-600 rounded focus:ring-red-500"
              />
              <div>
                <div className="font-medium text-gray-900 text-sm">Sicherheitsrelevante Funktion</div>
                <div className="text-xs text-gray-500">KI/SW hat sicherheitsrelevante Funktion</div>
              </div>
            </label>

            <label className={`flex items-start gap-3 p-4 rounded-xl border-2 cursor-pointer transition-all ${
              mb.autonomousBehavior ? 'border-amber-400 bg-amber-50' : 'border-gray-200 hover:border-gray-300'
            }`}>
              <input
                type="checkbox"
                checked={mb.autonomousBehavior}
                onChange={e => updateMB({ autonomousBehavior: e.target.checked })}
                className="mt-1 w-5 h-5 text-amber-600 rounded focus:ring-amber-500"
              />
              <div>
                <div className="font-medium text-gray-900 text-sm">Autonomes Verhalten</div>
                <div className="text-xs text-gray-500">System lernt oder handelt eigenstaendig</div>
              </div>
            </label>
          </div>

          {mb.hasSafetyFunction && (
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Beschreibung der Sicherheitsfunktion
              </label>
              <textarea
                value={mb.safetyFunctionDescription}
                onChange={e => updateMB({ safetyFunctionDescription: e.target.value })}
                placeholder="z.B. KI-Vision ueberwacht den Schutzbereich und stoppt den Roboter bei Personenerkennung..."
                rows={2}
                className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
              />
            </div>
          )}

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              Human Oversight Level
            </label>
            <select
              value={mb.humanOversightLevel}
              onChange={e => updateMB({ humanOversightLevel: e.target.value as HumanOversightLevel })}
              className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
            >
              {Object.entries(HUMAN_OVERSIGHT_LABELS).map(([value, label]) => (
                <option key={value} value={value}>{label}</option>
              ))}
            </select>
          </div>
        </div>
      </div>

      {/* Block 3: Konnektivitaet & Updates */}
      <div className="border-t border-gray-200 pt-6">
        <h3 className="text-lg font-semibold text-gray-900 mb-4">Konnektivitaet & Updates</h3>

        <div className="grid grid-cols-1 sm:grid-cols-3 gap-4 mb-4">
          {[
            { key: 'isNetworked', label: 'Vernetzt', desc: 'Maschine ist mit Netzwerk verbunden' },
            { key: 'hasRemoteAccess', label: 'Remote-Zugriff', desc: 'Fernwartung / Remote-Zugang' },
            { key: 'hasOTAUpdates', label: 'OTA-Updates', desc: 'Drahtlose Software-/Firmware-Updates' },
          ].map(item => (
            <label
              key={item.key}
              className={`flex items-start gap-3 p-4 rounded-xl border-2 cursor-pointer transition-all ${
                (mb as any)[item.key]
                  ? 'border-purple-500 bg-purple-50'
                  : 'border-gray-200 hover:border-purple-300'
              }`}
            >
              <input
                type="checkbox"
                checked={(mb as any)[item.key] ?? false}
                onChange={e => updateMB({ [item.key]: e.target.checked } as any)}
                className="mt-1 w-5 h-5 text-purple-600 rounded focus:ring-purple-500"
              />
              <div>
                <div className="font-medium text-gray-900 text-sm">{item.label}</div>
                <div className="text-xs text-gray-500">{item.desc}</div>
              </div>
            </label>
          ))}
        </div>

        {(mb.hasOTAUpdates || mb.hasRemoteAccess) && (
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              Wie werden Updates eingespielt?
            </label>
            <input
              type="text"
              value={mb.updateMechanism}
              onChange={e => updateMB({ updateMechanism: e.target.value })}
              placeholder="z.B. VPN-gesicherter Remote-Zugang mit manueller Freigabe..."
              className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
            />
          </div>
        )}
      </div>

      {/* Block 4: Markt & Kunden */}
      <div className="border-t border-gray-200 pt-6">
        <h3 className="text-lg font-semibold text-gray-900 mb-4">Markt & Kunden</h3>

        <div className="space-y-4">
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <label className={`flex items-start gap-3 p-4 rounded-xl border-2 cursor-pointer transition-all ${
              mb.criticalSectorClients ? 'border-red-400 bg-red-50' : 'border-gray-200 hover:border-gray-300'
            }`}>
              <input
                type="checkbox"
                checked={mb.criticalSectorClients}
                onChange={e => updateMB({ criticalSectorClients: e.target.checked })}
                className="mt-1 w-5 h-5 text-red-600 rounded focus:ring-red-500"
              />
              <div>
                <div className="font-medium text-gray-900 text-sm">Liefert an KRITIS-Betreiber</div>
                <div className="text-xs text-gray-500">Kunden in kritischer Infrastruktur</div>
              </div>
            </label>

            <label className={`flex items-start gap-3 p-4 rounded-xl border-2 cursor-pointer transition-all ${
              mb.oemClients ? 'border-purple-500 bg-purple-50' : 'border-gray-200 hover:border-gray-300'
            }`}>
              <input
                type="checkbox"
                checked={mb.oemClients}
                onChange={e => updateMB({ oemClients: e.target.checked })}
                className="mt-1 w-5 h-5 text-purple-600 rounded focus:ring-purple-500"
              />
              <div>
                <div className="font-medium text-gray-900 text-sm">OEM-Zulieferer</div>
                <div className="text-xs text-gray-500">Liefern Komponenten an andere Hersteller</div>
              </div>
            </label>
          </div>

          {mb.criticalSectorClients && (
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-3">
                Kritische Sektoren Ihrer Kunden
              </label>
              <div className="grid grid-cols-2 sm:grid-cols-4 gap-2">
                {Object.entries(CRITICAL_SECTOR_LABELS).map(([value, label]) => (
                  <button
                    key={value}
                    type="button"
                    onClick={() => toggleCriticalSector(value as CriticalSector)}
                    className={`px-3 py-2 rounded-lg border text-sm transition-all ${
                      mb.criticalSectors.includes(value as CriticalSector)
                        ? 'border-red-400 bg-red-50 text-red-700'
                        : 'border-gray-200 hover:border-gray-300 text-gray-700'
                    }`}
                  >
                    {label}
                  </button>
                ))}
              </div>
            </div>
          )}

          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <label className={`flex items-start gap-3 p-4 rounded-xl border-2 cursor-pointer transition-all ${
              mb.ceMarkingRequired ? 'border-blue-500 bg-blue-50' : 'border-gray-200 hover:border-gray-300'
            }`}>
              <input
                type="checkbox"
                checked={mb.ceMarkingRequired}
                onChange={e => updateMB({ ceMarkingRequired: e.target.checked })}
                className="mt-1 w-5 h-5 text-blue-600 rounded focus:ring-blue-500"
              />
              <div>
                <div className="font-medium text-gray-900 text-sm">CE-Kennzeichnung erforderlich</div>
                <div className="text-xs text-gray-500">Produkt benoetigt CE-Zertifizierung</div>
              </div>
            </label>

            <label className={`flex items-start gap-3 p-4 rounded-xl border-2 cursor-pointer transition-all ${
              mb.existingCEProcess ? 'border-green-400 bg-green-50' : 'border-gray-200 hover:border-gray-300'
            }`}>
              <input
                type="checkbox"
                checked={mb.existingCEProcess}
                onChange={e => updateMB({ existingCEProcess: e.target.checked })}
                className="mt-1 w-5 h-5 text-green-600 rounded focus:ring-green-500"
              />
              <div>
                <div className="font-medium text-gray-900 text-sm">Bestehender CE-Prozess</div>
                <div className="text-xs text-gray-500">Bereits ein CE-Verfahren etabliert</div>
              </div>
            </label>
          </div>

          {mb.ceMarkingRequired && (
            <label className={`flex items-start gap-3 p-4 rounded-xl border-2 cursor-pointer transition-all ${
              mb.hasRiskAssessment ? 'border-green-400 bg-green-50' : 'border-red-400 bg-red-50'
            }`}>
              <input
                type="checkbox"
                checked={mb.hasRiskAssessment}
                onChange={e => updateMB({ hasRiskAssessment: e.target.checked })}
                className="mt-1 w-5 h-5 text-green-600 rounded focus:ring-green-500"
              />
              <div>
                <div className="font-medium text-gray-900 text-sm">Bestehende Risikobeurteilung</div>
                <div className="text-xs text-gray-500">
                  {mb.hasRiskAssessment
                    ? 'Risikobeurteilung vorhanden'
                    : 'Keine bestehende Risikobeurteilung - IACE hilft Ihnen dabei!'}
                </div>
              </div>
            </label>
          )}
        </div>
      </div>
    </div>
  )
}

// =============================================================================
// COVERAGE ASSESSMENT COMPONENT
// =============================================================================

// =============================================================================
// GENERATE DOCUMENTS BUTTON
// =============================================================================

const DOC_TYPES = [
  { id: 'dsfa', label: 'DSFA', desc: 'Datenschutz-Folgenabschätzung' },
  { id: 'vvt', label: 'VVT', desc: 'Verarbeitungsverzeichnis' },
  { id: 'tom', label: 'TOM', desc: 'Technisch-Organisatorische Maßnahmen' },
  { id: 'loeschfristen', label: 'Löschfristen', desc: 'Löschfristen-Katalog' },
  { id: 'obligation', label: 'Pflichten', desc: 'Compliance-Pflichten' },
]

function GenerateDocumentsButton() {
  const [generating, setGenerating] = useState<string | null>(null)
  const [results, setResults] = useState<Record<string, { ok: boolean; count: number }>>({})

  const handleGenerate = async (docType: string) => {
    setGenerating(docType)
    try {
      const res = await fetch(`/api/sdk/v1/compliance/generation/apply/${docType}`, { method: 'POST' })
      if (res.ok) {
        const data = await res.json()
        setResults(prev => ({ ...prev, [docType]: { ok: true, count: data.change_requests_created || 0 } }))
      } else {
        setResults(prev => ({ ...prev, [docType]: { ok: false, count: 0 } }))
      }
    } catch {
      setResults(prev => ({ ...prev, [docType]: { ok: false, count: 0 } }))
    } finally {
      setGenerating(null)
    }
  }

  return (
    <div className="space-y-2">
      {DOC_TYPES.map(dt => (
        <div key={dt.id} className="flex items-center justify-between">
          <div>
            <span className="text-sm font-medium text-gray-900">{dt.label}</span>
            <span className="text-xs text-gray-500 ml-1">({dt.desc})</span>
          </div>
          {results[dt.id] ? (
            <span className={`text-xs px-2 py-1 rounded ${results[dt.id].ok ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}`}>
              {results[dt.id].ok ? `${results[dt.id].count} CR erstellt` : 'Fehler'}
            </span>
          ) : (
            <button
              onClick={() => handleGenerate(dt.id)}
              disabled={generating !== null}
              className="px-3 py-1 text-xs bg-purple-600 text-white rounded hover:bg-purple-700 disabled:opacity-50"
            >
              {generating === dt.id ? 'Generiere...' : 'Generieren'}
            </button>
          )}
        </div>
      ))}
      {Object.keys(results).length > 0 && (
        <a href="/sdk/change-requests" className="block text-center text-sm text-purple-600 hover:text-purple-800 font-medium mt-3">
          Zur Änderungsanfragen-Inbox &rarr;
        </a>
      )}
    </div>
  )
}

// =============================================================================
// MAIN COMPONENT
// =============================================================================

export default function CompanyProfilePage() {
  const { state, dispatch, setCompanyProfile, goToNextStep } = useSDK()
  const [currentStep, setCurrentStep] = useState(1)
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false)
  const [isDeleting, setIsDeleting] = useState(false)
  const [formData, setFormData] = useState<Partial<CompanyProfile>>({
    companyName: '',
    legalForm: undefined,
    industry: '',
    foundedYear: null,
    businessModel: undefined,
    offerings: [],
    offeringUrls: {},
    companySize: undefined,
    employeeCount: '',
    annualRevenue: '',
    headquartersCountry: 'DE',
    headquartersCountryOther: '',
    headquartersStreet: '',
    headquartersZip: '',
    headquartersCity: '',
    headquartersState: '',
    hasInternationalLocations: false,
    internationalCountries: [],
    targetMarkets: [],
    primaryJurisdiction: 'DE',
    isDataController: true,
    isDataProcessor: false,
    usesAI: false,
    aiUseCases: [],
    dpoName: null,
    dpoEmail: null,
    legalContactName: null,
    legalContactEmail: null,
    isComplete: false,
    completedAt: null,
  })

  const showMachineBuilderStep = isMachineBuilderIndustry(formData.industry || '')
  const wizardSteps = getWizardSteps(formData.industry || '')
  const totalSteps = wizardSteps.length
  const lastStep = wizardSteps[wizardSteps.length - 1].id

  // Load existing profile: first try backend, then SDK state as fallback
  useEffect(() => {
    let cancelled = false

    async function loadFromBackend() {
      try {
        const response = await fetch('/api/sdk/v1/company-profile?tenant_id=default')
        if (response.ok) {
          const data = await response.json()
          if (data && !cancelled) {
            const backendProfile: Partial<CompanyProfile> = {
              companyName: data.company_name || '',
              legalForm: data.legal_form || undefined,
              industry: data.industry || '',
              foundedYear: data.founded_year || undefined,
              businessModel: data.business_model || undefined,
              offerings: data.offerings || [],
              offeringUrls: data.offering_urls || {},
              companySize: data.company_size || undefined,
              employeeCount: data.employee_count || '',
              annualRevenue: data.annual_revenue || '',
              headquartersCountry: data.headquarters_country || 'DE',
              headquartersCountryOther: data.headquarters_country_other || '',
              headquartersStreet: data.headquarters_street || '',
              headquartersZip: data.headquarters_zip || '',
              headquartersCity: data.headquarters_city || '',
              headquartersState: data.headquarters_state || '',
              hasInternationalLocations: data.has_international_locations || false,
              internationalCountries: data.international_countries || [],
              targetMarkets: data.target_markets || [],
              primaryJurisdiction: data.primary_jurisdiction || 'DE',
              isDataController: data.is_data_controller ?? true,
              isDataProcessor: data.is_data_processor ?? false,
              usesAI: data.uses_ai ?? false,
              aiUseCases: data.ai_use_cases || [],
              dpoName: data.dpo_name || '',
              dpoEmail: data.dpo_email || '',
              isComplete: data.is_complete || false,
              // Phase 2 extended fields
              processingSystems: data.processing_systems || [],
              aiSystems: data.ai_systems || [],
              technicalContacts: data.technical_contacts || [],
              subjectToNis2: data.subject_to_nis2 || false,
              subjectToAiAct: data.subject_to_ai_act || false,
              subjectToIso27001: data.subject_to_iso27001 || false,
              supervisoryAuthority: data.supervisory_authority || '',
              reviewCycleMonths: data.review_cycle_months || 12,
              repos: data.repos || [],
              documentSources: data.document_sources || [],
            } as any
            setFormData(backendProfile)
            if (backendProfile.isComplete) {
              setCurrentStep(7)
            }
            return
          }
        }
      } catch {
        // Backend not available, fall through to SDK state
      }

      // Fallback: use SDK state
      if (!cancelled && state.companyProfile) {
        setFormData(state.companyProfile)
        if (state.companyProfile.isComplete) {
          setCurrentStep(7)
        }
      }
    }

    loadFromBackend()

    return () => { cancelled = true }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  const updateFormData = (updates: Partial<CompanyProfile>) => {
    setFormData(prev => ({ ...prev, ...updates }))
  }

  // Shared payload builder for draft saves and final save (DRY)
  const buildProfilePayload = (isComplete: boolean) => ({
    company_name: formData.companyName || '',
    legal_form: formData.legalForm || 'GmbH',
    industry: formData.industry || '',
    founded_year: formData.foundedYear || null,
    business_model: formData.businessModel || 'B2B',
    offerings: formData.offerings || [],
    offering_urls: formData.offeringUrls || {},
    company_size: formData.companySize || 'small',
    employee_count: formData.employeeCount || '',
    annual_revenue: formData.annualRevenue || '',
    headquarters_country: formData.headquartersCountry || 'DE',
    headquarters_country_other: formData.headquartersCountryOther || '',
    headquarters_street: formData.headquartersStreet || '',
    headquarters_zip: formData.headquartersZip || '',
    headquarters_city: formData.headquartersCity || '',
    headquarters_state: formData.headquartersState || '',
    has_international_locations: formData.hasInternationalLocations || false,
    international_countries: formData.internationalCountries || [],
    target_markets: formData.targetMarkets || [],
    primary_jurisdiction: formData.primaryJurisdiction || 'DE',
    is_data_controller: formData.isDataController ?? true,
    is_data_processor: formData.isDataProcessor ?? false,
    uses_ai: formData.usesAI ?? false,
    ai_use_cases: formData.aiUseCases || [],
    dpo_name: formData.dpoName || '',
    dpo_email: formData.dpoEmail || '',
    is_complete: isComplete,
    // Phase 2 extended fields
    processing_systems: (formData as any).processingSystems || [],
    ai_systems: (formData as any).aiSystems || [],
    technical_contacts: (formData as any).technicalContacts || [],
    subject_to_nis2: (formData as any).subjectToNis2 || false,
    subject_to_ai_act: (formData as any).subjectToAiAct || false,
    subject_to_iso27001: (formData as any).subjectToIso27001 || false,
    supervisory_authority: (formData as any).supervisoryAuthority || '',
    review_cycle_months: (formData as any).reviewCycleMonths || 12,
    repos: (formData as any).repos || [],
    document_sources: (formData as any).documentSources || [],
    // Machine builder fields (if applicable)
    ...(formData.machineBuilder ? {
      machine_builder: {
        product_types: formData.machineBuilder.productTypes || [],
        product_description: formData.machineBuilder.productDescription || '',
        product_pride: formData.machineBuilder.productPride || '',
        contains_software: formData.machineBuilder.containsSoftware || false,
        contains_firmware: formData.machineBuilder.containsFirmware || false,
        contains_ai: formData.machineBuilder.containsAI || false,
        ai_integration_type: formData.machineBuilder.aiIntegrationType || [],
        has_safety_function: formData.machineBuilder.hasSafetyFunction || false,
        safety_function_description: formData.machineBuilder.safetyFunctionDescription || '',
        autonomous_behavior: formData.machineBuilder.autonomousBehavior || false,
        human_oversight_level: formData.machineBuilder.humanOversightLevel || 'full',
        is_networked: formData.machineBuilder.isNetworked || false,
        has_remote_access: formData.machineBuilder.hasRemoteAccess || false,
        has_ota_updates: formData.machineBuilder.hasOTAUpdates || false,
        update_mechanism: formData.machineBuilder.updateMechanism || '',
        export_markets: formData.machineBuilder.exportMarkets || [],
        critical_sector_clients: formData.machineBuilder.criticalSectorClients || false,
        critical_sectors: formData.machineBuilder.criticalSectors || [],
        oem_clients: formData.machineBuilder.oemClients || false,
        ce_marking_required: formData.machineBuilder.ceMarkingRequired || false,
        existing_ce_process: formData.machineBuilder.existingCEProcess || false,
        has_risk_assessment: formData.machineBuilder.hasRiskAssessment || false,
      },
    } : {}),
  })

  // Auto-save draft to backend (fire-and-forget, non-blocking)
  const [draftSaveStatus, setDraftSaveStatus] = useState<'idle' | 'saving' | 'saved' | 'error'>('idle')
  const draftSaveTimerRef = React.useRef<ReturnType<typeof setTimeout> | null>(null)

  const saveProfileDraft = async () => {
    setDraftSaveStatus('saving')
    try {
      await fetch('/api/sdk/v1/company-profile', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(buildProfilePayload(false)),
      })
      setDraftSaveStatus('saved')
      // Reset status after 3 seconds
      if (draftSaveTimerRef.current) clearTimeout(draftSaveTimerRef.current)
      draftSaveTimerRef.current = setTimeout(() => setDraftSaveStatus('idle'), 3000)
    } catch (err) {
      console.error('Draft save failed:', err)
      setDraftSaveStatus('error')
      if (draftSaveTimerRef.current) clearTimeout(draftSaveTimerRef.current)
      draftSaveTimerRef.current = setTimeout(() => setDraftSaveStatus('idle'), 5000)
    }
  }

  const handleNext = () => {
    if (currentStep < lastStep) {
      // Skip step 8 if not a machine builder
      const nextStep = currentStep + 1
      if (nextStep === 8 && !showMachineBuilderStep) {
        // Complete profile (was step 7, last step for non-machine-builders)
        completeAndSaveProfile()
        return
      }
      saveProfileDraft()
      setCurrentStep(nextStep)
    } else {
      // Complete profile
      completeAndSaveProfile()
    }
  }

  const completeAndSaveProfile = async () => {
    const completeProfile: CompanyProfile = {
      ...formData,
      isComplete: true,
      completedAt: new Date(),
    } as CompanyProfile

    setCompanyProfile(completeProfile)
    dispatch({ type: 'COMPLETE_STEP', payload: 'company-profile' })

    // Also persist to dedicated backend endpoint
    try {
      await fetch('/api/sdk/v1/company-profile', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(buildProfilePayload(true)),
      })
    } catch (err) {
      console.error('Failed to save company profile to backend:', err)
    }

    goToNextStep()
  }

  const handleBack = () => {
    if (currentStep > 1) {
      saveProfileDraft()
      setCurrentStep(prev => prev - 1)
    }
  }

  const handleDeleteProfile = async () => {
    setIsDeleting(true)
    try {
      const response = await fetch('/api/sdk/v1/company-profile?tenant_id=default', {
        method: 'DELETE',
      })
      if (response.ok) {
        // Reset form and SDK state
        setFormData({
          companyName: '',
          legalForm: undefined,
          industry: '',
          foundedYear: null,
          businessModel: undefined,
          offerings: [],
          offeringUrls: {},
          companySize: undefined,
          employeeCount: '',
          annualRevenue: '',
          headquartersCountry: 'DE',
          headquartersCity: '',
          hasInternationalLocations: false,
          internationalCountries: [],
          targetMarkets: [],
          primaryJurisdiction: 'DE',
          isDataController: true,
          isDataProcessor: false,
          usesAI: false,
          aiUseCases: [],
          dpoName: null,
          dpoEmail: null,
          legalContactName: null,
          legalContactEmail: null,
          isComplete: false,
          completedAt: null,
        })
        setCurrentStep(1)
        dispatch({ type: 'SET_STATE', payload: { companyProfile: undefined } })
      }
    } catch (err) {
      console.error('Failed to delete company profile:', err)
    } finally {
      setIsDeleting(false)
      setShowDeleteConfirm(false)
    }
  }

  const canProceed = () => {
    switch (currentStep) {
      case 1:
        return formData.companyName && formData.legalForm
      case 2:
        return formData.businessModel && (formData.offerings?.length || 0) > 0
      case 3:
        return formData.companySize
      case 4:
        return formData.headquartersCountry && (formData.targetMarkets?.length || 0) > 0
      case 5:
        return true
      case 6:
        return true // Systems & AI step is optional
      case 7:
        return true // Legal framework step is optional
      case 8:
        // Machine builder step: require at least product description
        return (formData.machineBuilder?.productDescription?.length || 0) > 0
      default:
        return false
    }
  }

  const isLastStep = currentStep === lastStep || (currentStep === 7 && !showMachineBuilderStep)

  return (
    <div className="min-h-screen bg-gray-50 py-8">
      <div className="max-w-6xl mx-auto px-4">
        {/* Header */}
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-gray-900">Unternehmensprofil</h1>
          <p className="text-gray-600 mt-2">
            Helfen Sie uns, Ihr Unternehmen zu verstehen, damit wir die relevanten Regulierungen
            identifizieren können.
          </p>
        </div>

        {/* Progress Steps */}
        <div className="mb-8">
          <div className="flex items-center justify-between">
            {wizardSteps.map((step, index) => (
              <React.Fragment key={step.id}>
                <div className="flex items-center">
                  <div
                    className={`w-10 h-10 rounded-full flex items-center justify-center text-sm font-medium ${
                      step.id < currentStep
                        ? 'bg-purple-600 text-white'
                        : step.id === currentStep
                        ? 'bg-purple-100 text-purple-600 border-2 border-purple-600'
                        : 'bg-gray-100 text-gray-400'
                    }`}
                  >
                    {step.id < currentStep ? (
                      <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
                        <path
                          fillRule="evenodd"
                          d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"
                          clipRule="evenodd"
                        />
                      </svg>
                    ) : (
                      step.id
                    )}
                  </div>
                  <div className="ml-3 hidden sm:block">
                    <div
                      className={`text-sm font-medium ${
                        step.id <= currentStep ? 'text-gray-900' : 'text-gray-400'
                      }`}
                    >
                      {step.name}
                    </div>
                  </div>
                </div>
                {index < wizardSteps.length - 1 && (
                  <div
                    className={`flex-1 h-0.5 mx-4 ${
                      step.id < currentStep ? 'bg-purple-600' : 'bg-gray-200'
                    }`}
                  />
                )}
              </React.Fragment>
            ))}
          </div>
        </div>

        {/* Content */}
        <div>
          {/* Form */}
          <div>
            <div className="bg-white rounded-xl border border-gray-200 p-8">
              <div className="mb-6">
                <h2 className="text-xl font-semibold text-gray-900">
                  {(wizardSteps.find(s => s.id === currentStep) || wizardSteps[0]).name}
                </h2>
                <p className="text-gray-500">{(wizardSteps.find(s => s.id === currentStep) || wizardSteps[0]).description}</p>
                {STEP_EXPLANATIONS[currentStep] && (
                  <p className="text-sm text-blue-600 mt-2">{STEP_EXPLANATIONS[currentStep]}</p>
                )}
              </div>

              {currentStep === 1 && <StepBasicInfo data={formData} onChange={updateFormData} />}
              {currentStep === 2 && <StepBusinessModel data={formData} onChange={updateFormData} />}
              {currentStep === 3 && <StepCompanySize data={formData} onChange={updateFormData} />}
              {currentStep === 4 && <StepLocations data={formData} onChange={updateFormData} />}
              {currentStep === 5 && <StepDataProtection data={formData} onChange={updateFormData} />}
              {currentStep === 6 && <StepProcessingAndAI data={formData} onChange={updateFormData} />}
              {currentStep === 7 && <StepLegalFramework data={formData} onChange={updateFormData} />}
              {currentStep === 8 && showMachineBuilderStep && <StepMachineBuilder data={formData} onChange={updateFormData} />}

              {/* Navigation */}
              <div className="flex justify-between items-center mt-8 pt-6 border-t border-gray-200">
                <button
                  onClick={handleBack}
                  disabled={currentStep === 1}
                  className="px-6 py-3 text-gray-600 hover:text-gray-900 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  Zurück
                </button>
                {/* Draft save status */}
                {draftSaveStatus !== 'idle' && (
                  <span className={`text-xs px-3 py-1 rounded-full ${
                    draftSaveStatus === 'saving' ? 'text-gray-500 bg-gray-100' :
                    draftSaveStatus === 'saved' ? 'text-green-600 bg-green-50' :
                    'text-red-600 bg-red-50'
                  }`}>
                    {draftSaveStatus === 'saving' && 'Speichern...'}
                    {draftSaveStatus === 'saved' && '✓ Gespeichert'}
                    {draftSaveStatus === 'error' && 'Speichern fehlgeschlagen'}
                  </span>
                )}
                <button
                  onClick={handleNext}
                  disabled={!canProceed()}
                  className="px-8 py-3 bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {isLastStep ? 'Profil speichern & weiter' : 'Weiter'}
                </button>
              </div>

              {/* Generate Documents CTA (only when profile is complete) */}
              {formData.isComplete && (
                <div className="mt-6 bg-gradient-to-br from-purple-50 to-indigo-50 rounded-xl border border-purple-200 p-6">
                  <h3 className="font-semibold text-purple-900 mb-2">Dokumente generieren</h3>
                  <p className="text-sm text-purple-700 mb-4">
                    Basierend auf Ihrem Profil können DSFA, VVT, TOM, Löschfristen und Pflichten automatisch als Entwürfe generiert werden.
                  </p>
                  <GenerateDocumentsButton />
                </div>
              )}
            </div>
          </div>

          {/* Delete Confirmation Modal */}
          {showDeleteConfirm && (
            <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
              <div className="bg-white rounded-xl p-6 w-full max-w-md shadow-2xl">
                <h3 className="text-lg font-semibold text-gray-900 mb-2">Profil löschen?</h3>
                <p className="text-sm text-gray-600 mb-6">
                  Alle gespeicherten Unternehmensdaten werden unwiderruflich gelöscht (DSGVO Art. 17).
                  Diese Aktion kann nicht rückgängig gemacht werden.
                </p>
                <div className="flex justify-end gap-3">
                  <button
                    onClick={() => setShowDeleteConfirm(false)}
                    className="px-4 py-2 text-sm text-gray-600 hover:bg-gray-100 rounded-lg"
                  >
                    Abbrechen
                  </button>
                  <button
                    onClick={handleDeleteProfile}
                    disabled={isDeleting}
                    className="px-4 py-2 text-sm bg-red-600 text-white rounded-lg hover:bg-red-700 disabled:opacity-50"
                  >
                    {isDeleting ? 'Lösche...' : 'Endgültig löschen'}
                  </button>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
