import React from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Theme } from '@tamagui/core';
import { Image as ImageIcon, RefreshCcw, UploadCloud, Trash2, ChevronDown, Save, Droplets, Lock, X } from 'lucide-react';
import { YStack, XStack } from '@tamagui/stacks';
import { SizableText as Text } from '@tamagui/text';
import { Pressable } from '@tamagui/react-native-web-lite';
import { Slider, Tabs } from 'tamagui';
import { MobileShell, HeaderActionButton } from './components/MobileShell';
import { MobileCard, CTAButton, SkeletonCard } from './components/Primitives';
import { MobileColorInput, MobileField, MobileFileInput, MobileInput, MobileSelect, MobileTextArea } from './components/FormControls';
import { TenantEvent, getEvent, updateEvent, getTenantFonts, getTenantSettings, TenantFont, WatermarkSettings, trackOnboarding } from '../api';
import { isAuthError } from '../auth/tokens';
import { ApiError, getApiErrorMessage } from '../lib/apiError';
import { isBrandingAllowed, isWatermarkAllowed, isWatermarkRemovalAllowed } from '../lib/events';
import { MobileSheet } from './components/Sheet';
import toast from 'react-hot-toast';
import { adminPath } from '../constants';
import { useBackNavigation } from './hooks/useBackNavigation';
import { ADMIN_GRADIENTS, useAdminTheme } from './theme';
import { ContextHelpLink } from './components/ContextHelpLink';
import { extractBrandingForm, type BrandingFormValues } from '../lib/brandingForm';
import { DEFAULT_EVENT_BRANDING } from '@/guest/context/EventBrandingContext';
import { getContrastingTextColor, relativeLuminance } from '@/guest/lib/color';

const BRANDING_FORM_DEFAULTS = {
  primary: DEFAULT_EVENT_BRANDING.primaryColor,
  accent: DEFAULT_EVENT_BRANDING.secondaryColor,
  background: DEFAULT_EVENT_BRANDING.backgroundColor,
  surface: DEFAULT_EVENT_BRANDING.palette?.surface ?? DEFAULT_EVENT_BRANDING.backgroundColor,
  headingFont: DEFAULT_EVENT_BRANDING.typography?.heading ?? DEFAULT_EVENT_BRANDING.fontFamily ?? '',
  bodyFont: DEFAULT_EVENT_BRANDING.typography?.body ?? DEFAULT_EVENT_BRANDING.fontFamily ?? '',
  mode: DEFAULT_EVENT_BRANDING.mode ?? 'auto',
  buttonStyle: DEFAULT_EVENT_BRANDING.buttons?.style ?? 'filled',
  buttonRadius: DEFAULT_EVENT_BRANDING.buttons?.radius ?? 12,
  buttonPrimary: DEFAULT_EVENT_BRANDING.buttons?.primary ?? DEFAULT_EVENT_BRANDING.primaryColor,
  buttonSecondary: DEFAULT_EVENT_BRANDING.buttons?.secondary ?? DEFAULT_EVENT_BRANDING.secondaryColor,
  linkColor: DEFAULT_EVENT_BRANDING.buttons?.linkColor ?? DEFAULT_EVENT_BRANDING.secondaryColor,
  welcomeMessage: '',
  fontSize: DEFAULT_EVENT_BRANDING.typography?.sizePreset ?? 'm',
  logoMode: DEFAULT_EVENT_BRANDING.logo?.mode ?? 'emoticon',
  logoPosition: DEFAULT_EVENT_BRANDING.logo?.position ?? 'left',
  logoSize: DEFAULT_EVENT_BRANDING.logo?.size ?? 'm',
};

const buildBrandingFormBase = (defaults: typeof BRANDING_FORM_DEFAULTS): BrandingFormValues => ({
  ...defaults,
  logoDataUrl: '',
  logoValue: '',
});

const FONT_SIZE_SCALE: Record<BrandingFormValues['fontSize'], number> = {
  s: 0.94,
  m: 1,
  l: 1.08,
};

const LOGO_SIZE_PREVIEW: Record<BrandingFormValues['logoSize'], number> = {
  s: 28,
  m: 36,
  l: 44,
};

const resolveBrandingDefaults = (tenantBranding: BrandingFormValues | null) => {
  if (!tenantBranding) {
    return BRANDING_FORM_DEFAULTS;
  }

  const primary = tenantBranding.primary.trim() ? tenantBranding.primary : BRANDING_FORM_DEFAULTS.primary;
  const accent = tenantBranding.accent.trim() ? tenantBranding.accent : BRANDING_FORM_DEFAULTS.accent;
  const background = tenantBranding.background.trim() ? tenantBranding.background : BRANDING_FORM_DEFAULTS.background;
  const surface = tenantBranding.surface.trim() ? tenantBranding.surface : BRANDING_FORM_DEFAULTS.surface;
  const headingFont = tenantBranding.headingFont.trim()
    ? tenantBranding.headingFont
    : BRANDING_FORM_DEFAULTS.headingFont;
  const bodyFont = tenantBranding.bodyFont.trim()
    ? tenantBranding.bodyFont
    : BRANDING_FORM_DEFAULTS.bodyFont;
  const welcomeMessage = tenantBranding.welcomeMessage?.trim()
    ? tenantBranding.welcomeMessage
    : BRANDING_FORM_DEFAULTS.welcomeMessage;

  return {
    ...BRANDING_FORM_DEFAULTS,
    primary,
    accent,
    background,
    surface,
    headingFont,
    bodyFont,
    fontSize: tenantBranding.fontSize ?? BRANDING_FORM_DEFAULTS.fontSize,
    mode: tenantBranding.mode ?? BRANDING_FORM_DEFAULTS.mode,
    buttonPrimary: primary,
    buttonSecondary: accent,
    linkColor: accent,
    welcomeMessage,
  };
};

type WatermarkPosition =
  | 'top-left'
  | 'top-center'
  | 'top-right'
  | 'middle-left'
  | 'center'
  | 'middle-right'
  | 'bottom-left'
  | 'bottom-center'
  | 'bottom-right';

type WatermarkForm = {
  mode: 'base' | 'custom' | 'off';
  assetPath: string;
  assetDataUrl: string;
  assetPreviewUrl: string;
  position: WatermarkPosition;
  opacity: number;
  scale: number;
  padding: number;
  offsetX: number;
  offsetY: number;
};

type TabKey = 'branding' | 'watermark';

