'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: 'Systeme & KI', description: 'IT-Systeme und KI-Katalog' },
  { 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 IT-Systeme und KI-Anwendungen werden für das Verarbeitungsverzeichnis (VVT), die technisch-organisatorischen Maßnahmen (TOM) und die KI-Risikobewertung benötigt.',
  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 className="grid grid-cols-2 gap-6">
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">Mitarbeiterzahl</label>
          <select
            value={data.employeeCount || ''}
            onChange={e => onChange({ employeeCount: 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="1-9">1-9 Mitarbeiter</option>
            <option value="10-49">10-49 Mitarbeiter</option>
            <option value="50-249">50-249 Mitarbeiter</option>
            <option value="250-999">250-999 Mitarbeiter</option>
            <option value="1000+">1.000+ Mitarbeiter</option>
          </select>
        </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>
        </div>
      </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] })
    }
  }

  return (
    <div className="space-y-8">
      <div className="grid grid-cols-2 gap-6">
        <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 })}
            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="other">Anderes Land</option>
          </select>
        </div>

        <div>
          <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="z.B. 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>

      <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, regulations }]) => (
            <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="flex items-center justify-between">
                <div>
                  <div className="font-medium text-gray-900">{label}</div>
                  <div className="text-sm text-gray-500">{description}</div>
                </div>
                <div className="text-right">
                  <div className="text-xs text-gray-400">Relevante Regulierungen:</div>
                  <div className="text-xs text-purple-600">{regulations.join(', ')}</div>
                </div>
              </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: SYSTEME & KI
// =============================================================================

interface ProcessingSystem {
  name: string
  vendor: string
  hosting: string
  personal_data_categories: string[]
}

interface AISystem {
  name: string
  purpose: string
  risk_category: string
  vendor: string
  has_human_oversight: boolean
}

function StepSystemsAndAI({
  data,
  onChange,
}: {
  data: Partial<CompanyProfile> & { processingSystems?: ProcessingSystem[]; aiSystems?: AISystem[] }
  onChange: (updates: Record<string, unknown>) => void
}) {
  const systems = (data as any).processingSystems || []
  const aiSystems = (data as any).aiSystems || []

  const addSystem = () => {
    onChange({ processingSystems: [...systems, { name: '', vendor: '', hosting: 'cloud', personal_data_categories: [] }] })
  }
  const removeSystem = (i: number) => {
    onChange({ processingSystems: systems.filter((_: ProcessingSystem, idx: number) => idx !== i) })
  }
  const updateSystem = (i: number, updates: Partial<ProcessingSystem>) => {
    const updated = [...systems]
    updated[i] = { ...updated[i], ...updates }
    onChange({ processingSystems: updated })
  }

  const addAISystem = () => {
    onChange({ aiSystems: [...aiSystems, { name: '', purpose: '', risk_category: 'limited', vendor: '', has_human_oversight: true }] })
  }
  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 })
  }

  return (
    <div className="space-y-8">
      {/* Processing Systems */}
      <div>
        <div className="flex items-center justify-between mb-4">
          <div>
            <h3 className="text-sm font-medium text-gray-700">IT-Systeme mit personenbezogenen Daten</h3>
            <p className="text-xs text-gray-500">Systeme, die personenbezogene Daten verarbeiten (fuer VVT-Generierung)</p>
          </div>
          <button type="button" onClick={addSystem} className="px-3 py-1.5 text-sm bg-purple-100 text-purple-700 rounded-lg hover:bg-purple-200">
            + System
          </button>
        </div>
        {systems.length === 0 && (
          <div className="text-center py-6 text-gray-400 border-2 border-dashed rounded-lg">Noch keine Systeme hinzugefuegt</div>
        )}
        <div className="space-y-3">
          {systems.map((sys: ProcessingSystem, 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">System {i + 1}</span>
                <button type="button" onClick={() => removeSystem(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={sys.name} onChange={e => updateSystem(i, { name: e.target.value })} placeholder="Name (z.B. SAP HR)" 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={sys.vendor} onChange={e => updateSystem(i, { vendor: e.target.value })} placeholder="Hersteller" className="px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-purple-500 focus:border-transparent" />
              </div>
              <div className="grid grid-cols-2 gap-3">
                <select value={sys.hosting} onChange={e => updateSystem(i, { hosting: e.target.value })} className="px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-purple-500 focus:border-transparent">
                  <option value="on-premise">On-Premise</option>
                  <option value="cloud">Cloud (EU)</option>
                  <option value="us-cloud">Cloud (US)</option>
                  <option value="hybrid">Hybrid</option>
                </select>
                <input type="text" value={sys.personal_data_categories.join(', ')} onChange={e => updateSystem(i, { personal_data_categories: e.target.value.split(',').map(s => s.trim()).filter(Boolean) })} placeholder="Datenkategorien (kommagetrennt)" className="px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-purple-500 focus:border-transparent" />
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* AI Systems */}
      <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">KI-Systeme</h3>
            <p className="text-xs text-gray-500">Strukturierter KI-Katalog fuer AI Act Compliance</p>
          </div>
          <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>
        {aiSystems.length === 0 && (
          <div className="text-center py-6 text-gray-400 border-2 border-dashed rounded-lg">Noch keine KI-Systeme</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. Chatbot)" 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" 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="Zweck (z.B. Kundensupport)" 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" />
              <div className="grid grid-cols-2 gap-3">
                <select value={ai.risk_category} onChange={e => updateAISystem(i, { risk_category: e.target.value })} className="px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-purple-500 focus:border-transparent">
                  <option value="minimal">Minimal Risk</option>
                  <option value="limited">Limited Risk</option>
                  <option value="high">High Risk</option>
                  <option value="unacceptable">Unacceptable Risk</option>
                </select>
                <label className="flex items-center gap-2 px-3 py-2">
                  <input type="checkbox" checked={ai.has_human_oversight} onChange={e => updateAISystem(i, { has_human_oversight: e.target.checked })} className="w-4 h-4 text-purple-600 rounded focus:ring-purple-500" />
                  <span className="text-sm text-gray-700">Human Oversight</span>
                </label>
              </div>
            </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',
    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,
  })

  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',
              headquartersCity: data.headquarters_city || '',
              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_city: formData.headquartersCity || '',
    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 className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          {/* Form */}
          <div className="lg:col-span-2">
            <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 && <StepSystemsAndAI 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>
            </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>
          )}

          {/* Sidebar */}
          <div className="lg:col-span-1">
            {/* Generate Documents CTA */}
            {formData.isComplete && (
              <div className="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>
      </div>
    </div>
  )
}
