import React, { useEffect, useMemo, useRef, useState } from 'react';
import {
  ScheduleComponent,
  Day,
  Week,
  WorkWeek,
  Month,
  Agenda,
  Inject,
  ViewsDirective,
  ViewDirective,
} from '@syncfusion/ej2-react-schedule';
import { DropDownListComponent } from '@syncfusion/ej2-react-dropdowns';
import { DialogComponent } from '@syncfusion/ej2-react-popups';
import { L10n, loadCldr, setCulture } from '@syncfusion/ej2-base';
import type {
  EventRenderedArgs,
  ActionEventArgs,
  RenderCellEventArgs,
} from '@syncfusion/ej2-react-schedule';
import { fetchEvents, fetchEventById } from './apiEvents';
import { fetchGroups } from './apiGroups';
import { getGroupColor } from './groupColors';
import { deleteEvent, deleteEventOccurrence } from './apiEvents';
import { detachEventOccurrence, updateEvent } from './apiEvents';
import CustomEventModal from './components/CustomEventModal';
import { fetchMediaById } from './apiClients';
import { listHolidays, type Holiday } from './apiHolidays';
import {
  getAcademicPeriodForDate,
  listAcademicPeriods,
  setActiveAcademicPeriod,
} from './apiAcademicPeriods';
import {
  Presentation,
  Globe,
  Video,
  MessageSquare,
  School,
  CheckCircle,
  AlertCircle,
  TentTree,
} from 'lucide-react';
import caGregorian from './cldr/ca-gregorian.json';
import numbers from './cldr/numbers.json';
import timeZoneNames from './cldr/timeZoneNames.json';
import numberingSystems from './cldr/numberingSystems.json';

// Typ für Gruppe ergänzen
type Group = {
  id: string;
  name: string;
};

// Typ für Event ergänzen
type Event = {
  Id: string;
  Subject: string;
  StartTime: Date;
  EndTime: Date;
  IsAllDay: boolean;
  IsBlock?: boolean; // Syncfusion block appointment
  isHoliday?: boolean; // marker for styling/logic
  MediaId?: string | number;
  SlideshowInterval?: number;
  PageProgress?: boolean;
  AutoProgress?: boolean;
  WebsiteUrl?: string;
  // Video-specific fields
  Autoplay?: boolean;
  Loop?: boolean;
  Volume?: number;
  Muted?: boolean;
  Icon?: string; // <--- Icon ergänzen!
  Type?: string; // <--- Typ ergänzen, falls benötigt
  OccurrenceOfId?: string; // Serieninstanz
  RecurrenceID?: string; // Syncfusion linkage to master series
  Recurrence?: boolean; // Marker für Serientermin
  RecurrenceRule?: string | null;
  RecurrenceEnd?: string | null;
  SkipHolidays?: boolean;
  RecurrenceException?: string;
};

// CLDR-Daten laden (direkt die JSON-Objekte übergeben)
loadCldr(
  caGregorian as object,
  numbers as object,
  timeZoneNames as object,
  numberingSystems as object
);

// Deutsche Lokalisierung für den Scheduler
L10n.load({
  de: {
    schedule: {
      day: 'Tag',
      week: 'Woche',
      workWeek: 'Arbeitswoche',
      month: 'Monat',
      agenda: 'Agenda',
      today: 'Heute',
      noEvents: 'Keine Termine',
      allDay: 'Ganztägig',
      start: 'Start',
      end: 'Ende',
      event: 'Termin',
      save: 'Speichern',
      cancel: 'Abbrechen',
      delete: 'Löschen',
      edit: 'Bearbeiten',
      newEvent: 'Neuer Termin',
      title: 'Titel',
      description: 'Beschreibung',
      location: 'Ort',
      recurrence: 'Wiederholung',
      repeat: 'Wiederholen',
      deleteEvent: 'Termin löschen',
      deleteContent: 'Möchten Sie diesen Termin wirklich löschen?',
      moreDetails: 'Mehr Details',
      addTitle: 'Termintitel',
    },
  },
});

// Kultur setzen
setCulture('de');

// Mapping für Lucide-Icons
const iconMap: Record<string, React.ElementType> = {
  Presentation,
  Globe,
  Video,
  MessageSquare,
  School,
};

const eventTemplate = (event: Event) => {
  const IconComponent = iconMap[event.Icon ?? ''] || null;
  // Zeitangabe formatieren
  const start = event.StartTime instanceof Date ? event.StartTime : new Date(event.StartTime);
  const end = event.EndTime instanceof Date ? event.EndTime : new Date(event.EndTime);
  const timeString = `${start.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })} - ${end.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}`;

  // Render TentTree icon if SkipHolidays is true
  const showTentTree = !!event.SkipHolidays;
  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start' }}>
      <div style={{ display: 'flex', alignItems: 'center', color: '#000', marginBottom: 2 }}>
        {IconComponent && (
          <span style={{ verticalAlign: 'middle', display: 'inline-block', marginRight: 6 }}>
            <IconComponent size={18} color="#000" />
          </span>
        )}
        {showTentTree && (
          <span
            style={{ verticalAlign: 'middle', display: 'inline-block', marginRight: 6 }}
            title="Ferientage werden berücksichtigt"
          >
            <TentTree size={16} color="#000" />
          </span>
        )}
        <span style={{ marginTop: 3 }}>{event.Subject}</span>
      </div>
      <div style={{ fontSize: '0.95em', color: '#000', marginTop: -2 }}>{timeString}</div>
    </div>
  );
}

// Robust ISO date parsing: append 'Z' only if no timezone offset present
function parseEventDate(iso: string): Date {
  if (!iso) return new Date(NaN);
  // If string already contains 'Z' or a timezone offset like +00:00/-02:00, don't modify
  const hasTZ = /Z$/i.test(iso) || /[+-]\d{2}:\d{2}$/.test(iso);
  const s = hasTZ ? iso : `${iso}Z`;
  return new Date(s);
}