export default function MobileBrandingPage() {
  const { slug: slugParam } = useParams<{ slug?: string }>();
  const slug = slugParam ?? null;
  const navigate = useNavigate();
  const { t } = useTranslation('management');
  const { textStrong, muted, subtle, border, primary, accentSoft, danger, surfaceMuted, surface } = useAdminTheme();

  const [event, setEvent] = React.useState<TenantEvent | null>(null);
  const [form, setForm] = React.useState<BrandingFormValues>(() => buildBrandingFormBase(BRANDING_FORM_DEFAULTS));
  const [watermarkForm, setWatermarkForm] = React.useState<WatermarkForm>({
    mode: 'base',
    assetPath: '',
    assetDataUrl: '',
    assetPreviewUrl: '',
    position: 'bottom-right',
    opacity: 0.25,
    scale: 0.2,
    padding: 16,
    offsetX: 0,
    offsetY: 0,
  });
  const [activeTab, setActiveTab] = React.useState<TabKey>('branding');
  const [loading, setLoading] = React.useState(true);
  const [saving, setSaving] = React.useState(false);
  const [error, setError] = React.useState<string | null>(null);
  const [showFontsSheet, setShowFontsSheet] = React.useState(false);
  const [fontField, setFontField] = React.useState<'heading' | 'body'>('heading');
  const back = useBackNavigation(slug ? adminPath(`/mobile/events/${slug}`) : adminPath('/mobile/events'));
  const [fonts, setFonts] = React.useState<TenantFont[]>([]);
  const [fontsLoading, setFontsLoading] = React.useState(false);
  const [fontsLoaded, setFontsLoaded] = React.useState(false);
  const [tenantBranding, setTenantBranding] = React.useState<BrandingFormValues | null>(null);
  const [tenantBrandingLoaded, setTenantBrandingLoaded] = React.useState(false);
  const [formInitialized, setFormInitialized] = React.useState(false);
  const resolvedDefaults = React.useMemo(() => resolveBrandingDefaults(tenantBranding), [tenantBranding]);

  React.useEffect(() => {
    if (!slug) return;
    (async () => {
      setFormInitialized(false);
      setLoading(true);
      try {
        const data = await getEvent(slug);
        if (!data) {
          setLoading(false);
          return;
        }
        setEvent(data);
        setWatermarkForm(extractWatermark(data));
        setError(null);
      } catch (err) {
        if (!isAuthError(err)) {
          setError(getApiErrorMessage(err, t('events.errors.loadFailed', 'Branding konnte nicht geladen werden.')));
        }
      } finally {
        setLoading(false);
      }
    })();
  }, [slug, t]);

  React.useEffect(() => {
    if (!event || !tenantBrandingLoaded || formInitialized) return;
    setForm(extractBrandingForm(event.settings ?? {}, resolvedDefaults));
    setFormInitialized(true);
  }, [event, tenantBrandingLoaded, formInitialized, resolvedDefaults]);

  React.useEffect(() => {
    if (!showFontsSheet || fontsLoaded) return;
    setFontsLoading(true);
    getTenantFonts()
      .then((data) => setFonts(data ?? []))
      .catch(() => undefined)
      .finally(() => {
        setFontsLoading(false);
        setFontsLoaded(true);
      });
  }, [showFontsSheet, fontsLoaded]);

  React.useEffect(() => {
    if (tenantBrandingLoaded) return;
    let active = true;
    getTenantSettings()
      .then((payload) => {
        if (!active || !payload) return;
        setTenantBranding(extractBrandingForm(payload.settings ?? {}, BRANDING_FORM_DEFAULTS));
      })
      .catch(() => undefined)
      .finally(() => {
        if (active) {
          setTenantBrandingLoaded(true);
        }
      });

    return () => {
      active = false;
    };
  }, [tenantBrandingLoaded]);

  const previewForm = form;
  const previewBackground = previewForm.background;
  const previewSurfaceCandidate = previewForm.surface || previewBackground;
  const backgroundLuminance = relativeLuminance(previewBackground);
  const surfaceLuminance = relativeLuminance(previewSurfaceCandidate);
  const previewSurface = Math.abs(surfaceLuminance - backgroundLuminance) < 0.06
    ? backgroundLuminance >= 0.6
      ? '#ffffff'
      : '#0f172a'
    : previewSurfaceCandidate;
  const previewForeground = backgroundLuminance >= 0.6 ? '#1f2937' : '#f8fafc';
  const previewMutedForeground = backgroundLuminance >= 0.6 ? '#6b7280' : '#cbd5e1';
  const previewBorder = backgroundLuminance >= 0.6 ? '#e6d9d6' : '#334155';
  const previewTitle = event ? renderName(event.name) : t('events.placeholders.untitled', 'Unbenanntes Event');
  const previewHeadingFont = previewForm.headingFont || DEFAULT_EVENT_BRANDING.typography?.heading || DEFAULT_EVENT_BRANDING.fontFamily;
  const previewBodyFont = previewForm.bodyFont || DEFAULT_EVENT_BRANDING.typography?.body || DEFAULT_EVENT_BRANDING.fontFamily;
  const previewSurfaceText = previewForeground;
  const previewScale = FONT_SIZE_SCALE[previewForm.fontSize] ?? 1;
  const previewButtonColor = previewForm.buttonPrimary || previewForm.primary;
  const previewButtonText = getContrastingTextColor(previewButtonColor, '#ffffff', '#0f172a');
  const previewLogoSize = LOGO_SIZE_PREVIEW[previewForm.logoSize] ?? 36;
  const previewLogoUrl = previewForm.logoMode === 'upload' ? previewForm.logoDataUrl : '';
  const previewLogoValue = previewForm.logoMode === 'emoticon' ? previewForm.logoValue : '';
  const previewInitials = getInitials(previewTitle);
  const previewWelcomeTemplate = previewForm.welcomeMessage.trim()
    ? previewForm.welcomeMessage.trim()
    : t('events.branding.welcomeMessageFallback', 'Willkommen bei {eventName}.');
  const previewWelcomeMessage = previewWelcomeTemplate
    .replace('{eventName}', previewTitle)
    .replace('{name}', t('events.branding.welcomeGuestFallback', 'Gast'));
  const previewThemeName = previewForm.mode === 'dark' ? 'guestNight' : 'guestLight';
  const previewIsDark = previewThemeName === 'guestNight';
  const previewVariables = {
    '--guest-primary': previewForm.primary,
    '--guest-secondary': previewForm.accent,
    '--guest-background': previewBackground,
    '--guest-surface': previewSurface,
    '--guest-font-scale': String(previewScale),
    '--guest-body-font': previewBodyFont,
    '--guest-heading-font': previewHeadingFont,
    '--guest-button-radius': `${previewForm.buttonRadius}px`,
    '--guest-radius': `${previewForm.buttonRadius}px`,
    '--guest-link': previewForm.linkColor,
  } as React.CSSProperties;
  const previewAmbient = previewIsDark
    ? 'radial-gradient(circle at 18% 12%, rgba(255, 110, 110, 0.22), transparent 46%), radial-gradient(circle at 82% 18%, rgba(78, 205, 196, 0.18), transparent 44%), linear-gradient(180deg, rgba(6, 9, 20, 0.96), rgba(10, 14, 28, 1))'
    : 'radial-gradient(circle at 18% 12%, color-mix(in oklab, var(--guest-primary, #FF6B6B) 24%, white), transparent 50%), radial-gradient(circle at 82% 18%, color-mix(in oklab, var(--guest-secondary, #4ECDC4) 20%, white), transparent 48%), linear-gradient(180deg, color-mix(in oklab, var(--guest-background, #FFF5F5) 96%, white), color-mix(in oklab, var(--guest-background, #FFF5F5) 72%, white))';
  const previewSurfaceShadow = previewIsDark
    ? '0 18px 32px rgba(2, 6, 23, 0.55)'
    : '0 16px 28px rgba(15, 23, 42, 0.15)';
  const previewIconSurface = previewIsDark ? 'rgba(255, 255, 255, 0.12)' : 'rgba(15, 23, 42, 0.08)';
  const watermarkAllowed = isWatermarkAllowed(event ?? null);
  const watermarkRemovalAllowed = isWatermarkRemovalAllowed(event ?? null);
  const brandingAllowed = isBrandingAllowed(event ?? null);
  const customWatermarkAllowed = watermarkAllowed && brandingAllowed;
  const watermarkLocked = watermarkAllowed && !brandingAllowed;
  const brandingDisabled = !brandingAllowed;

  React.useEffect(() => {
    setWatermarkForm((prev) => {
      if (prev.mode === 'custom' && !customWatermarkAllowed) {
        return { ...prev, mode: 'base' };
      }
      if (prev.mode === 'off' && !watermarkRemovalAllowed) {
        return { ...prev, mode: 'base' };
      }
      return prev;
    });
  }, [customWatermarkAllowed, watermarkRemovalAllowed]);

  async function handleSave() {
    if (!event?.slug) return;
    setSaving(true);
    setError(null);
    try {
      if (watermarkAllowed && brandingAllowed && watermarkForm.mode === 'custom' && !watermarkForm.assetDataUrl && !watermarkForm.assetPath) {
        const msg = t('events.watermark.errors.noAsset', 'Bitte lade zuerst ein Wasserzeichen hoch.');
        setError(msg);
        setActiveTab('watermark');
        setSaving(false);
        return;
      }

      const settings = { ...(event.settings ?? {}) };
      const logoUploadValue = form.logoMode === 'upload' ? form.logoDataUrl.trim() : '';
      const logoIsDataUrl = logoUploadValue.startsWith('data:image/');
      const normalizedLogoPath = logoIsDataUrl ? '' : normalizeBrandingPath(logoUploadValue);
      const logoValue = form.logoMode === 'upload'
        ? (logoIsDataUrl ? logoUploadValue : normalizedLogoPath || null)
        : (form.logoValue.trim() || null);

      settings.branding = {
        ...(typeof settings.branding === 'object' ? (settings.branding as Record<string, unknown>) : {}),
        primary_color: form.primary,
        secondary_color: form.accent,
        accent_color: form.accent,
        background_color: form.background,
        surface_color: form.surface,
        font_family: form.bodyFont,
        heading_font: form.headingFont,
        body_font: form.bodyFont,
        font_size: form.fontSize,
        mode: form.mode,
        button_style: form.buttonStyle,
        button_radius: form.buttonRadius,
        button_primary_color: form.buttonPrimary,
        button_secondary_color: form.buttonSecondary,
        link_color: form.linkColor,
        typography: {
          ...(typeof (settings.branding as Record<string, unknown> | undefined)?.typography === 'object'
            ? ((settings.branding as Record<string, unknown>).typography as Record<string, unknown>)
            : {}),
          heading: form.headingFont,
          body: form.bodyFont,
          size: form.fontSize,
        },
        palette: {
          ...(typeof (settings.branding as Record<string, unknown> | undefined)?.palette === 'object'
            ? ((settings.branding as Record<string, unknown>).palette as Record<string, unknown>)
            : {}),
          primary: form.primary,
          secondary: form.accent,
          background: form.background,
          surface: form.surface,
        },
        buttons: {
          ...(typeof (settings.branding as Record<string, unknown> | undefined)?.buttons === 'object'
            ? ((settings.branding as Record<string, unknown>).buttons as Record<string, unknown>)
            : {}),
          style: form.buttonStyle,
          radius: form.buttonRadius,
          primary: form.buttonPrimary,
          secondary: form.buttonSecondary,
          link_color: form.linkColor,
        },
        welcome_message: form.welcomeMessage.trim() ? form.welcomeMessage.trim() : null,
        logo_data_url: form.logoMode === 'upload' && logoIsDataUrl ? logoUploadValue : null,
        logo_url: form.logoMode === 'upload' ? (normalizedLogoPath || null) : null,
        logo_mode: form.logoMode,
        logo_value: logoValue,
        logo_position: form.logoPosition,
        logo_size: form.logoSize,
        logo: {
          mode: form.logoMode,
          value: logoValue,
          position: form.logoPosition,
          size: form.logoSize,
        },
      };
      const watermarkPayload = buildWatermarkPayload(
        watermarkForm,
        watermarkAllowed,
        brandingAllowed,
        watermarkRemovalAllowed
      );
      if (watermarkPayload) {
        settings.watermark = watermarkPayload;
      }
      const updated = await updateEvent(event.slug, { settings });
      setEvent(updated);
      setWatermarkForm(extractWatermark(updated));
      void trackOnboarding('branding_configured', { event_id: updated.id });
      toast.success(t('events.branding.saveSuccess', 'Branding gespeichert'));
    } catch (err) {
      if (!isAuthError(err)) {
        let message = getApiErrorMessage(err, t('events.errors.saveFailed', 'Branding konnte nicht gespeichert werden.'));
        if (err instanceof ApiError && err.meta?.errors && typeof err.meta.errors === 'object') {
          const allErrors = Object.values(err.meta.errors as Record<string, unknown>)
            .flat()
            .filter((val): val is string => typeof val === 'string');
          if (allErrors.length) {
            message = allErrors.join('\n');
          }
        }
        setError(message);
        toast.error(message, { duration: 5000 });
      }
    } finally {
      setSaving(false);
    }
  }

  function handleReset() {
    if (event) {
      setForm(extractBrandingForm(event.settings ?? {}, resolvedDefaults));
      setWatermarkForm(extractWatermark(event));
    }
  }

  function renderWatermarkTab() {
    const controlsLocked = watermarkLocked;
    const mode = controlsLocked ? 'base' : watermarkForm.mode;
    const resolvedMode = mode === 'custom' && !customWatermarkAllowed
      ? 'base'
      : mode === 'off' && !watermarkRemovalAllowed
        ? 'base'
        : mode;
    const customizationDisabled = controlsLocked || resolvedMode !== 'custom';

    return (
      <>
        <MobileCard gap="$3">
          <Text fontSize="$sm" fontWeight="700" color={textStrong}>
            {t('events.watermark.previewTitle', 'Watermark Preview')}
          </Text>
          <WatermarkPreview
            position={watermarkForm.position}
            scale={watermarkForm.scale}
            opacity={watermarkForm.opacity}
            padding={watermarkForm.padding}
            offsetX={watermarkForm.offsetX}
            offsetY={watermarkForm.offsetY}
            previewUrl={resolvedMode === 'off' ? '' : watermarkForm.assetDataUrl || watermarkForm.assetPreviewUrl}
            previewAlt={t('events.watermark.previewAlt', 'Watermark preview')}
          />
        </MobileCard>

        {!watermarkAllowed ? (
          <UpgradeCard
            title={t('events.watermark.lockedTitle', 'Unlock watermarks')}
            body={t('events.watermark.lockedBody', 'Custom watermarks are available with the Premium package.')}
            actionLabel={t('events.watermark.upgradeAction', 'Upgrade to Premium')}
            onPress={() => navigate(adminPath('/mobile/billing/shop?feature=watermark_allowed'))}
          />
        ) : null}

        {watermarkLocked ? (
          <InfoBadge
            icon={<Lock size={16} color={textStrong} />}
            text={t('events.watermark.lockedBranding', 'Custom-Wasserzeichen ist im aktuellen Paket gesperrt. Standard wird genutzt.')}
          />
        ) : null}

        <MobileCard gap="$3">
          <Text fontSize="$md" fontWeight="800" color={textStrong}>
            {t('events.watermark.title', 'Wasserzeichen')}
          </Text>

          <MobileField label={t('events.watermark.mode', 'Modus')}>
            <MobileSelect
              value={resolvedMode}
              disabled={controlsLocked}
              onChange={(event) => {
                const value = event.target.value;
                if (controlsLocked) return;
                if (value === 'custom' || value === 'base' || value === 'off') {
                  setWatermarkForm((prev) => ({ ...prev, mode: value as WatermarkForm['mode'] }));
                }
              }}
            >
              <option value="base">{t('events.watermark.modeBase', 'Basis')}</option>
              <option value="custom" disabled={!customWatermarkAllowed}>
                {t('events.watermark.modeCustom', 'Eigenes Wasserzeichen')}
              </option>
              <option value="off" disabled={!watermarkRemovalAllowed}>
                {t('events.watermark.modeOff', 'Deaktiviert')}
              </option>
            </MobileSelect>
          </MobileField>

          {resolvedMode === 'custom' && !controlsLocked ? (
            <YStack gap="$2">
              <Text fontSize="$sm" fontWeight="700" color={textStrong}>
                {t('events.watermark.upload', 'Wasserzeichen hochladen')}
              </Text>
              <Pressable onPress={() => document.getElementById('watermark-upload-input')?.click()}>
                <XStack
                  alignItems="center"
                  gap="$2"
                  paddingHorizontal="$3.5"
                  paddingVertical="$2.5"
                  borderRadius={12}
                  borderWidth={1}
                  borderColor={border}
                  backgroundColor={surface}
                >
                  <UploadCloud size={18} color={primary} />
                  <Text fontSize="$sm" color={primary} fontWeight="700">
                    {watermarkForm.assetPath || watermarkForm.assetDataUrl
                      ? t('events.watermark.replace', 'Wasserzeichen ersetzen')
                      : t('events.watermark.uploadCta', 'PNG/SVG/JPG (max. 3 MB)')}
                  </Text>
                </XStack>
              </Pressable>
              {watermarkForm.assetDataUrl ? (
                <YStack
                  borderRadius={12}
                  borderWidth={1}
                  borderColor={border}
                  backgroundColor={surfaceMuted}
                  padding="$2"
                  alignItems="center"
                  justifyContent="center"
                >
                  <img
                    src={watermarkForm.assetDataUrl}
                    alt={t('events.watermark.previewAlt', 'Wasserzeichen Vorschau')}
                    style={{ maxHeight: 120, maxWidth: '100%', objectFit: 'contain' }}
                  />
                </YStack>
              ) : null}
              <MobileFileInput
                id="watermark-upload-input"
                accept="image/png,image/jpeg,image/webp,image/svg+xml"
                onChange={(event) => {
                  const file = event.target.files?.[0];
                  if (!file) return;
                  if (file.size > 3 * 1024 * 1024) {
                    setError(t('events.watermark.errors.fileTooLarge', 'Wasserzeichen muss kleiner als 3 MB sein.'));
                    return;
                  }
                  const reader = new FileReader();
                  reader.onload = () => {
                    const result = typeof reader.result === 'string' ? reader.result : '';
                    setWatermarkForm((prev) => ({
                      ...prev,
                      assetDataUrl: result,
                      assetPreviewUrl: result,
                      assetPath: '',
                    }));
                    setError(null);
                  };
                  reader.readAsDataURL(file);
                }}
              />
              <Text fontSize="$xs" color={muted}>
                {t('events.watermark.uploadHint', 'PNG mit transparenter Fläche empfohlen.')}
              </Text>
            </YStack>
          ) : null}
        </MobileCard>

        <MobileCard gap="$3">
          <Text fontSize="$md" fontWeight="800" color={textStrong}>
            {t('events.watermark.placement', 'Position & Größe')}
          </Text>
          <PositionGrid
            value={watermarkForm.position}
            onChange={(next) => setWatermarkForm((prev) => ({ ...prev, position: next }))}
            disabled={customizationDisabled}
          />
          <LabeledSlider
            label={t('events.watermark.size', 'Größe')}
            value={Math.round(watermarkForm.scale * 100)}
            min={5}
            max={60}
            step={1}
            onChange={(value) => setWatermarkForm((prev) => ({ ...prev, scale: value / 100 }))}
            disabled={customizationDisabled}
          />
          <LabeledSlider
            label={t('events.watermark.opacity', 'Transparenz')}
            value={Math.round(watermarkForm.opacity * 100)}
            min={10}
            max={80}
            step={5}
            onChange={(value) => setWatermarkForm((prev) => ({ ...prev, opacity: value / 100 }))}
            disabled={customizationDisabled}
          />
          <LabeledSlider
            label={t('events.watermark.padding', 'Abstand zum Rand')}
            value={watermarkForm.padding}
            min={0}
            max={80}
            step={2}
            onChange={(value) => setWatermarkForm((prev) => ({ ...prev, padding: value }))}
            disabled={customizationDisabled}
          />
          <LabeledSlider
            label={t('events.watermark.offset', 'Feinjustierung')}
            value={watermarkForm.offsetX}
            min={-30}
            max={30}
            step={1}
            onChange={(value) => setWatermarkForm((prev) => ({ ...prev, offsetX: value }))}
            disabled={customizationDisabled}
            suffix={t('events.watermark.offsetX', 'X-Achse')}
          />
          <LabeledSlider
            label={t('events.watermark.offsetY', 'Y-Achse')}
            value={watermarkForm.offsetY}
            min={-30}
            max={30}
            step={1}
            onChange={(value) => setWatermarkForm((prev) => ({ ...prev, offsetY: value }))}
            disabled={customizationDisabled}
          />
        </MobileCard>
      </>
    );
  }

  return (
    <MobileShell
      activeTab="home"
      title={t('events.branding.titleShort', 'Branding')}
      onBack={back}
      headerActions={
        <HeaderActionButton onPress={() => handleSave()} ariaLabel={t('common.save', 'Save')}>
          <Save size={18} color={primary} />
        </HeaderActionButton>
      }
    >
      {error ? (
        <MobileCard>
          <Text fontWeight="700" color={danger}>
            {error}
          </Text>
        </MobileCard>
      ) : null}

      <XStack justifyContent="flex-end">
        <ContextHelpLink slug="event-branding-assets" />
      </XStack>

      <Tabs
        value={activeTab}
        onValueChange={(value) => setActiveTab(value as TabKey)}
        orientation="horizontal"
        flexDirection="column"
      >
        <MobileCard gap="$2">
          <Tabs.List gap="$2">
            <Tabs.Tab value="branding" flex={1} paddingVertical="$2.5" paddingHorizontal="$3" borderRadius="$4">
              <Text fontSize="$sm" fontWeight="600" textAlign="center">
                {t('events.branding.titleShort', 'Branding')}
              </Text>
            </Tabs.Tab>
            <Tabs.Tab value="watermark" flex={1} paddingVertical="$2.5" paddingHorizontal="$3" borderRadius="$4">
              <Text fontSize="$sm" fontWeight="600" textAlign="center">
                {t('events.watermark.tab', 'Wasserzeichen')}
              </Text>
            </Tabs.Tab>
          </Tabs.List>
        </MobileCard>

        <Tabs.Content value="branding" paddingTop="$2">
          <MobileCard gap="$3">
            <Text fontSize="$sm" fontWeight="700" color={textStrong}>
              {t('events.branding.previewTitle', 'Guest App Preview')}
            </Text>
            <Theme name={previewThemeName}>
              <YStack
                borderRadius={18}
                borderWidth={1}
                borderColor={previewBorder}
                overflow="hidden"
                style={previewVariables}
              >
                <YStack
                  padding="$3"
                  gap="$3"
                  style={{
                    backgroundImage: previewAmbient,
                    backgroundSize: '140% 140%, 140% 140%, 100% 100%',
                  }}
                >
                  <XStack alignItems="center" justifyContent="space-between" gap="$3">
                    <XStack
                      alignItems="center"
                      gap="$2"
                      flexDirection={previewForm.logoPosition === 'center' ? 'column' : previewForm.logoPosition === 'right' ? 'row-reverse' : 'row'}
                      justifyContent={previewForm.logoPosition === 'center' ? 'center' : 'flex-start'}
                      flex={1}
                    >
                      <YStack
                        width={previewLogoSize}
                        height={previewLogoSize}
                        borderRadius={previewLogoSize}
                        alignItems="center"
                        justifyContent="center"
                        backgroundColor={previewForm.accent}
                      >
                        {previewLogoUrl ? (
                          <img
                            src={previewLogoUrl}
                            alt={t('events.branding.logoAlt', 'Logo')}
                            style={{ width: previewLogoSize - 6, height: previewLogoSize - 6, borderRadius: previewLogoSize, objectFit: 'cover' }}
                          />
                        ) : (
                          <Text fontSize="$sm" color={previewSurfaceText} fontWeight="700">
                            {previewLogoValue || previewInitials}
                          </Text>
                        )}
                      </YStack>
                      <YStack gap="$1">
                        <Text
                          fontWeight="800"
                          color={previewSurfaceText}
                          style={{ fontFamily: previewHeadingFont, fontSize: 18 * previewScale }}
                        >
                          {previewTitle}
                        </Text>
                        <Text
                          color={previewMutedForeground}
                          style={{ fontFamily: previewBodyFont, fontSize: 13 * previewScale }}
                        >
                          {t('events.branding.previewSubtitle', 'Aktuelle Farben & Schriften')}
                        </Text>
                      </YStack>
                    </XStack>
                    <XStack gap="$2">
                      <YStack width={28} height={28} borderRadius={999} backgroundColor={previewIconSurface} />
                      <YStack width={28} height={28} borderRadius={999} backgroundColor={previewIconSurface} />
                    </XStack>
                  </XStack>

                  <YStack gap="$2">
                    <YStack
                      position="relative"
                      padding="$3"
                      borderRadius={14}
                      backgroundColor={previewSurface}
                      borderWidth={1}
                      borderColor={previewBorder}
                      style={{ boxShadow: previewSurfaceShadow }}
                    >
                      <YStack position="absolute" top={-10} right={-10}>
                        <YStack
                          width={28}
                          height={28}
                          borderRadius={999}
                          backgroundColor={previewSurface}
                          borderWidth={1}
                          borderColor={previewBorder}
                          alignItems="center"
                          justifyContent="center"
                          style={{
                            boxShadow: previewIsDark
                              ? '0 6px 0 rgba(0, 0, 0, 0.45)'
                              : '0 6px 0 rgba(15, 23, 42, 0.2)',
                          }}
                        >
                          <X size={12} color={previewSurfaceText} />
                        </YStack>
                      </YStack>
                      <Text
                        fontWeight="700"
                        color={previewSurfaceText}
                        style={{ fontFamily: previewHeadingFont, fontSize: 14 * previewScale }}
                      >
                        {t('events.branding.previewWelcome', 'Willkommen!')}
                      </Text>
                      <Text
                        color={previewMutedForeground}
                        style={{ fontFamily: previewBodyFont, fontSize: 12 * previewScale }}
                      >
                        {previewWelcomeMessage}
                      </Text>
                    </YStack>
                    <YStack
                      padding="$3"
                      borderRadius={14}
                      backgroundColor={previewSurface}
                      borderWidth={1}
                      borderColor={previewBorder}
                      style={{ boxShadow: previewSurfaceShadow }}
                    >
                      <Text
                        fontWeight="700"
                        color={previewSurfaceText}
                        style={{ fontFamily: previewHeadingFont, fontSize: 14 * previewScale }}
                      >
                        {t('events.branding.previewTitleShort', 'Dein Event-Hub')}
                      </Text>
                      <Text
                        color={previewMutedForeground}
                        style={{ fontFamily: previewBodyFont, fontSize: 12 * previewScale }}
                      >
                        {t('events.branding.previewSubtitleShort', 'Gäste, Fotos, Highlights')}
                      </Text>
                      <XStack gap="$2" marginTop="$2">
                        <ColorSwatch color={previewForm.primary} label={t('events.branding.primary', 'Primary')} borderColor={previewBorder} />
                        <ColorSwatch color={previewForm.accent} label={t('events.branding.accent', 'Accent')} borderColor={previewBorder} />
                        <ColorSwatch color={previewBackground} label={t('events.branding.background', 'Background')} borderColor={previewBorder} />
                        <ColorSwatch color={previewSurface} label={t('events.branding.surface', 'Surface')} borderColor={previewBorder} />
                      </XStack>
                    </YStack>

                    <XStack alignItems="center" justifyContent="space-between" gap="$2">
                      <YStack
                        padding="$2"
                        borderRadius="$pill"
                        backgroundColor={previewSurface}
                        borderWidth={1}
                        borderColor={previewBorder}
                        flex={1}
                      >
                        <Text fontSize="$2" color={previewMutedForeground}>
                          {t('events.branding.previewGuests', 'Guests')}
                        </Text>
                        <Text fontWeight="800" color={previewSurfaceText} style={{ fontSize: 14 * previewScale }}>
                          148
                        </Text>
                      </YStack>
                      <YStack
                        padding="$2"
                        borderRadius="$pill"
                        backgroundColor={previewSurface}
                        borderWidth={1}
                        borderColor={previewBorder}
                        flex={1}
                      >
                        <Text fontSize="$2" color={previewMutedForeground}>
                          {t('events.branding.previewLikes', 'Likes')}
                        </Text>
                        <Text fontWeight="800" color={previewSurfaceText} style={{ fontSize: 14 * previewScale }}>
                          392
                        </Text>
                      </YStack>
                    </XStack>
                    <XStack gap="$2" alignItems="center">
                      <YStack width={64} height={48} borderRadius={12} backgroundColor={previewIconSurface} />
                      <YStack width={64} height={48} borderRadius={12} backgroundColor={previewIconSurface} />
                      <YStack width={64} height={48} borderRadius={12} backgroundColor={previewIconSurface} />
                    </XStack>
                    <XStack gap="$2">
                      <YStack flex={1} height={44} borderRadius={12} backgroundColor={previewIconSurface} />
                      <YStack flex={1} height={44} borderRadius={12} backgroundColor={previewIconSurface} />
                      <YStack flex={1} height={44} borderRadius={12} backgroundColor={previewIconSurface} />
                    </XStack>
                  </YStack>

                  <XStack
                    alignItems="center"
                    justifyContent="space-between"
                    gap="$2"
                    padding="$2"
                    borderRadius="$pill"
                    backgroundColor={previewSurface}
                    borderWidth={1}
                    borderColor={previewBorder}
                  >
                    <XStack gap="$2">
                      <YStack width={28} height={28} borderRadius={999} backgroundColor={previewIconSurface} />
                      <YStack width={28} height={28} borderRadius={999} backgroundColor={previewIconSurface} />
                      <YStack width={28} height={28} borderRadius={999} backgroundColor={previewIconSurface} />
                    </XStack>
                    <YStack width={36} height={36} borderRadius={999} backgroundColor={previewButtonColor} />
                    <XStack gap="$2">
                      <YStack width={28} height={28} borderRadius={999} backgroundColor={previewIconSurface} />
                      <YStack width={28} height={28} borderRadius={999} backgroundColor={previewIconSurface} />
                    </XStack>
                  </XStack>
                </YStack>
              </YStack>
            </Theme>
          </MobileCard>

          {!brandingAllowed ? (
            <UpgradeCard
              title={t('events.branding.lockedTitle', 'Unlock branding')}
              body={t('events.branding.lockedBody', 'Upgrade to Classic or Premium to unlock event branding.')}
              actionLabel={t('events.branding.upgradeAction', 'Upgrade package')}
              onPress={() => navigate(adminPath('/mobile/billing/shop?feature=custom_branding'))}
            />
          ) : null}

          <>
              <MobileCard gap="$3">
                <Text fontSize="$md" fontWeight="800" color={textStrong}>
                  {t('events.branding.mode', 'Theme')}
                </Text>
                <XStack gap="$2">
                  <ModeButton
                    label={t('events.branding.modeLight', 'Light')}
                    active={form.mode === 'light'}
                    onPress={() => setForm((prev) => ({ ...prev, mode: 'light' }))}
                    disabled={brandingDisabled}
                  />
                  <ModeButton
                    label={t('events.branding.modeAuto', 'Auto')}
                    active={form.mode === 'auto'}
                    onPress={() => setForm((prev) => ({ ...prev, mode: 'auto' }))}
                    disabled={brandingDisabled}
                  />
                  <ModeButton
                    label={t('events.branding.modeDark', 'Dark')}
                    active={form.mode === 'dark'}
                    onPress={() => setForm((prev) => ({ ...prev, mode: 'dark' }))}
                    disabled={brandingDisabled}
                  />
                </XStack>
              </MobileCard>

              <MobileCard gap="$3">
                <Text fontSize="$md" fontWeight="800" color={textStrong}>
                  {t('events.branding.colors', 'Colors')}
                </Text>
                <ColorField
                  label={t('events.branding.primary', 'Primary Color')}
                  value={form.primary}
                  onChange={(value) => setForm((prev) => ({ ...prev, primary: value }))}
                  disabled={brandingDisabled}
                />
                <ColorField
                  label={t('events.branding.accent', 'Accent Color')}
                  value={form.accent}
                  onChange={(value) => setForm((prev) => ({ ...prev, accent: value }))}
                  disabled={brandingDisabled}
                />
                <ColorField
                  label={t('events.branding.backgroundColor', 'Background Color')}
                  value={form.background}
                  onChange={(value) => setForm((prev) => ({ ...prev, background: value }))}
                  disabled={brandingDisabled}
                />
                <ColorField
                  label={t('events.branding.surfaceColor', 'Surface Color')}
                  value={form.surface}
                  onChange={(value) => setForm((prev) => ({ ...prev, surface: value }))}
                  disabled={brandingDisabled}
                />
              </MobileCard>

              <MobileCard gap="$3">
                <Text fontSize="$md" fontWeight="800" color={textStrong}>
                  {t('events.branding.fonts', 'Fonts')}
                </Text>
                <InputField
                  label={t('events.branding.headingFont', 'Headline Font')}
                  value={form.headingFont}
                  placeholder={t('events.branding.headingFontPlaceholder', 'SF Pro Display')}
                  onChange={(value) => setForm((prev) => ({ ...prev, headingFont: value }))}
                  onPicker={() => {
                    setFontField('heading');
                    setShowFontsSheet(true);
                  }}
                  disabled={brandingDisabled}
                />
                <InputField
                  label={t('events.branding.bodyFont', 'Body Font')}
                  value={form.bodyFont}
                  placeholder={t('events.branding.bodyFontPlaceholder', 'SF Pro Text')}
                  onChange={(value) => setForm((prev) => ({ ...prev, bodyFont: value }))}
                  onPicker={() => {
                    setFontField('body');
                    setShowFontsSheet(true);
                  }}
                  disabled={brandingDisabled}
                />
                <Text fontSize="$sm" fontWeight="700" color={textStrong}>
                  {t('events.branding.fontSize', 'Font Size')}
                </Text>
                <XStack gap="$2">
                  <ModeButton
                    label={t('events.branding.fontSizeSmall', 'S')}
                    active={form.fontSize === 's'}
                    onPress={() => setForm((prev) => ({ ...prev, fontSize: 's' }))}
                    disabled={brandingDisabled}
                  />
                  <ModeButton
                    label={t('events.branding.fontSizeMedium', 'M')}
                    active={form.fontSize === 'm'}
                    onPress={() => setForm((prev) => ({ ...prev, fontSize: 'm' }))}
                    disabled={brandingDisabled}
                  />
                  <ModeButton
                    label={t('events.branding.fontSizeLarge', 'L')}
                    active={form.fontSize === 'l'}
                    onPress={() => setForm((prev) => ({ ...prev, fontSize: 'l' }))}
                    disabled={brandingDisabled}
                  />
                </XStack>
              </MobileCard>

              <MobileCard gap="$3">
                <Text fontSize="$md" fontWeight="800" color={textStrong}>
                  {t('events.branding.welcomeMessage.title', 'Welcome message')}
                </Text>
                <MobileField label={t('events.branding.welcomeMessage.label', 'Message')}>
                  <MobileTextArea
                    value={form.welcomeMessage}
                    placeholder={t('events.branding.welcomeMessage.placeholder', 'Welcome to {eventName}!')}
                    onChange={(event) => setForm((prev) => ({ ...prev, welcomeMessage: event.target.value }))}
                    disabled={brandingDisabled}
                  />
                </MobileField>
                <Text fontSize="$xs" color={muted}>
                  {t('events.branding.welcomeMessage.hint', 'Use {eventName} or {name} as placeholders.')}
                </Text>
              </MobileCard>

              <MobileCard gap="$3">
                <Text fontSize="$md" fontWeight="800" color={textStrong}>
                  {t('events.branding.logo', 'Logo')}
                </Text>
                <Text fontSize="$sm" color={muted}>
                  {t('events.branding.logoHint', 'Upload a logo or use an emoji for the guest header.')}
                </Text>
                <XStack gap="$2">
                  <ModeButton
                    label={t('events.branding.logoModeUpload', 'Upload')}
                    active={form.logoMode === 'upload'}
                    onPress={() => setForm((prev) => ({ ...prev, logoMode: 'upload' }))}
                    disabled={brandingDisabled}
                  />
                  <ModeButton
                    label={t('events.branding.logoModeEmoticon', 'Emoticon')}
                    active={form.logoMode === 'emoticon'}
                    onPress={() => setForm((prev) => ({ ...prev, logoMode: 'emoticon' }))}
                    disabled={brandingDisabled}
                  />
                </XStack>

                {form.logoMode === 'emoticon' ? (
                  <InputField
                    label={t('events.branding.logoValue', 'Emoticon')}
                    value={form.logoValue}
                    placeholder={t('events.branding.logoValuePlaceholder', '🎉')}
                    onChange={(value) => setForm((prev) => ({ ...prev, logoValue: value }))}
                    disabled={brandingDisabled}
                  />
                ) : (
                  <YStack
                    borderRadius={14}
                    borderWidth={1}
                    borderColor={border}
                    backgroundColor={surfaceMuted}
                    padding="$3"
                    alignItems="center"
                    justifyContent="center"
                    gap="$2"
                  >
                    {form.logoDataUrl ? (
                      <>
                        <img
                          src={form.logoDataUrl}
                          alt={t('events.branding.logoAlt', 'Logo')}
                          style={{ maxHeight: 80, maxWidth: '100%', objectFit: 'contain' }}
                        />
                        <XStack gap="$2">
                          <CTAButton
                            label={t('events.branding.replaceLogo', 'Replace logo')}
                            onPress={() => document.getElementById('branding-logo-input')?.click()}
                            disabled={brandingDisabled}
                          />
                          <Pressable
                            disabled={brandingDisabled}
                            onPress={() => setForm((prev) => ({ ...prev, logoDataUrl: '' }))}
                          >
                            <XStack
                              alignItems="center"
                              gap="$1.5"
                              paddingHorizontal="$3"
                              paddingVertical="$2"
                              borderRadius={12}
                              borderWidth={1}
                              borderColor={border}
                            >
                              <Trash2 size={16} color={danger} />
                              <Text fontSize="$sm" color={danger} fontWeight="700">
                                {t('events.branding.removeLogo', 'Remove')}
                              </Text>
                            </XStack>
                          </Pressable>
                        </XStack>
                      </>
                    ) : (
                      <>
                        <ImageIcon size={28} color={subtle} />
                        <Pressable
                          disabled={brandingDisabled}
                          onPress={() => document.getElementById('branding-logo-input')?.click()}
                        >
                          <XStack
                            alignItems="center"
                            gap="$2"
                            paddingHorizontal="$3.5"
                            paddingVertical="$2.5"
                            borderRadius={12}
                            borderWidth={1}
                            borderColor={border}
                            backgroundColor={surface}
                          >
                            <UploadCloud size={18} color={primary} />
                            <Text fontSize="$sm" color={primary} fontWeight="700">
                              {t('events.branding.uploadLogo', 'Upload logo (max. 1 MB)')}
                            </Text>
                          </XStack>
                        </Pressable>
                      </>
                    )}
                    <MobileFileInput
                      id="branding-logo-input"
                      accept="image/*"
                      disabled={brandingDisabled}
                      onChange={(event) => {
                        const file = event.target.files?.[0];
                        if (!file) return;
                        if (file.size > 1024 * 1024) {
                          setError(t('events.branding.logoTooLarge', 'Logo must be under 1 MB.'));
                          return;
                        }
                        const reader = new FileReader();
                        reader.onload = () => {
                          const nextLogo =
                            typeof reader.result === 'string'
                              ? reader.result
                              : typeof reader.result === 'object' && reader.result !== null
                                ? String(reader.result)
                                : '';
                          setForm((prev) => ({ ...prev, logoDataUrl: nextLogo }));
                          setError(null);
                        };
                        reader.readAsDataURL(file);
                      }}
                    />
                  </YStack>
                )}

                <Text fontSize="$sm" fontWeight="700" color={textStrong}>
                  {t('events.branding.logoPosition', 'Position')}
                </Text>
                <XStack gap="$2">
                  <ModeButton
                    label={t('events.branding.positionLeft', 'Left')}
                    active={form.logoPosition === 'left'}
                    onPress={() => setForm((prev) => ({ ...prev, logoPosition: 'left' }))}
                    disabled={brandingDisabled}
                  />
                  <ModeButton
                    label={t('events.branding.positionCenter', 'Center')}
                    active={form.logoPosition === 'center'}
                    onPress={() => setForm((prev) => ({ ...prev, logoPosition: 'center' }))}
                    disabled={brandingDisabled}
                  />
                  <ModeButton
                    label={t('events.branding.positionRight', 'Right')}
                    active={form.logoPosition === 'right'}
                    onPress={() => setForm((prev) => ({ ...prev, logoPosition: 'right' }))}
                    disabled={brandingDisabled}
                  />
                </XStack>
                <Text fontSize="$sm" fontWeight="700" color={textStrong}>
                  {t('events.branding.logoSize', 'Size')}
                </Text>
                <XStack gap="$2">
                  <ModeButton
                    label={t('events.branding.logoSizeSmall', 'S')}
                    active={form.logoSize === 's'}
                    onPress={() => setForm((prev) => ({ ...prev, logoSize: 's' }))}
                    disabled={brandingDisabled}
                  />
                  <ModeButton
                    label={t('events.branding.logoSizeMedium', 'M')}
                    active={form.logoSize === 'm'}
                    onPress={() => setForm((prev) => ({ ...prev, logoSize: 'm' }))}
                    disabled={brandingDisabled}
                  />
                  <ModeButton
                    label={t('events.branding.logoSizeLarge', 'L')}
                    active={form.logoSize === 'l'}
                    onPress={() => setForm((prev) => ({ ...prev, logoSize: 'l' }))}
                    disabled={brandingDisabled}
                  />
                </XStack>
              </MobileCard>

              <MobileCard gap="$3">
                <Text fontSize="$md" fontWeight="800" color={textStrong}>
                  {t('events.branding.buttons', 'Buttons & Links')}
                </Text>
                <Text fontSize="$sm" color={muted}>
                  {t('events.branding.buttonsHint', 'Style, radius, and link color for CTA buttons.')}
                </Text>
                <XStack gap="$2">
                  <ModeButton
                    label={t('events.branding.buttonFilled', 'Filled')}
                    active={form.buttonStyle === 'filled'}
                    onPress={() => setForm((prev) => ({ ...prev, buttonStyle: 'filled' }))}
                    disabled={brandingDisabled}
                  />
                  <ModeButton
                    label={t('events.branding.buttonOutline', 'Outline')}
                    active={form.buttonStyle === 'outline'}
                    onPress={() => setForm((prev) => ({ ...prev, buttonStyle: 'outline' }))}
                    disabled={brandingDisabled}
                  />
                </XStack>
                <LabeledSlider
                  label={t('events.branding.buttonRadius', 'Radius')}
                  value={form.buttonRadius}
                  min={0}
                  max={32}
                  step={1}
                  onChange={(value) => setForm((prev) => ({ ...prev, buttonRadius: value }))}
                  disabled={brandingDisabled}
                />
                <ColorField
                  label={t('events.branding.buttonPrimary', 'Button Primary')}
                  value={form.buttonPrimary}
                  onChange={(value) => setForm((prev) => ({ ...prev, buttonPrimary: value }))}
                  disabled={brandingDisabled}
                />
                <ColorField
                  label={t('events.branding.buttonSecondary', 'Button Secondary')}
                  value={form.buttonSecondary}
                  onChange={(value) => setForm((prev) => ({ ...prev, buttonSecondary: value }))}
                  disabled={brandingDisabled}
                />
                <ColorField
                  label={t('events.branding.linkColor', 'Link Color')}
                  value={form.linkColor}
                  onChange={(value) => setForm((prev) => ({ ...prev, linkColor: value }))}
                  disabled={brandingDisabled}
                />
                  </MobileCard>
          </>
        </Tabs.Content>

        <Tabs.Content value="watermark" paddingTop="$2">
          {renderWatermarkTab()}
        </Tabs.Content>
      </Tabs>

      <YStack gap="$2">
        <CTAButton label={saving ? t('events.branding.saving', 'Saving...') : t('events.branding.save', 'Save Branding')} onPress={() => handleSave()} />
        <Pressable disabled={loading || saving} onPress={handleReset}>
          <XStack
            height={52}
            borderRadius={14}
            alignItems="center"
            justifyContent="center"
            backgroundColor={surface}
            borderWidth={1}
            borderColor={border}
            gap="$2"
          >
            <RefreshCcw size={16} color={textStrong} />
            <Text fontSize="$sm" color={textStrong} fontWeight="700">
              {t('events.branding.reset', 'Reset to Defaults')}
            </Text>
          </XStack>
        </Pressable>
      </YStack>

      <MobileSheet
        open={showFontsSheet}
        onClose={() => setShowFontsSheet(false)}
        title={t('events.branding.fontPicker', 'Select font')}
        footer={null}
        bottomOffsetPx={120}
      >
        <YStack gap="$2">
          {fontsLoading ? (
            Array.from({ length: 4 }).map((_, idx) => <SkeletonCard key={`font-sk-${idx}`} height={48} />)
          ) : fonts.length === 0 ? (
            <Text fontSize="$sm" color={muted}>
              {t('events.branding.noFonts', 'Keine Schriftarten gefunden.')}
            </Text>
          ) : (
            fonts.map((font) => (
              <Pressable
                key={font.family}
                onPress={() => {
                  setForm((prev) => ({
                    ...prev,
                    [fontField === 'heading' ? 'headingFont' : 'bodyFont']: font.family,
                  }));
                  setShowFontsSheet(false);
                }}
              >
                <XStack alignItems="center" justifyContent="space-between" paddingVertical="$2">
                  <YStack>
                    <Text fontSize="$sm" color={textStrong} style={{ fontFamily: font.family }}>
                      {font.family}
                    </Text>
                    {font.variants?.length ? (
                      <Text fontSize="$xs" color={muted} style={{ fontFamily: font.family }}>
                        {font.variants.map((v) => v.style ?? v.weight ?? '').filter(Boolean).join(', ')}
                      </Text>
                    ) : null}
                  </YStack>
                  {form[fontField === 'heading' ? 'headingFont' : 'bodyFont'] === font.family ? (
                    <Text fontSize="$xs" color={primary}>
                      {t('common.active', 'Active')}
                    </Text>
                  ) : null}
                </XStack>
              </Pressable>
            ))
          )}
        </YStack>
      </MobileSheet>
    </MobileShell>
  );
}

