import React from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Image as ImageIcon, RefreshCcw, UploadCloud, Trash2, ChevronDown, Save, Droplets, Lock } 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 } from 'tamagui';
import { MobileShell, HeaderActionButton } from './components/MobileShell';
import { MobileCard, CTAButton, SkeletonCard } from './components/Primitives';
import { MobileColorInput, MobileField, MobileFileInput, MobileInput, MobileSelect } 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_COLORS, ADMIN_GRADIENTS, useAdminTheme } from './theme';
import { extractBrandingForm, type BrandingFormValues } from '../lib/brandingForm';
import { getContrastingTextColor } from '@/guest/lib/color';

const BRANDING_FORM_DEFAULTS = {
  primary: ADMIN_COLORS.primary,
  accent: ADMIN_COLORS.accent,
  background: '#ffffff',
  surface: '#ffffff',
  mode: 'auto' as const,
  buttonStyle: 'filled' as const,
  buttonRadius: 12,
  buttonPrimary: ADMIN_COLORS.primary,
  buttonSecondary: ADMIN_COLORS.accent,
  linkColor: ADMIN_COLORS.accent,
  fontSize: 'm' as const,
  logoMode: 'upload' as const,
  logoPosition: 'left' as const,
  logoSize: 'm' as const,
};

const BRANDING_FORM_BASE: BrandingFormValues = {
  ...BRANDING_FORM_DEFAULTS,
  headingFont: '',
  bodyFont: '',
  logoDataUrl: '',
  logoValue: '',
  useDefaultBranding: false,
};

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,
};

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>(BRANDING_FORM_BASE);
  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);

  React.useEffect(() => {
    if (!slug) return;
    (async () => {
      setLoading(true);
      try {
        const data = await getEvent(slug);
        if (!data) {
          setLoading(false);
          return;
        }
        setEvent(data);
        setForm(extractBrandingForm(data.settings ?? {}, BRANDING_FORM_DEFAULTS));
        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 (!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.useDefaultBranding && tenantBranding ? tenantBranding : form;
  const previewTitle = event ? renderName(event.name) : t('events.placeholders.untitled', 'Unbenanntes Event');
  const previewHeadingFont = previewForm.headingFont || 'Archivo Black';
  const previewBodyFont = previewForm.bodyFont || 'Manrope';
  const previewSurfaceText = getContrastingTextColor(previewForm.surface, '#ffffff', '#0f172a');
  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 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 || form.useDefaultBranding;

  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>) : {}),
        use_default_branding: form.useDefaultBranding,
        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,
        },
        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 ?? {}, BRANDING_FORM_DEFAULTS));
      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 space="$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 space="$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 space="$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"
                  space="$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 space="$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}

      <MobileCard space="$2">
        <XStack space="$2">
          <TabButton label={t('events.branding.titleShort', 'Branding')} active={activeTab === 'branding'} onPress={() => setActiveTab('branding')} />
          <TabButton label={t('events.watermark.tab', 'Wasserzeichen')} active={activeTab === 'watermark'} onPress={() => setActiveTab('watermark')} />
        </XStack>
      </MobileCard>

      {activeTab === 'branding' ? (
        <>
          <MobileCard space="$3">
            <Text fontSize="$sm" fontWeight="700" color={textStrong}>
              {t('events.branding.previewTitle', 'Guest App Preview')}
            </Text>
            <YStack borderRadius={16} borderWidth={1} borderColor={border} backgroundColor={previewForm.background} padding="$3" space="$2" alignItems="center">
              <YStack width="100%" borderRadius={12} backgroundColor={previewForm.surface} borderWidth={1} borderColor={border} overflow="hidden">
                <YStack
                  height={64}
                  style={{ background: `linear-gradient(135deg, ${previewForm.primary}, ${previewForm.accent})` }}
                />
                <YStack padding="$3" space="$2">
                  <XStack
                    alignItems="center"
                    space="$2"
                    flexDirection={previewForm.logoPosition === 'center' ? 'column' : previewForm.logoPosition === 'right' ? 'row-reverse' : 'row'}
                    justifyContent={previewForm.logoPosition === 'center' ? 'center' : 'flex-start'}
                  >
                    <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>
                      <Text
                        fontWeight="800"
                        color={previewSurfaceText}
                        style={{ fontFamily: previewHeadingFont, fontSize: 18 * previewScale }}
                      >
                        {previewTitle}
                      </Text>
                      <Text
                        color={previewSurfaceText}
                        style={{ fontFamily: previewBodyFont, opacity: 0.7, fontSize: 13 * previewScale }}
                      >
                        {t('events.branding.previewSubtitle', 'Aktuelle Farben & Schriften')}
                      </Text>
                    </YStack>
                  </XStack>
                  <XStack space="$2" marginTop="$1">
                    <ColorSwatch color={previewForm.primary} label={t('events.branding.primary', 'Primary')} />
                    <ColorSwatch color={previewForm.accent} label={t('events.branding.accent', 'Accent')} />
                    <ColorSwatch color={previewForm.background} label={t('events.branding.background', 'Background')} />
                    <ColorSwatch color={previewForm.surface} label={t('events.branding.surface', 'Surface')} />
                  </XStack>
                  <XStack marginTop="$2">
                    <div
                      style={{
                        padding: '8px 14px',
                        borderRadius: previewForm.buttonRadius,
                        background: previewForm.buttonStyle === 'outline' ? 'transparent' : previewButtonColor,
                        color: previewForm.buttonStyle === 'outline' ? previewForm.linkColor : previewButtonText,
                        border: previewForm.buttonStyle === 'outline' ? `1px solid ${previewForm.linkColor}` : 'none',
                        fontWeight: 700,
                        fontSize: 13 * previewScale,
                      }}
                    >
                      {t('events.branding.previewCta', 'Fotos hochladen')}
                    </div>
                  </XStack>
                </YStack>
              </YStack>
            </YStack>
          </MobileCard>

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

          <MobileCard space="$3">
            <Text fontSize="$md" fontWeight="800" color={textStrong}>
              {t('events.branding.source', 'Branding Source')}
            </Text>
            <Text fontSize="$sm" color={muted}>
              {t('events.branding.sourceHint', 'Use the default branding or customize this event only.')}
            </Text>
            <XStack space="$2">
              <ModeButton
                label={t('events.branding.useDefault', 'Default')}
                active={form.useDefaultBranding}
                onPress={() => setForm((prev) => ({ ...prev, useDefaultBranding: true }))}
                disabled={!brandingAllowed}
              />
              <ModeButton
                label={t('events.branding.useCustom', 'This event')}
                active={!form.useDefaultBranding}
                onPress={() => setForm((prev) => ({ ...prev, useDefaultBranding: false }))}
                disabled={!brandingAllowed}
              />
            </XStack>
            <Text fontSize="$xs" color={muted}>
              {form.useDefaultBranding
                ? t('events.branding.usingDefault', 'Tenant-Branding aktiv')
                : t('events.branding.usingCustom', 'Event-Branding aktiv')}
            </Text>
          </MobileCard>

          {form.useDefaultBranding ? null : (
            <>
              <MobileCard space="$3">
                <Text fontSize="$md" fontWeight="800" color={textStrong}>
                  {t('events.branding.mode', 'Theme')}
                </Text>
                <XStack space="$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 space="$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 space="$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 space="$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 space="$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 space="$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"
                    space="$2"
                  >
                    {form.logoDataUrl ? (
                      <>
                        <img
                          src={form.logoDataUrl}
                          alt={t('events.branding.logoAlt', 'Logo')}
                          style={{ maxHeight: 80, maxWidth: '100%', objectFit: 'contain' }}
                        />
                        <XStack space="$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"
                              space="$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"
                            space="$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 space="$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 space="$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 space="$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 space="$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>
            </>
          )}
        </>
      ) : (
        renderWatermarkTab()
      )}

      <YStack space="$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}
            space="$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 space="$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 space="$2" opacity={disabled ? 0.6 : 1}>
      <Text fontSize="$sm" fontWeight="700" color={textStrong}>
        {label}
      </Text>
      <XStack alignItems="center" space="$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 }: { color: string; label: string }) {
  const { border, muted } = useAdminTheme();
  return (
    <YStack alignItems="center" space="$1">
      <YStack width={40} height={40} borderRadius={12} borderWidth={1} 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" space="$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 space="$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) => 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 space="$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, ${overlay}, 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 space="$2" backgroundColor={background} borderColor={border}>
      <XStack space="$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
      space="$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 space="$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 TabButton({ label, active, onPress }: { label: string; active: boolean; onPress: () => void }) {
  const { primary, surfaceMuted, border, surface, textStrong } = useAdminTheme();
  return (
    <Pressable onPress={onPress} style={{ flex: 1 }}>
      <XStack
        alignItems="center"
        justifyContent="center"
        paddingVertical="$2.5"
        borderRadius={12}
        backgroundColor={active ? primary : surfaceMuted}
        borderWidth={1}
        borderColor={active ? primary : border}
      >
        <Text fontSize="$sm" color={active ? surface : textStrong} fontWeight="700">
          {label}
        </Text>
      </XStack>
    </Pressable>
  );
}

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>
  );
}