const Appointments: React.FC = () => {

  // Debug logging removed
    const [groups, setGroups] = useState<Group[]>([]);
    const [selectedGroupId, setSelectedGroupId] = useState<string | null>(null);
    const [events, setEvents] = useState<Event[]>([]);
  const [holidays, setHolidays] = useState<Holiday[]>([]);
  const [modalOpen, setModalOpen] = useState(false);
  const [modalInitialData, setModalInitialData] = useState({});
  // Removed schedulerKey remount mechanism; rely on refreshEvents()
  const [editMode, setEditMode] = useState(false); // NEU: Editiermodus
  const [showInactive, setShowInactive] = React.useState(true);
  const [allowScheduleOnHolidays, setAllowScheduleOnHolidays] = React.useState(false);
  const [showHolidayList, setShowHolidayList] = React.useState(true);
  // Always let Syncfusion handle recurrence; do not expand on backend
  // Remove expandRecurrences toggle and state
  const scheduleRef = React.useRef<ScheduleComponent | null>(null);
  const [holidaysInView, setHolidaysInView] = React.useState<number>(0);
  const [schoolYearLabel, setSchoolYearLabel] = React.useState<string>('');
  const [hasSchoolYearPlan, setHasSchoolYearPlan] = React.useState<boolean>(false);
  const [periods, setPeriods] = React.useState<{ id: number; label: string }[]>([]);
  const [activePeriodId, setActivePeriodId] = React.useState<number | null>(null);
  const getWeekMonday = (date: Date): Date => {
    const d = new Date(date);
    const day = d.getDay();
    const diffToMonday = (day + 6) % 7; // Monday = 0
    d.setDate(d.getDate() - diffToMonday);
    d.setHours(12, 0, 0, 0); // use noon to avoid TZ shifting back a day
    return d;
  };

  const [selectedDate, setSelectedDate] = useState<Date>(() => getWeekMonday(new Date()));
  const navigationSynced = useRef(false);
  
  
  // Confirmation dialog state
  const [confirmDialogOpen, setConfirmDialogOpen] = React.useState(false);
  const [confirmDialogData, setConfirmDialogData] = React.useState<{
    title: string;
    message: string;
    onConfirm: () => void;
    onCancel: () => void;
  } | null>(null);

  // Recurring deletion dialog state
  const [recurringDeleteDialogOpen, setRecurringDeleteDialogOpen] = React.useState(false);
  const [recurringDeleteData, setRecurringDeleteData] = React.useState<{
    event: Event;
    onChoice: (choice: 'series' | 'occurrence' | 'cancel') => void;
  } | null>(null);

  // Series deletion final confirmation dialog (after choosing 'series')
  const [seriesConfirmDialogOpen, setSeriesConfirmDialogOpen] = React.useState(false);
  const [seriesConfirmData, setSeriesConfirmData] = React.useState<{
    event: Event;
    onConfirm: () => void;
    onCancel: () => void;
  } | null>(null);

  const showSeriesConfirmDialog = (event: Event): Promise<boolean> => {
    return new Promise(resolve => {
      console.log('[Delete] showSeriesConfirmDialog invoked for event', event.Id);
      // Defer open to next tick to avoid race with closing previous dialog
      setSeriesConfirmData({
        event,
        onConfirm: () => {
          console.log('[Delete] Series confirm dialog: confirmed');
          setSeriesConfirmDialogOpen(false);
          resolve(true);
        },
        onCancel: () => {
          console.log('[Delete] Series confirm dialog: cancelled');
          setSeriesConfirmDialogOpen(false);
          resolve(false);
        }
      });
      setTimeout(() => {
        setSeriesConfirmDialogOpen(true);
      }, 0);
    });
  };

  // Helper function to show confirmation dialog
  const showConfirmDialog = (title: string, message: string): Promise<boolean> => {
    return new Promise((resolve) => {
      setConfirmDialogData({
        title,
        message,
        onConfirm: () => {
          setConfirmDialogOpen(false);
          resolve(true);
        },
        onCancel: () => {
          setConfirmDialogOpen(false);
          resolve(false);
        }
      });
      setConfirmDialogOpen(true);
    });
  };

  // Helper function to show recurring event deletion dialog
  const showRecurringDeleteDialog = (event: Event): Promise<'series' | 'occurrence' | 'cancel'> => {
    return new Promise((resolve) => {
      setRecurringDeleteData({
        event,
        onChoice: (choice: 'series' | 'occurrence' | 'cancel') => {
          setRecurringDeleteDialogOpen(false);
          resolve(choice);
        }
      });
      setRecurringDeleteDialogOpen(true);
    });
  };

  // Gruppen laden
  useEffect(() => {
    fetchGroups()
      .then(data => {
        // Nur Gruppen mit id != 1 berücksichtigen (nicht zugeordnet ignorieren)
        const filtered = Array.isArray(data) ? data.filter(g => g.id && g.name && g.id !== 1) : [];
        setGroups(filtered);
        if (filtered.length > 0) setSelectedGroupId(filtered[0].id);
      })
      .catch(console.error);
  }, []);

  // Perioden laden (Dropdown)
  useEffect(() => {
    listAcademicPeriods()
      .then(all => {
        setPeriods(all.map(p => ({ id: p.id, label: p.displayName || p.name })));
        const active = all.find(p => p.isActive);
        setActivePeriodId(active ? active.id : null);
      })
      .catch(err => console.error('Akademische Perioden laden fehlgeschlagen:', err));
  }, []);

  // Holidays passend zur aktiven akademischen Periode laden
  useEffect(() => {
    if (!activePeriodId) {
      setHolidays([]);
      return;
    }

    listHolidays(undefined, activePeriodId)
      .then(res => setHolidays(res.holidays || []))
      .catch(err => console.error('Ferien laden fehlgeschlagen:', err));
  }, [activePeriodId]);

  // fetchAndSetEvents als useCallback definieren, damit die Dependency korrekt ist:
  const fetchAndSetEvents = React.useCallback(async () => {
    if (!selectedGroupId) {
      setEvents([]);
      return;
    }
    try {
      // Sichtbaren Bereich bestimmen (optional, for future filtering)
      const inst = scheduleRef.current;
      let startRange: Date | undefined;
      let endRange: Date | undefined;
      // Fallback to current week if scheduler is not initialized yet
      const today = new Date();
      const fallbackStart = new Date(today);
      const day = today.getDay();
      const diffToMonday = (day + 6) % 7; // Monday=0
      fallbackStart.setDate(today.getDate() - diffToMonday);
      fallbackStart.setHours(0, 0, 0, 0);
      const fallbackEnd = new Date(fallbackStart);
      fallbackEnd.setDate(fallbackStart.getDate() + 6);
      fallbackEnd.setHours(23, 59, 59, 999);
      if (inst) {
        const view = inst.currentView as 'Day' | 'Week' | 'WorkWeek' | 'Month' | 'Agenda';
        const baseDate = inst.selectedDate as Date;
        if (baseDate) {
          if (view === 'Day' || view === 'Agenda') {
            startRange = new Date(baseDate);
            startRange.setHours(0, 0, 0, 0);
            endRange = new Date(baseDate);
            endRange.setHours(23, 59, 59, 999);
          } else if (view === 'Week' || view === 'WorkWeek') {
            const day = baseDate.getDay();
            const diffToMonday = (day + 6) % 7; // Monday=0
            startRange = new Date(baseDate);
            startRange.setDate(baseDate.getDate() - diffToMonday);
            startRange.setHours(0, 0, 0, 0);
            endRange = new Date(startRange);
            endRange.setDate(startRange.getDate() + 6);
            endRange.setHours(23, 59, 59, 999);
          } else if (view === 'Month') {
            startRange = new Date(baseDate.getFullYear(), baseDate.getMonth(), 1, 0, 0, 0, 0);
            endRange = new Date(baseDate.getFullYear(), baseDate.getMonth() + 1, 0, 23, 59, 59, 999);
          }
        }
      }
      if (!startRange || !endRange) {
        startRange = fallbackStart;
        endRange = fallbackEnd;
      }
      // Always request non-expanded events (expand=0)
      const data = await fetchEvents(selectedGroupId, showInactive, {
        start: startRange!,
        end: endRange!,
        expand: false,
      });
      // Manually expand recurring events and filter out EXDATE occurrences
      const expandedEvents: Event[] = [];
      
      for (const e of data) {
          if (e.recurrenceRule) {
          // Parse EXDATE list
          const exdates = new Set<string>();
          if (e.recurrenceException) {
            e.recurrenceException.split(',').forEach((dateStr: string) => {
              const trimmed = dateStr.trim();
              exdates.add(trimmed);
            });
          }
          
          // Let Syncfusion handle ALL recurrence patterns natively for proper badge display
          expandedEvents.push({
            Id: e.id,
            Subject: e.subject,
            StartTime: parseEventDate(e.startTime),
            EndTime: parseEventDate(e.endTime),
            IsAllDay: e.isAllDay,
            MediaId: e.mediaId,
            SlideshowInterval: e.slideshowInterval,
            PageProgress: e.pageProgress,
            AutoProgress: e.autoProgress,
            WebsiteUrl: e.websiteUrl,
            Autoplay: e.autoplay,
            Loop: e.loop,
            Volume: e.volume,
            Muted: e.muted,
            Icon: e.icon,
            Type: e.type,
            OccurrenceOfId: e.occurrenceOfId,
            Recurrence: true,
            RecurrenceRule: e.recurrenceRule,
            RecurrenceEnd: e.recurrenceEnd ?? null,
            SkipHolidays: e.skipHolidays ?? false,
            RecurrenceException: e.recurrenceException || undefined,
          });
        } else {
          // Non-recurring event - add as-is
          expandedEvents.push({
            Id: e.id,
            Subject: e.subject,
            StartTime: parseEventDate(e.startTime),
            EndTime: parseEventDate(e.endTime),
            IsAllDay: e.isAllDay,
            MediaId: e.mediaId,
            SlideshowInterval: e.slideshowInterval,
            PageProgress: e.pageProgress,
            AutoProgress: e.autoProgress,
            WebsiteUrl: e.websiteUrl,
            Autoplay: e.autoplay,
            Loop: e.loop,
            Volume: e.volume,
            Muted: e.muted,
            Icon: e.icon,
            Type: e.type,
            OccurrenceOfId: e.occurrenceOfId,
            Recurrence: false,
            RecurrenceRule: null,
            RecurrenceEnd: null,
            SkipHolidays: e.skipHolidays ?? false,
            RecurrenceException: undefined,
          });
        }
      }
      

      
      setEvents(expandedEvents);
    } catch (err) {
      console.error('Fehler beim Laden der Termine:', err);
    }
  }, [selectedGroupId, showInactive]);

  React.useEffect(() => {
    if (selectedGroupId) {
      // selectedGroupId kann null sein, fetchEvents erwartet aber string
      fetchAndSetEvents();
    } else {
      setEvents([]);
    }
  }, [selectedGroupId, showInactive, fetchAndSetEvents]);

  // Helper: prüfe, ob Zeitraum einen Feiertag/Ferienbereich schneidet
  const isWithinHolidayRange = React.useCallback(
    (start: Date, end: Date) => {
      // normalisiere Endzeit minimal (Syncfusion nutzt exklusive Enden in einigen Fällen)
      const adjEnd = new Date(end);
      // keine Änderung nötig – unsere eigenen Events sind präzise
      for (const h of holidays) {
        // Holiday dates are strings YYYY-MM-DD (local date)
        const hs = new Date(h.start_date + 'T00:00:00');
        const he = new Date(h.end_date + 'T23:59:59');
        if (
          (start >= hs && start <= he) ||
          (adjEnd >= hs && adjEnd <= he) ||
          (start <= hs && adjEnd >= he)
        ) {
          return true;
        }
      }
      return false;
    },
    [holidays]
  );

  // Baue Holiday-Anzeige-Events und Block-Events
  const holidayDisplayEvents: Event[] = useMemo(() => {
    if (!showHolidayList) return [];
    const out: Event[] = [];
    for (const h of holidays) {
      const start = new Date(h.start_date + 'T00:00:00');
      const end = new Date(h.end_date + 'T23:59:59');
      out.push({
        Id: `holiday-${h.id}-display`,
        Subject: h.name,
        StartTime: start,
        EndTime: end,
        IsAllDay: true,
        isHoliday: true,
      });
    }
    return out;
  }, [holidays, showHolidayList]);

  const holidayBlockEvents: Event[] = useMemo(() => {
    if (allowScheduleOnHolidays) return [];
    const out: Event[] = [];
    for (const h of holidays) {
      const start = new Date(h.start_date + 'T00:00:00');
      const end = new Date(h.end_date + 'T23:59:59');
      out.push({
        Id: `holiday-${h.id}-block`,
        Subject: h.name,
        StartTime: start,
        EndTime: end,
        IsAllDay: true,
        IsBlock: true,
        isHoliday: true,
      });
    }
    return out;
  }, [holidays, allowScheduleOnHolidays]);

  const dataSource = useMemo(() => {
    // Existing events should always be visible; holiday skipping for recurring events
    // is handled via RecurrenceException from the backend.
    return [...events, ...holidayDisplayEvents, ...holidayBlockEvents];
  }, [events, holidayDisplayEvents, holidayBlockEvents]);

  // Removed dataSource logging

  // Aktive akademische Periode für Datum aus dem Backend ermitteln
  const refreshAcademicPeriodFor = React.useCallback(
    async (baseDate: Date) => {
      try {
        const p = await getAcademicPeriodForDate(baseDate);
        if (!p) {
          setSchoolYearLabel('');
          setHasSchoolYearPlan(false);
          return;
        }
        // Anzeige: bevorzugt displayName, sonst name
        const label = p.displayName ? p.displayName : p.name;
        setSchoolYearLabel(label);
        // Existiert ein Ferienplan innerhalb der Periode?
        const start = new Date(p.startDate + 'T00:00:00');
        const end = new Date(p.endDate + 'T23:59:59');
        let exists = false;
        for (const h of holidays) {
          const hs = new Date(h.start_date + 'T00:00:00');
          const he = new Date(h.end_date + 'T23:59:59');
          if (hs <= end && he >= start) {
            exists = true;
            break;
          }
        }
        setHasSchoolYearPlan(exists);
      } catch (e) {
        console.error('Akademische Periode laden fehlgeschlagen:', e);
        setSchoolYearLabel('');
        setHasSchoolYearPlan(false);
      }
    },
    [holidays]
  );

  // Anzahl an Ferienzeiträumen in aktueller Ansicht ermitteln + Perioden-Indikator setzen
  const updateHolidaysInView = React.useCallback(() => {
    const inst = scheduleRef.current;
    if (!inst) {
      setHolidaysInView(0);
      return;
    }
    const view = inst.currentView as 'Day' | 'Week' | 'WorkWeek' | 'Month' | 'Agenda';
    const baseDate = inst.selectedDate as Date;
    if (!baseDate) {
      setHolidaysInView(0);
      return;
    }
    let rangeStart = new Date(baseDate);
    let rangeEnd = new Date(baseDate);
    if (view === 'Day' || view === 'Agenda') {
      rangeStart.setHours(0, 0, 0, 0);
      rangeEnd.setHours(23, 59, 59, 999);
    } else if (view === 'Week' || view === 'WorkWeek') {
      const day = baseDate.getDay();
      const diffToMonday = (day + 6) % 7; // Monday=0
      rangeStart = new Date(baseDate);
      rangeStart.setDate(baseDate.getDate() - diffToMonday);
      rangeStart.setHours(0, 0, 0, 0);
      rangeEnd = new Date(rangeStart);
      rangeEnd.setDate(rangeStart.getDate() + 6);
      rangeEnd.setHours(23, 59, 59, 999);
    } else if (view === 'Month') {
      rangeStart = new Date(baseDate.getFullYear(), baseDate.getMonth(), 1, 0, 0, 0, 0);
      rangeEnd = new Date(baseDate.getFullYear(), baseDate.getMonth() + 1, 0, 23, 59, 59, 999);
    }
    let count = 0;
    for (const h of holidays) {
      const hs = new Date(h.start_date + 'T00:00:00');
      const he = new Date(h.end_date + 'T23:59:59');
      const overlaps =
        (hs >= rangeStart && hs <= rangeEnd) ||
        (he >= rangeStart && he <= rangeEnd) ||
        (hs <= rangeStart && he >= rangeEnd);
      if (overlaps) count += 1;
    }
    setHolidaysInView(count);
    // Perioden-Indikator über Backend prüfen
    refreshAcademicPeriodFor(baseDate);
  }, [holidays, refreshAcademicPeriodFor]);

  // Aktualisiere Indikator wenn Ferien oder Ansicht (Key) wechseln
  React.useEffect(() => {
    updateHolidaysInView();
  }, [holidays, updateHolidaysInView]);

  // Inject global z-index fixes for dialogs (only once)
  React.useEffect(() => {
    if (typeof document !== 'undefined' && !document.getElementById('series-dialog-zfix')) {
      const style = document.createElement('style');
      style.id = 'series-dialog-zfix';
      style.textContent = `\n        .final-series-dialog.e-dialog { z-index: 25000 !important; }\n        .final-series-dialog + .e-dlg-overlay { z-index: 24990 !important; }\n        .recurring-delete-dialog.e-dialog { z-index: 24000 !important; }\n        .recurring-delete-dialog + .e-dlg-overlay { z-index: 23990 !important; }\n      `;
      document.head.appendChild(style);
    }
  }, []);

  React.useEffect(() => {
    if (seriesConfirmDialogOpen) {
      console.log('[Delete] Series confirm dialog now visible');
    }
  }, [seriesConfirmDialogOpen]);

  return (
    <div>
      <h1 style={{ fontSize: '1.5rem', fontWeight: 700, marginBottom: 16 }}>Terminmanagement</h1>
      <div
        style={{
          marginBottom: 16,
          display: 'flex',
          alignItems: 'center',
          gap: 16,
          flexWrap: 'wrap',
        }}
      >
        <label htmlFor="groupDropdown" className="mb-0 mr-2" style={{ whiteSpace: 'nowrap' }}>
          Raumgruppe auswählen:
        </label>
        <DropDownListComponent
          id="groupDropdown"
          dataSource={groups}
          fields={{ text: 'name', value: 'id' }}
          placeholder="Gruppe auswählen"
          value={selectedGroupId}
          width="240px"
          change={(e: { value: string }) => {
            // <--- Typ für e ergänzt
            setEvents([]); // Events sofort leeren
            setSelectedGroupId(e.value);
          }}
          style={{}}
        />

        {/* Akademische Periode Selector + Plan-Badge */}
        <span style={{ marginLeft: 8, whiteSpace: 'nowrap' }}>Periode:</span>
        <DropDownListComponent
          id="periodDropdown"
          dataSource={periods}
          fields={{ text: 'label', value: 'id' }}
          placeholder="Periode wählen"
          value={activePeriodId ?? undefined}
          width="260px"
          change={async (e: { value: number }) => {
            const id = Number(e.value);
            if (!id) return;
            if (activePeriodId === id) return; // avoid firing on initial mount
            try {
              const updated = await setActiveAcademicPeriod(id);
              setActivePeriodId(updated.id);
              // Zum gleichen Tag/Monat (heute) innerhalb der gewählten Periode springen
              const today = new Date();
              const targetYear = new Date(updated.startDate).getFullYear();
              const target = new Date(targetYear, today.getMonth(), today.getDate(), 12, 0, 0);
              if (scheduleRef.current) {
                scheduleRef.current.selectedDate = target;
                scheduleRef.current.dataBind?.();
              }
              setSelectedDate(target);
              updateHolidaysInView();
            } catch (err) {
              console.error('Aktive Periode setzen fehlgeschlagen:', err);
            }
          }}
          style={{}}
        />
        {/* School-year/period plan badge (adjacent) */}
        <span
          title={hasSchoolYearPlan ? 'Ferienplan ist hinterlegt' : 'Kein Ferienplan hinterlegt'}
          style={{
            background: hasSchoolYearPlan ? '#dcfce7' : '#f3f4f6',
            border: hasSchoolYearPlan ? '1px solid #86efac' : '1px solid #e5e7eb',
            color: '#000',
            padding: '4px 10px',
            borderRadius: 16,
            fontSize: 12,
            display: 'flex',
            alignItems: 'center',
            gap: 6,
          }}
        >
          {hasSchoolYearPlan ? (
            <CheckCircle size={14} color="#166534" />
          ) : (
            <AlertCircle size={14} color="#6b7280" />
          )}
          {schoolYearLabel || 'Periode'}
        </span>
      </div>
      <button
        className="e-btn e-success mb-4"
        onClick={() => {
          const now = new Date();
          // Runde auf die nächste halbe Stunde
          const minutes = now.getMinutes();
          const roundedMinutes = minutes < 30 ? 30 : 0;
          const startTime = new Date(now);
          startTime.setMinutes(roundedMinutes, 0, 0);
          if (roundedMinutes === 0) startTime.setHours(startTime.getHours() + 1);

          const endTime = new Date(startTime);
          endTime.setMinutes(endTime.getMinutes() + 30);

          setModalInitialData({
            startDate: startTime,
            startTime: startTime,
            endTime: endTime,
          });
          setEditMode(false);
          setModalOpen(true);
        }}
      >
        Neuen Termin anlegen
      </button>
      <div
        style={{
          display: 'flex',
          alignItems: 'center',
          gap: 24,
          marginBottom: 16,
          flexWrap: 'wrap',
        }}
      >
        <label>
          <input
            type="checkbox"
            checked={showInactive}
            onChange={e => setShowInactive(e.target.checked)}
            style={{ marginRight: 8 }}
          />
          Vergangene Termine anzeigen
        </label>
        <label>
          <input
            type="checkbox"
            checked={allowScheduleOnHolidays}
            onChange={e => setAllowScheduleOnHolidays(e.target.checked)}
            style={{ marginRight: 8 }}
          />
          Termine an Ferientagen erlauben
        </label>
        <label>
          <input
            type="checkbox"
            checked={showHolidayList}
            onChange={e => setShowHolidayList(e.target.checked)}
            style={{ marginRight: 8 }}
          />
          Ferien im Kalender anzeigen
        </label>
        {/* Removed expandRecurrences toggle: Syncfusion now always handles recurrence */}
        {/* Right-aligned indicators */}
        <div style={{ marginLeft: 'auto', display: 'flex', gap: 8, alignItems: 'center' }}>
          {/* Holidays-in-view badge */}
          <span
            title="Anzahl der Ferientage/-zeiträume in der aktuellen Ansicht"
            style={{
              background: holidaysInView > 0 ? '#ffe8cc' : '#f3f4f6',
              border: holidaysInView > 0 ? '1px solid #ffcf99' : '1px solid #e5e7eb',
              color: '#000',
              padding: '4px 10px',
              borderRadius: 16,
              fontSize: 12,
            }}
          >
            {holidaysInView > 0 ? `Ferien im Blick: ${holidaysInView}` : 'Keine Ferien in Ansicht'}
          </span>
        </div>
        {/* Removed expandRecurrences indicator: Syncfusion now always handles recurrence */}
      </div>
      <CustomEventModal
        open={modalOpen}
        onClose={() => {
          setModalOpen(false);
          setEditMode(false); // Editiermodus zurücksetzen
        }}
        onSave={async (eventData) => {
          console.log('Modal saved event data:', eventData);
          
          // The CustomEventModal already handled the API calls internally
          // For now, just refresh the data (the recurring event logic is handled in the modal itself)
          setModalOpen(false);
          setEditMode(false);
          
          // Refresh the data and scheduler
          await fetchAndSetEvents();
          
          // Defer refresh to avoid interfering with current React commit
          setTimeout(() => {
            scheduleRef.current?.refreshEvents?.();
          }, 0);
        }}
        initialData={modalInitialData}
        groupName={groups.find(g => g.id === selectedGroupId) ?? { id: selectedGroupId, name: '' }}
        groupColor={selectedGroupId ? getGroupColor(selectedGroupId, groups) : undefined}
        editMode={editMode} // NEU: Prop für Editiermodus
      />
      <ScheduleComponent
        key={`scheduler-${selectedDate.toISOString().slice(0, 10)}`}
        ref={scheduleRef}
        height="750px"
        locale="de"
        currentView="Week"
        firstDayOfWeek={1}
        enablePersistence={false}
        selectedDate={selectedDate}
        created={() => {
          const inst = scheduleRef.current;
          if (inst && selectedDate) {
            inst.selectedDate = selectedDate;
            inst.dataBind?.();
          }
        }}
        eventSettings={{
          dataSource: dataSource,
          fields: {
            id: 'Id',
            subject: 'Subject',
            startTime: 'StartTime',
            endTime: 'EndTime',
            isBlock: 'IsBlock',
            recurrenceID: 'RecurrenceID', // Map for proper series recognition
            recurrenceRule: 'RecurrenceRule',
            recurrenceException: 'RecurrenceException',
          },
          template: eventTemplate, // <--- Hier das Template setzen!
        }}
        actionComplete={async (args: ActionEventArgs) => {
          updateHolidaysInView();
          // Bei Navigation oder Viewwechsel Events erneut laden (für Range-basierte Expansion)
          if (args && (args.requestType === 'dateNavigate' || args.requestType === 'viewNavigate')) {
            if (!navigationSynced.current) {
              navigationSynced.current = true;
              if (scheduleRef.current && selectedDate) {
                scheduleRef.current.selectedDate = selectedDate;
                scheduleRef.current.dataBind?.();
              }
              return;
            }
            if (scheduleRef.current?.selectedDate) {
              setSelectedDate(new Date(scheduleRef.current.selectedDate));
            }
            fetchAndSetEvents();
            return;
          }

          // Persist UI-driven changes (drag/resize/editor fallbacks)
          if (args && args.requestType === 'eventChanged') {
            console.log('actionComplete: Processing eventChanged from direct UI interaction (drag/resize)');
            try {
              type SchedulerEvent = Partial<Event> & {
                Id?: string | number;
                OccurrenceOfId?: string | number;
                RecurrenceRule?: string | null;
                isHoliday?: boolean;
                IsBlock?: boolean;
                StartTime?: Date | string;
                EndTime?: Date | string;
                Subject?: string;
              };
              const raw = args.data as unknown;
              const changed = (Array.isArray(raw) ? raw[0] : raw) as SchedulerEvent | undefined;
              if (!changed) return;
              // Ignore holiday visuals and blocks
              if (changed.isHoliday || changed.IsBlock) return;

              // Build payload (only fields we can safely update here)
              const payload: Record<string, unknown> = {};
              if (changed.Subject) payload.title = changed.Subject;
              if (changed.StartTime) {
                const s = changed.StartTime instanceof Date ? changed.StartTime : new Date(changed.StartTime);
                payload.start = s.toISOString();
              }
              if (changed.EndTime) {
                const e = changed.EndTime instanceof Date ? changed.EndTime : new Date(changed.EndTime);
                payload.end = e.toISOString();
              }

              // Check if this is a single occurrence edit by looking at the original master event
              const eventId = String(changed.Id);
              
              // Debug logging to understand what Syncfusion sends
              console.log('actionComplete eventChanged - Debug info:', {
                eventId,
                changedRecurrenceRule: changed.RecurrenceRule,
                changedRecurrenceID: changed.RecurrenceID,
                changedStartTime: changed.StartTime,
                changedSubject: changed.Subject,
                payload,
                fullChangedObject: JSON.stringify(changed, null, 2)
              });
              
              // First, fetch the master event to check if it has a RecurrenceRule
              let masterEvent = null;
              let isMasterRecurring = false;
              try {
                masterEvent = await fetchEventById(eventId);
                isMasterRecurring = !!masterEvent.recurrenceRule;
                console.log('Master event info:', {
                  masterRecurrenceRule: masterEvent.recurrenceRule,
                  masterStartTime: masterEvent.startTime,
                  isMasterRecurring
                });
              } catch (err) {
                console.error('Failed to fetch master event:', err);
              }

              // KEY DETECTION: Syncfusion sets RecurrenceID when editing a single occurrence
              const hasRecurrenceID = 'RecurrenceID' in changed && !!(changed as Record<string, unknown>).RecurrenceID;
              
              // When dragging a single occurrence, Syncfusion may not provide RecurrenceID 
              // but it won't provide RecurrenceRule on the changed object
              const isRecurrenceRuleStripped = isMasterRecurring && !changed.RecurrenceRule;
              
              console.log('FINAL Edit detection:', {
                isMasterRecurring,
                hasRecurrenceID,
                isRecurrenceRuleStripped,
                masterHasRule: masterEvent?.RecurrenceRule ? 'YES' : 'NO',
                changedHasRule: changed.RecurrenceRule ? 'YES' : 'NO',
                decision: (hasRecurrenceID || isRecurrenceRuleStripped) ? 'DETACH' : 'UPDATE'
              });

              // SINGLE OCCURRENCE EDIT detection:
              // 1. RecurrenceID is set (explicit single occurrence marker)
              // 2. OR master has RecurrenceRule but changed object doesn't (stripped during single edit)
              if (isMasterRecurring && (hasRecurrenceID || isRecurrenceRuleStripped) && changed.StartTime) {
                // This is a single occurrence edit - detach it
                console.log('Detaching single occurrence...');
                const occStart = changed.StartTime instanceof Date ? changed.StartTime : new Date(changed.StartTime as string);
                const occDate = occStart.toISOString().split('T')[0];
                await detachEventOccurrence(Number(eventId), occDate, payload);
              } else {
                // This is a series edit or regular single event
                console.log('Updating event directly...');
                await updateEvent(eventId, payload);
              }

              // Refresh events and scheduler cache after persisting
              await fetchAndSetEvents();
              // Defer refresh to avoid React/Syncfusion DOM race
              setTimeout(() => {
                scheduleRef.current?.refreshEvents?.();
              }, 0);
            } catch (err) {
              console.error('Persisting geänderten Termin fehlgeschlagen:', err);
            }
            return;
          }

          // If events were created via built-in UI (rare, as we use custom modal), reload as fallback
          if (args && args.requestType === 'eventCreated') {
            await fetchAndSetEvents();
            setTimeout(() => {
              scheduleRef.current?.refreshEvents?.();
            }, 0);
          }
        }}
        cellClick={args => {
          if (!allowScheduleOnHolidays && isWithinHolidayRange(args.startTime, args.endTime)) {
            args.cancel = true;
            return; // block creation on holidays
          }
          // args.startTime und args.endTime sind Date-Objekte
          args.cancel = true; // Verhindert die Standardaktion
          setModalInitialData({
            startDate: args.startTime,
            startTime: args.startTime,
            endTime: args.endTime,
          });
          setEditMode(false); // NEU: kein Editiermodus
          setModalOpen(true);
        }}
        popupOpen={async args => {
          // Intercept Syncfusion's recurrence choice dialog (RecurrenceAlert) and replace with custom
          if (args.type === 'RecurrenceAlert') {
            // Prevent default Syncfusion dialog
            args.cancel = true;
            const event = args.data;
            console.log('[RecurrenceAlert] Intercepted for event', event?.Id);
            if (!event) return;

            // Show our custom recurring delete dialog
            const choice = await showRecurringDeleteDialog(event);
            let didDelete = false;
            try {
              if (choice === 'series') {
                const confirmed = await showSeriesConfirmDialog(event);
                if (confirmed) {
                  await deleteEvent(event.Id, true);
                  didDelete = true;
                }
              } else if (choice === 'occurrence') {
                const occurrenceDate = event.StartTime instanceof Date
                  ? event.StartTime.toISOString().split('T')[0]
                  : new Date(event.StartTime).toISOString().split('T')[0];
                // If this is the master being edited for a single occurrence, treat as occurrence delete
                if (event.OccurrenceOfId) {
                  await deleteEventOccurrence(event.OccurrenceOfId, occurrenceDate);
                } else {
                  await deleteEventOccurrence(event.Id, occurrenceDate);
                }
                didDelete = true;
              }
            } catch (e) {
              console.error('Fehler bei RecurrenceAlert Löschung:', e);
            }
            if (didDelete) {
              await fetchAndSetEvents();
              setTimeout(() => scheduleRef.current?.refreshEvents?.(), 0);
            }
            return; // handled
          }
          if (args.type === 'DeleteAlert') {
            // Handle delete confirmation directly here to avoid multiple dialogs
            args.cancel = true;
            const event = args.data;
            let didDelete = false;
            
            try {
              // 1) Single occurrence of a recurring event → delete occurrence only
              if (event.OccurrenceOfId && event.StartTime) {
                console.log('[Delete] Deleting single occurrence via OccurrenceOfId path', {
                  eventId: event.Id,
                  masterId: event.OccurrenceOfId,
                  start: event.StartTime
                });
                const occurrenceDate = event.StartTime instanceof Date
                  ? event.StartTime.toISOString().split('T')[0]
                  : new Date(event.StartTime).toISOString().split('T')[0];
                await deleteEventOccurrence(event.OccurrenceOfId, occurrenceDate);
                didDelete = true;
              }
              // 2) Recurring master event deletion → show deletion choice dialog
              else if (event.RecurrenceRule) {
                // For recurring events the RecurrenceAlert should have been intercepted.
                console.log('[DeleteAlert] Recurring event delete without RecurrenceAlert (fallback)');
                const confirmed = await showSeriesConfirmDialog(event);
                if (confirmed) {
                  await deleteEvent(event.Id, true);
                  didDelete = true;
                }
              }
              // 3) Single non-recurring event → delete normally with simple confirmation
              else {
                  console.log('Deleting single non-recurring event:', event.Id);
                  await deleteEvent(event.Id, false);
                  didDelete = true;
              }
              
              // Refresh events only if a deletion actually occurred
              if (didDelete) {
                await fetchAndSetEvents();
                setTimeout(() => {
                  scheduleRef.current?.refreshEvents?.();
                }, 0);
              }
              
            } catch (err) {
              console.error('Fehler beim Löschen:', err);
            }
            return; // Exit early for delete operations
          }
          
          if (args.type === 'Editor') {
            args.cancel = true;
            const event = args.data;

            
            // Determine if this is single occurrence editing
            let isSingleOccurrence = false;
            
            if (event.OccurrenceOfId) {
              // This is a manually expanded occurrence from a recurring series
              // Ask user if they want to edit single occurrence or entire series
              isSingleOccurrence = await showConfirmDialog(
                'Termin aus wiederholender Serie',
                'Dies ist ein Termin aus einer wiederholenden Serie.\n\nMöchten Sie nur diesen Termin bearbeiten oder die ganze Serie?'
              );
            } else if (event.RecurrenceRule) {
              // This is a recurring event - ask user what they want to edit
              isSingleOccurrence = await showConfirmDialog(
                'Wiederholender Termin',
                'Dies ist ein wiederholender Termin.\n\nMöchten Sie nur diesen Termin bearbeiten oder die ganze Serie?'
              );
            } else {
              // Regular single event
              isSingleOccurrence = false;
            }
            
            // Fetch master event data if editing entire series from an occurrence
            let eventDataToUse = event;
            if (event.OccurrenceOfId && !isSingleOccurrence) {
              try {
                const masterEventData = await fetchEventById(event.OccurrenceOfId);
                eventDataToUse = {
                  ...masterEventData,
                  // Keep the scheduler-specific properties from the occurrence
                  StartTime: parseEventDate(masterEventData.StartTime),
                  EndTime: parseEventDate(masterEventData.EndTime),
                };
              } catch (err) {
                console.error('Failed to load master event data:', err);
                // Fall back to occurrence data if master event can't be loaded
              }
            }

            let media = null;
            if (eventDataToUse.MediaId) {
              try {
                const mediaData = await fetchMediaById(eventDataToUse.MediaId);
                media = {
                  id: mediaData.id,
                  path: mediaData.file_path,
                  name: mediaData.name || mediaData.url,
                };
              } catch (err) {
                console.error('Fehler beim Laden der Mediainfos:', err);
              }
            }
            
            let repeat = false;
            let weekdays: number[] = [];
            let repeatUntil: Date | null = null;
            
            // Only parse recurrence info if editing the entire series (not a single occurrence)
            if (!isSingleOccurrence) {
              const rr = (eventDataToUse.RecurrenceRule as string) || '';
              if (rr && rr.includes('FREQ=WEEKLY')) {
                repeat = true;
                const m = rr.match(/BYDAY=([^;]+)/);
                if (m && m[1]) {
                  const map: Record<string, number> = { MO: 0, TU: 1, WE: 2, TH: 3, FR: 4, SA: 5, SU: 6 };
                  weekdays = m[1].split(',').map(s => map[s]).filter(v => v !== undefined);
                }
                const mu = rr.match(/UNTIL=([0-9TZ]+)/);
                if (mu && mu[1]) {
                  // UNTIL is UTC in yyyymmddThhmmssZ form; we take date part
                  const untilIso = mu[1]
                    .replace(/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/, '$1-$2-$3T$4:$5:$6Z');
                  repeatUntil = new Date(untilIso);
                } else if (eventDataToUse.RecurrenceEnd) {
                  repeatUntil = new Date(eventDataToUse.RecurrenceEnd);
                }
              }
            }

            // Fixed: Ensure OccurrenceOfId is set for recurring events in native recurrence mode

            const modalData = {
              Id: (event.OccurrenceOfId && !isSingleOccurrence) ? event.OccurrenceOfId : event.Id, // Use master ID for series edit, occurrence ID for single edit
              OccurrenceOfId: event.OccurrenceOfId || (event.RecurrenceRule ? event.Id : undefined), // Master event ID - use current ID if it's a recurring master
              occurrenceDate: isSingleOccurrence ? event.StartTime : null, // Store occurrence date for single occurrence editing
              isSingleOccurrence,
              title: eventDataToUse.Subject,
              startDate: eventDataToUse.StartTime,
              startTime: eventDataToUse.StartTime,
              endTime: eventDataToUse.EndTime,
              description: eventDataToUse.Description ?? '',
              type: eventDataToUse.Type ?? 'presentation',
              repeat: isSingleOccurrence ? false : repeat, // Disable recurrence for single occurrence
              weekdays: isSingleOccurrence ? [] : weekdays,
              repeatUntil: isSingleOccurrence ? null : repeatUntil,
              skipHolidays: isSingleOccurrence ? false : (eventDataToUse.SkipHolidays ?? false),
              media,
              slideshowInterval: eventDataToUse.SlideshowInterval ?? 10,
              pageProgress: eventDataToUse.PageProgress ?? true,
              autoProgress: eventDataToUse.AutoProgress ?? true,
              websiteUrl: eventDataToUse.WebsiteUrl ?? '',
              autoplay: eventDataToUse.Autoplay ?? true,
              loop: eventDataToUse.Loop ?? true,
              volume: eventDataToUse.Volume ?? 0.8,
              muted: eventDataToUse.Muted ?? false,
            };
            
            setModalInitialData(modalData);
            setEditMode(true);
            setModalOpen(true);
          }
        }}
        eventRendered={(args: EventRenderedArgs) => {

          if (selectedGroupId && args.data && args.data.Id) {
            const groupColor = getGroupColor(selectedGroupId, groups);
            const now = new Date();

            // Vergangene Termine: Raumgruppenfarbe
            if (args.data.EndTime && args.data.EndTime < now) {
              args.element.style.backgroundColor = groupColor ? `${groupColor}` : '#f3f3f3';
              args.element.style.color = '#000';
            } else if (groupColor) {
              args.element.style.backgroundColor = groupColor;
              args.element.style.color = '#000';
            }

            // Spezielle Darstellung für Ferienanzeige-Events
            if (args.data.isHoliday && !args.data.IsBlock) {
              args.element.style.backgroundColor = '#ffe8cc'; // sanftes Orange
              args.element.style.border = '1px solid #ffcf99';
              args.element.style.color = '#000';
            }
            // Gleiche Darstellung für Ferien-Block-Events
            if (args.data.isHoliday && args.data.IsBlock) {
              args.element.style.backgroundColor = '#ffe8cc';
              args.element.style.border = '1px solid #ffcf99';
              args.element.style.color = '#000';
            }
          }
        }}
        actionBegin={async (args: ActionEventArgs) => {
          // Delete operations are now handled in popupOpen to avoid multiple dialogs
          if (args.requestType === 'eventRemove') {
            // Cancel all delete operations here - they're handled in popupOpen
            args.cancel = true;
            return;
          }
          
          if (
            (args.requestType === 'eventCreate' || args.requestType === 'eventChange') &&
            !allowScheduleOnHolidays
          ) {
            // Verhindere Erstellen/Ändern in Ferienbereichen (Failsafe, falls eingebauter Editor genutzt wird)
            type PartialEventLike = { StartTime?: Date | string; EndTime?: Date | string };
            const raw = (args as ActionEventArgs).data as
              | PartialEventLike
              | PartialEventLike[]
              | undefined;
            const data = Array.isArray(raw) ? raw[0] : raw;
            if (data && data.StartTime && data.EndTime) {
              const s = data.StartTime instanceof Date ? data.StartTime : new Date(data.StartTime);
              const e = data.EndTime instanceof Date ? data.EndTime : new Date(data.EndTime);
              if (isWithinHolidayRange(s, e)) {
                args.cancel = true;
                return;
              }
            }
          }
        }}
        renderCell={(args: RenderCellEventArgs) => {
          // Nur für Arbeitszellen (Stunden-/Tageszellen)
          if (args.elementType === 'workCells') {
            const now = new Date();
            // args.element ist vom Typ Element, daher als HTMLElement casten:
            const cell = args.element as HTMLElement;
            if (args.date && args.date < now) {
              cell.style.backgroundColor = '#fff9e3'; // Hellgelb für Vergangenheit
              cell.style.opacity = '0.7';
            }
          }
        }}
      >
        <ViewsDirective>
          <ViewDirective option="Day" />
          <ViewDirective option="Week" />
          <ViewDirective option="WorkWeek" />
          <ViewDirective option="Month" />
          <ViewDirective option="Agenda" />
        </ViewsDirective>
        <Inject services={[Day, Week, WorkWeek, Month, Agenda]} />
      </ScheduleComponent>
      
      {/* Confirmation Dialog */}
      {confirmDialogData && (
        <DialogComponent
          target="#root"
          visible={confirmDialogOpen}
          width="500px"
          header={confirmDialogData.title}
          showCloseIcon={true}
          close={() => {
            setConfirmDialogOpen(false);
            confirmDialogData.onCancel();
          }}
          isModal={true}
          footerTemplate={() => (
            <div className="flex gap-2 justify-end">
              <button 
                className="e-btn e-primary" 
                onClick={confirmDialogData.onConfirm}
              >
                Einzeltermin bearbeiten
              </button>
              <button 
                className="e-btn e-normal" 
                onClick={confirmDialogData.onCancel}
              >
                Serie bearbeiten
              </button>
            </div>
          )}
        >
          <div style={{ padding: '20px', whiteSpace: 'pre-line', fontSize: '14px' }}>
            {confirmDialogData.message}
          </div>
        </DialogComponent>
      )}

      {/* Recurring Event Deletion Dialog */}
      {recurringDeleteDialogOpen && recurringDeleteData && (
        <DialogComponent
          target="#root"
          visible={recurringDeleteDialogOpen}
          width="500px"
          zIndex={18000}
          cssClass="recurring-delete-dialog"
          header={() => (
            <div style={{ 
              padding: '12px 20px',
              background: '#dc3545',
              color: 'white',
              fontWeight: 600,
              borderRadius: '6px 6px 0 0'
            }}>
              🗑️ Wiederkehrenden Termin löschen
            </div>
          )}
          showCloseIcon={true}
          close={() => recurringDeleteData.onChoice('cancel')}
          isModal={true}
          footerTemplate={() => (
            <div style={{ padding: '12px 20px', display: 'flex', gap: '12px', justifyContent: 'flex-end' }}>
              <button 
                className="e-btn e-outline"
                onClick={() => recurringDeleteData.onChoice('cancel')}
                style={{ minWidth: '100px' }}
              >
                Abbrechen
              </button>
              <button 
                className="e-btn e-warning"
                onClick={() => recurringDeleteData.onChoice('occurrence')}
                style={{ minWidth: '140px' }}
              >
                Nur diesen Termin
              </button>
              <button 
                className="e-btn e-danger"
                onClick={() => recurringDeleteData.onChoice('series')}
                style={{ minWidth: '140px' }}
              >
                Gesamte Serie
              </button>
            </div>
          )}
        >
          <div style={{ padding: '24px', fontSize: '14px', lineHeight: 1.5 }}>
            <div style={{ marginBottom: '16px', fontSize: '16px', fontWeight: 500 }}>
              Sie möchten einen wiederkehrenden Termin löschen:
            </div>
            <div style={{ 
              background: '#f8f9fa',
              border: '1px solid #e9ecef',
              borderRadius: '6px',
              padding: '12px',
              marginBottom: '20px',
              fontWeight: 500
            }}>
              📅 {recurringDeleteData.event.Subject}
            </div>
            
            <div style={{ marginBottom: '16px' }}>
              <strong>Was möchten Sie löschen?</strong>
            </div>
            
            <div style={{ marginBottom: '12px' }}>
              <div style={{ display: 'flex', alignItems: 'flex-start', gap: '8px' }}>
                <span style={{ color: '#fd7e14', fontSize: '16px' }}>📝</span>
                <div>
                  <strong>Nur diesen Termin:</strong> Löscht nur den ausgewählten Termin. Die anderen Termine der Serie bleiben bestehen.
                </div>
              </div>
            </div>
            
            <div style={{ marginBottom: '20px' }}>
              <div style={{ display: 'flex', alignItems: 'flex-start', gap: '8px' }}>
                <span style={{ color: '#dc3545', fontSize: '16px' }}>⚠️</span>
                <div>
                  <strong>Gesamte Serie:</strong> Löscht <u>alle Termine</u> dieser Wiederholungsserie. Diese Aktion kann nicht rückgängig gemacht werden!
                </div>
              </div>
            </div>
          </div>
        </DialogComponent>
      )}

      {/* Final Series Deletion Confirmation Dialog */}
      {seriesConfirmDialogOpen && seriesConfirmData && (
        <DialogComponent
          target="#root"
          visible={seriesConfirmDialogOpen}
          width="520px"
          zIndex={19000}
          cssClass="final-series-dialog"
          header={() => (
            <div style={{
              padding: '12px 20px',
              background: '#b91c1c',
              color: 'white',
              fontWeight: 600,
              borderRadius: '6px 6px 0 0'
            }}>
              ⚠️ Serie endgültig löschen
            </div>
          )}
          showCloseIcon={true}
          close={() => seriesConfirmData.onCancel()}
          isModal={true}
          footerTemplate={() => (
            <div style={{ padding: '12px 20px', display: 'flex', gap: '12px', justifyContent: 'flex-end' }}>
              <button
                className="e-btn e-outline"
                onClick={seriesConfirmData.onCancel}
                style={{ minWidth: '110px' }}
              >
                Abbrechen
              </button>
              <button
                className="e-btn e-danger"
                onClick={seriesConfirmData.onConfirm}
                style={{ minWidth: '180px' }}
              >
                Serie löschen
              </button>
            </div>
          )}
        >
          <div style={{ padding: '24px', fontSize: '14px', lineHeight: 1.55 }}>
            <div style={{ marginBottom: '14px' }}>
              Sie sind dabei die <strong>gesamte Terminserie</strong> zu löschen:
            </div>
            <div style={{
              background: '#fef2f2',
              border: '1px solid #fecaca',
              borderRadius: 6,
              padding: '10px 14px',
              marginBottom: 18,
              fontWeight: 500
            }}>
              📅 {seriesConfirmData.event.Subject}
            </div>
            <ul style={{ margin: '0 0 18px 18px', padding: 0 }}>
              <li>Alle zukünftigen und vergangenen Vorkommen werden entfernt.</li>
              <li>Dieser Vorgang kann nicht rückgängig gemacht werden.</li>
              <li>Einzelne bereits abgetrennte Einzeltermine bleiben bestehen.</li>
            </ul>
            <div style={{
              background: '#fff7ed',
              border: '1px solid #ffedd5',
              borderRadius: 6,
              padding: '10px 14px',
              fontSize: 13
            }}>
              Wenn Sie nur einen einzelnen Termin entfernen möchten, schließen Sie diesen Dialog und wählen Sie im vorherigen Dialog "Nur diesen Termin".
            </div>
          </div>
        </DialogComponent>
      )}
    </div>
  );
};

export default Appointments;