function extractWatermark(event: TenantEvent): WatermarkForm {
  const settings = (event.settings as Record<string, unknown>) ?? {};
  const wm = (settings.watermark as Record<string, unknown>) ?? {};
  const readNumber = (key: string, fallback: number) => {
    const value = wm[key];
    return typeof value === 'number' && !Number.isNaN(value) ? value : fallback;
  };
  const readString = (key: string, fallback: string) => {
    const value = wm[key];
    return typeof value === 'string' && value.trim() ? value : fallback;
  };

  const mode = (wm.mode === 'custom' || wm.mode === 'off') ? wm.mode : 'base';
  const position = readString('position', 'bottom-right') as WatermarkPosition;

  return {
    mode,
    assetPath: readString('asset', ''),
    assetDataUrl: '',
    assetPreviewUrl: readString('asset_url', ''),
    position,
    opacity: readNumber('opacity', 0.25),
    scale: readNumber('scale', 0.2),
    padding: readNumber('padding', 16),
    offsetX: readNumber('offset_x', 0),
    offsetY: readNumber('offset_y', 0),
  };
}

function buildWatermarkPayload(
  form: WatermarkForm,
  watermarkAllowed: boolean,
  brandingAllowed: boolean,
  removalAllowed: boolean
): WatermarkSettings | null {
  const customAllowed = watermarkAllowed && brandingAllowed;
  let mode = form.mode;

  if (mode === 'custom' && !customAllowed) {
    mode = 'base';
  }

  if (mode === 'off' && !removalAllowed) {
    mode = 'base';
  }

  const payload: WatermarkSettings = {
    mode,
    position: form.position,
    opacity: Math.min(1, Math.max(0, form.opacity)),
    scale: Math.min(1, Math.max(0.05, form.scale)),
    padding: Math.max(0, Math.round(form.padding)),
    offset_x: Math.max(-500, Math.min(500, Math.round(form.offsetX))),
    offset_y: Math.max(-500, Math.min(500, Math.round(form.offsetY))),
  };

  if (mode === 'custom' && customAllowed) {
    if (form.assetDataUrl) {
      payload.asset_data_url = form.assetDataUrl;
    }
    if (form.assetPath) {
      payload.asset = form.assetPath;
    }
  }

  return payload;
}

function renderName(name: TenantEvent['name']): string {
  if (typeof name === 'string') return name;
  if (name && typeof name === 'object') {
    return name.de ?? name.en ?? Object.values(name)[0] ?? '';
  }
  return '';
}

function normalizeBrandingPath(value: string): string {
  const trimmed = value.trim();
  if (!trimmed) {
    return '';
  }

  if (trimmed.startsWith('http://') || trimmed.startsWith('https://') || trimmed.startsWith('data:')) {
    return trimmed;
  }

  const normalized = trimmed.replace(/^\/+/, '');

  if (normalized.startsWith('storage/')) {
    return normalized.slice('storage/'.length);
  }

  return normalized;
}

function getInitials(name: string): string {
  const words = name.split(' ').filter(Boolean);
  if (words.length >= 2) {
    return `${words[0][0]}${words[1][0]}`.toUpperCase();
  }
  return name.substring(0, 2).toUpperCase();
}

function ColorField({
  label,
  value,
  onChange,
  disabled,
}: {
  label: string;
  value: string;
  onChange: (next: string) => void;
  disabled?: boolean;
}) {
  const { textStrong, muted } = useAdminTheme();
  return (
    <YStack gap="$2" opacity={disabled ? 0.6 : 1}>
      <Text fontSize="$sm" fontWeight="700" color={textStrong}>
        {label}
      </Text>
      <XStack alignItems="center" gap="$2">
        <MobileColorInput
          value={value}
          onChange={(event) => onChange(event.target.value)}
          disabled={disabled}
        />
        <Text fontSize="$sm" color={muted}>
          {value}
        </Text>
      </XStack>
    </YStack>
  );
}

function ColorSwatch({ color, label, borderColor }: { color: string; label: string; borderColor?: string }) {
  const { border, muted } = useAdminTheme();
  return (
    <YStack alignItems="center" gap="$1">
      <YStack width={40} height={40} borderRadius={12} borderWidth={1} borderColor={borderColor ?? border} backgroundColor={color} />
      <Text fontSize="$xs" color={muted}>
        {label}
      </Text>
    </YStack>
  );
}

function InputField({
  label,
  value,
  placeholder,
  onChange,
  onPicker,
  disabled,
}: {
  label: string;
  value: string;
  placeholder?: string;
  onChange: (next: string) => void;
  onPicker?: () => void;
  disabled?: boolean;
}) {
  const { primary } = useAdminTheme();
  return (
    <MobileField label={label}>
      <XStack alignItems="center" gap="$2">
        <MobileInput
          value={value}
          placeholder={placeholder}
          onChange={(event) => onChange(event.target.value)}
          onFocus={onPicker}
          disabled={disabled}
          style={{ flex: 1 }}
        />
        {onPicker ? (
          <Pressable onPress={onPicker} disabled={disabled}>
            <ChevronDown size={16} color={primary} />
          </Pressable>
        ) : null}
      </XStack>
    </MobileField>
  );
}

function LabeledSlider({
  label,
  value,
  min,
  max,
  step,
  onChange,
  disabled,
  suffix,
}: {
  label: string;
  value: number;
  min: number;
  max: number;
  step: number;
  onChange: (value: number) => void;
  disabled?: boolean;
  suffix?: string;
}) {
  const { textStrong, muted, primary, border, surface } = useAdminTheme();
  return (
    <YStack gap="$1.5">
      <XStack alignItems="center" justifyContent="space-between">
        <Text fontSize="$sm" fontWeight="700" color={textStrong}>
          {label}
        </Text>
        <Text fontSize="$xs" color={muted}>
          {value}
          {suffix ? ` ${suffix}` : ''}
        </Text>
      </XStack>
      <Slider
        width="100%"
        min={min}
        max={max}
        step={step}
        value={[value]}
        onValueChange={(next: number[]) => onChange(next[0] ?? value)}
        disabled={disabled}
      >
        <Slider.Track height={6} borderRadius={999} backgroundColor={border}>
          <Slider.TrackActive backgroundColor={primary} />
        </Slider.Track>
        <Slider.Thumb index={0} size="$2" backgroundColor={surface} borderColor={primary} borderWidth={2} />
      </Slider>
    </YStack>
  );
}

function PositionGrid({
  value,
  onChange,
  disabled,
}: {
  value: WatermarkPosition;
  onChange: (value: WatermarkPosition) => void;
  disabled?: boolean;
}) {
  const { textStrong, primary, border, accentSoft, surface } = useAdminTheme();
  const positions: WatermarkPosition[] = [
    'top-left',
    'top-center',
    'top-right',
    'middle-left',
    'center',
    'middle-right',
    'bottom-left',
    'bottom-center',
    'bottom-right',
  ];

  return (
    <YStack gap="$2">
      <Text fontSize="$sm" fontWeight="700" color={textStrong}>
        Position
      </Text>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, minmax(0, 1fr))', gap: 8 }}>
        {positions.map((pos) => (
          <button
            key={pos}
            type="button"
            disabled={disabled}
            onClick={() => onChange(pos)}
            style={{
              height: 40,
              borderRadius: 10,
              border: value === pos ? `2px solid ${primary}` : `1px solid ${border}`,
              background: value === pos ? accentSoft : surface,
            }}
          >
            <Text fontSize="$xs" color={textStrong} textAlign="center">
              {pos.replace('-', ' ')}
            </Text>
          </button>
        ))}
      </div>
    </YStack>
  );
}

function WatermarkPreview({
  position,
  scale,
  opacity,
  padding,
  offsetX,
  offsetY,
  previewUrl,
  previewAlt,
}: {
  position: WatermarkPosition;
  scale: number;
  opacity: number;
  padding: number;
  offsetX: number;
  offsetY: number;
  previewUrl?: string;
  previewAlt?: string;
}) {
  const { border, muted, textStrong, overlay } = useAdminTheme();
  const width = 280;
  const height = 180;
  const wmWidth = Math.max(24, Math.round(width * Math.min(1, Math.max(0.05, scale))));
  const wmHeight = Math.round(wmWidth * 0.4);

  const baseX = (() => {
    switch (position) {
      case 'top-center':
      case 'center':
      case 'bottom-center':
        return (width - wmWidth) / 2;
      case 'top-right':
      case 'middle-right':
      case 'bottom-right':
        return width - wmWidth - padding;
      default:
        return padding;
    }
  })();

  const baseY = (() => {
    switch (position) {
      case 'middle-left':
      case 'center':
      case 'middle-right':
        return (height - wmHeight) / 2;
      case 'bottom-left':
      case 'bottom-center':
      case 'bottom-right':
        return height - wmHeight - padding;
      default:
        return padding;
    }
  })();

  const x = Math.max(0, Math.min(width - wmWidth, baseX + offsetX));
  const y = Math.max(0, Math.min(height - wmHeight, baseY + offsetY));

  return (
    <div style={{ position: 'relative', width: '100%', maxWidth: 320 }}>
      <div
        style={{
          width,
          height,
          borderRadius: 16,
          overflow: 'hidden',
          border: `1px solid ${border}`,
          background: ADMIN_GRADIENTS.softCard,
        }}
      >
        <div style={{ position: 'absolute', inset: 0, background: `linear-gradient(180deg, rgba(0,0,0,0.4), transparent)` }} />
        <div
          style={{
            position: 'absolute',
            left: x,
            top: y,
            width: wmWidth,
            height: wmHeight,
            background: previewUrl ? 'transparent' : 'rgba(255,255,255,0.8)',
            borderRadius: 10,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            opacity: Math.min(1, Math.max(0, opacity)),
            border: `1px dashed ${muted}`,
          }}
        >
          {previewUrl ? (
            <img
              src={previewUrl}
              alt={previewAlt ?? 'Watermark'}
              style={{ width: '100%', height: '100%', objectFit: 'contain' }}
            />
          ) : (
            <Droplets size={18} color={textStrong} />
          )}
        </div>
      </div>
    </div>
  );
}

function InfoBadge({ icon, text, tone = 'info' }: { icon?: React.ReactNode; text: string; tone?: 'info' | 'danger' }) {
  const { dangerBg, dangerText, surfaceMuted, textStrong, border } = useAdminTheme();
  const background = tone === 'danger' ? dangerBg : surfaceMuted;
  const color = tone === 'danger' ? dangerText : textStrong;

  return (
    <MobileCard gap="$2" backgroundColor={background} borderColor={border}>
      <XStack gap="$2" alignItems="center">
        {icon}
        <Text fontSize="$sm" color={color}>
          {text}
        </Text>
      </XStack>
    </MobileCard>
  );
}

function UpgradeCard({
  title,
  body,
  actionLabel,
  onPress,
}: {
  title: string;
  body: string;
  actionLabel: string;
  onPress: () => void;
}) {
  const { textStrong, muted, border, surface, primary, accentSoft } = useAdminTheme();

  return (
    <MobileCard
      gap="$4"
      padding="$6"
      alignItems="center"
      justifyContent="center"
      borderColor={border}
      backgroundColor={surface}
    >
      <YStack
        width={64}
        height={64}
        borderRadius={32}
        backgroundColor={accentSoft}
        alignItems="center"
        justifyContent="center"
        marginBottom="$2"
      >
        <Lock size={32} color={primary} />
      </YStack>
      <YStack gap="$2" alignItems="center">
        <Text fontSize="$xl" fontWeight="900" color={textStrong} textAlign="center">
          {title}
        </Text>
        <Text fontSize="$sm" color={muted} textAlign="center">
          {body}
        </Text>
      </YStack>
      <CTAButton label={actionLabel} onPress={onPress} />
    </MobileCard>
  );
}

function ModeButton({
  label,
  active,
  onPress,
  disabled,
}: {
  label: string;
  active: boolean;
  onPress: () => void;
  disabled?: boolean;
}) {
  const { primary, surfaceMuted, border, surface, textStrong } = useAdminTheme();
  return (
    <Pressable onPress={onPress} disabled={disabled} style={{ flex: 1, opacity: disabled ? 0.6 : 1 }}>
      <XStack
        alignItems="center"
        justifyContent="center"
        paddingVertical="$2"
        borderRadius={10}
        backgroundColor={active ? primary : surfaceMuted}
        borderWidth={1}
        borderColor={active ? primary : border}
      >
        <Text fontSize="$xs" color={active ? surface : textStrong} fontWeight="700">
          {label}
        </Text>
      </XStack>
    </Pressable>
  );
}
