<?php

function mrLayoutEditorModeCatalog(): array
{
    return [
        'html' => [
            'label' => 'HTML-Code',
            'description' => 'Direkte Bearbeitung von Header und Footer als HTML.',
        ],
        'layout_builder' => [
            'label' => 'Layout-Builder',
            'description' => 'Gefuehrter Editor fuer Kopf- und Fussbereich mit Vorschau.',
        ],
    ];
}

function mrNormalizeLayoutEditorMode(string $mode): string
{
    return array_key_exists($mode, mrLayoutEditorModeCatalog()) ? $mode : 'html';
}

function mrCreateDefaultLayoutBuilderSource(): string
{
    return json_encode([
        'header' => [
            'background_color' => '#F8FAFC',
            'text_color' => '#243B53',
            'logo_url' => '',
            'logo_alt' => '',
            'logo_width' => 180,
            'align' => 'center',
            'text_position' => 'below',
            'headline' => '',
            'text' => '',
            'show_online_view' => true,
            'online_view_text' => 'E-Mail im Browser ansehen',
        ],
        'footer' => [
            'background_color' => '#F8FAFC',
            'text_color' => '#486581',
            'text' => '',
            'show_social' => false,
            'facebook_url' => '',
            'instagram_url' => '',
            'linkedin_url' => '',
            'youtube_url' => '',
            'show_unsubscribe' => true,
            'unsubscribe_text' => 'Abmelden',
            'show_online_view' => false,
            'online_view_text' => 'Im Browser ansehen',
            'show_pause' => true,
            'pause_text' => 'Versand pausieren',
        ],
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}

function mrNormalizeLayoutBuilderColor(string $value, string $fallback): string
{
    $value = trim($value);
    if (preg_match('/^#[0-9a-fA-F]{6}$/', $value)) {
        return strtoupper($value);
    }

    return $fallback;
}

function mrNormalizeLayoutBuilderAlign(string $value): string
{
    return in_array($value, ['left', 'center', 'right'], true) ? $value : 'center';
}

function mrNormalizeLayoutBuilderTextPosition(string $value): string
{
    return in_array($value, ['below', 'side'], true) ? $value : 'below';
}

function mrDecodeLayoutBuilderSource(string $sourceContent): array
{
    $decoded = json_decode(trim($sourceContent) !== '' ? $sourceContent : mrCreateDefaultLayoutBuilderSource(), true);
    if (!is_array($decoded)) {
        $decoded = json_decode(mrCreateDefaultLayoutBuilderSource(), true);
    }

    $header = is_array($decoded['header'] ?? null) ? $decoded['header'] : [];
    $footer = is_array($decoded['footer'] ?? null) ? $decoded['footer'] : [];

    return [
        'header' => [
            'background_color' => mrNormalizeLayoutBuilderColor((string) ($header['background_color'] ?? '#F8FAFC'), '#F8FAFC'),
            'text_color' => mrNormalizeLayoutBuilderColor((string) ($header['text_color'] ?? '#243B53'), '#243B53'),
            'logo_url' => trim((string) ($header['logo_url'] ?? '')),
            'logo_alt' => trim((string) ($header['logo_alt'] ?? '')),
            'logo_width' => max(80, min(320, (int) ($header['logo_width'] ?? 180))),
            'align' => mrNormalizeLayoutBuilderAlign((string) ($header['align'] ?? 'center')),
            'text_position' => mrNormalizeLayoutBuilderTextPosition((string) ($header['text_position'] ?? 'below')),
            'headline' => trim((string) ($header['headline'] ?? '')),
            'text' => trim((string) ($header['text'] ?? '')),
            'show_online_view' => !empty($header['show_online_view']),
            'online_view_text' => trim((string) ($header['online_view_text'] ?? 'E-Mail im Browser ansehen')),
        ],
        'footer' => [
            'background_color' => mrNormalizeLayoutBuilderColor((string) ($footer['background_color'] ?? '#F8FAFC'), '#F8FAFC'),
            'text_color' => mrNormalizeLayoutBuilderColor((string) ($footer['text_color'] ?? '#486581'), '#486581'),
            'text' => trim((string) ($footer['text'] ?? '')),
            'show_social' => !empty($footer['show_social']),
            'facebook_url' => trim((string) ($footer['facebook_url'] ?? '')),
            'instagram_url' => trim((string) ($footer['instagram_url'] ?? '')),
            'linkedin_url' => trim((string) ($footer['linkedin_url'] ?? '')),
            'youtube_url' => trim((string) ($footer['youtube_url'] ?? '')),
            'show_unsubscribe' => !array_key_exists('show_unsubscribe', $footer) || !empty($footer['show_unsubscribe']),
            'unsubscribe_text' => trim((string) ($footer['unsubscribe_text'] ?? 'Abmelden')),
            'show_online_view' => !empty($footer['show_online_view']),
            'online_view_text' => trim((string) ($footer['online_view_text'] ?? 'Im Browser ansehen')),
            'show_pause' => !empty($footer['show_pause']),
            'pause_text' => trim((string) ($footer['pause_text'] ?? 'Versand pausieren')),
        ],
    ];
}

function mrLayoutBuilderMarginStyle(string $align): string
{
    return match ($align) {
        'left' => 'margin:0 auto 0 0;',
        'right' => 'margin:0 0 0 auto;',
        default => 'margin:0 auto;',
    };
}

function mrRenderLayoutBuilderHeaderHtml(array $source): string
{
    $header = $source['header'] ?? [];
    $background = htmlspecialchars((string) ($header['background_color'] ?? '#F8FAFC'), ENT_QUOTES, 'UTF-8');
    $textColor = htmlspecialchars((string) ($header['text_color'] ?? '#243B53'), ENT_QUOTES, 'UTF-8');
    $align = htmlspecialchars(mrNormalizeLayoutBuilderAlign((string) ($header['align'] ?? 'center')), ENT_QUOTES, 'UTF-8');
    $logoUrl = trim((string) ($header['logo_url'] ?? ''));
    $logoAlt = htmlspecialchars((string) ($header['logo_alt'] ?? ''), ENT_QUOTES, 'UTF-8');
    $logoWidth = max(80, min(320, (int) ($header['logo_width'] ?? 180)));
    $headline = trim((string) ($header['headline'] ?? ''));
    $text = trim((string) ($header['text'] ?? ''));
    $showOnlineView = !empty($header['show_online_view']);
    $onlineViewText = trim((string) ($header['online_view_text'] ?? ''));

    $parts = [];
    if ($showOnlineView && $onlineViewText !== '') {
        $parts[] = '<tr><td align="center" style="padding:0 0 12px 0;font-family:Arial,Helvetica,sans-serif;font-size:12px;line-height:1.5;color:' . $textColor . ';"><a href="[online_view_url]" style="color:' . $textColor . ';text-decoration:underline;">' . htmlspecialchars($onlineViewText, ENT_QUOTES, 'UTF-8') . '</a></td></tr>';
    }
    $textPosition = mrNormalizeLayoutBuilderTextPosition((string) ($header['text_position'] ?? 'below'));
    $hasTextBlock = $headline !== '' || $text !== '';
    if ($logoUrl !== '' && $hasTextBlock && $textPosition === 'side') {
        $textParts = [];
        if ($headline !== '') {
            $textParts[] = '<div style="padding:0 0 10px 0;font-family:Arial,Helvetica,sans-serif;font-size:28px;line-height:1.2;font-weight:700;color:' . $textColor . ';text-align:center;">' . htmlspecialchars($headline, ENT_QUOTES, 'UTF-8') . '</div>';
        }
        if ($text !== '') {
            $textParts[] = '<div style="font-family:Arial,Helvetica,sans-serif;font-size:15px;line-height:1.6;color:' . $textColor . ';text-align:center;">' . nl2br(htmlspecialchars($text, ENT_QUOTES, 'UTF-8')) . '</div>';
        }
        $parts[] = '<tr><td align="' . $align . '" style="padding:0 0 24px 0;"><table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;max-width:100%;' . mrLayoutBuilderMarginStyle((string) ($header['align'] ?? 'center')) . '"><tr><td valign="middle" style="padding:0 18px 0 0;"><img src="' . htmlspecialchars($logoUrl, ENT_QUOTES, 'UTF-8') . '" alt="' . $logoAlt . '" width="' . $logoWidth . '" style="display:block;max-width:100%;height:auto;border:0;"></td><td valign="middle" align="center" style="text-align:center;">' . implode('', $textParts) . '</td></tr></table></td></tr>';
    } else {
        if ($logoUrl !== '') {
            $parts[] = '<tr><td align="' . $align . '" style="padding:0 0 16px 0;"><img src="' . htmlspecialchars($logoUrl, ENT_QUOTES, 'UTF-8') . '" alt="' . $logoAlt . '" width="' . $logoWidth . '" style="display:inline-block;max-width:100%;height:auto;border:0;"></td></tr>';
        }
        if ($headline !== '') {
            $parts[] = '<tr><td align="' . $align . '" style="padding:0 0 12px 0;font-family:Arial,Helvetica,sans-serif;font-size:28px;line-height:1.2;font-weight:700;color:' . $textColor . ';">' . htmlspecialchars($headline, ENT_QUOTES, 'UTF-8') . '</td></tr>';
        }
        if ($text !== '') {
            $parts[] = '<tr><td align="' . $align . '" style="padding:0 0 24px 0;font-family:Arial,Helvetica,sans-serif;font-size:15px;line-height:1.6;color:' . $textColor . ';">' . nl2br(htmlspecialchars($text, ENT_QUOTES, 'UTF-8')) . '</td></tr>';
        }
    }

    $headerSection = '';
    if ($parts !== []) {
        $headerSection = '<tr><td style="padding:28px 24px 8px 24px;background:' . $background . ';"><table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">' . implode('', $parts) . '</table></td></tr>';
    }

    return '<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;background:#FFFFFF;">' . $headerSection . '<tr><td style="padding:0;">';
}

function mrRenderLayoutBuilderFooterHtml(array $source): string
{
    $footer = $source['footer'] ?? [];
    $background = htmlspecialchars((string) ($footer['background_color'] ?? '#F8FAFC'), ENT_QUOTES, 'UTF-8');
    $textColor = htmlspecialchars((string) ($footer['text_color'] ?? '#486581'), ENT_QUOTES, 'UTF-8');
    $text = trim((string) ($footer['text'] ?? ''));
    $parts = [];

    if ($text !== '') {
        $parts[] = '<tr><td align="center" style="padding:0 0 14px 0;font-family:Arial,Helvetica,sans-serif;font-size:13px;line-height:1.6;color:' . $textColor . ';">' . nl2br(htmlspecialchars($text, ENT_QUOTES, 'UTF-8')) . '</td></tr>';
    }

    $socialLinks = [];
    $socialMap = [
        'facebook_url' => 'Facebook',
        'instagram_url' => 'Instagram',
        'linkedin_url' => 'LinkedIn',
        'youtube_url' => 'YouTube',
    ];
    if (!empty($footer['show_social'])) {
        foreach ($socialMap as $field => $label) {
            $url = trim((string) ($footer[$field] ?? ''));
            if ($url !== '') {
                $socialLinks[] = '<a href="' . htmlspecialchars($url, ENT_QUOTES, 'UTF-8') . '" style="color:' . $textColor . ';text-decoration:underline;">' . htmlspecialchars($label, ENT_QUOTES, 'UTF-8') . '</a>';
            }
        }
    }
    if ($socialLinks !== []) {
        $parts[] = '<tr><td align="center" style="padding:0 0 14px 0;font-family:Arial,Helvetica,sans-serif;font-size:13px;line-height:1.6;color:' . $textColor . ';">' . implode(' &nbsp;&middot;&nbsp; ', $socialLinks) . '</td></tr>';
    }

    $systemLinks = [];
    if (!empty($footer['show_unsubscribe']) && trim((string) ($footer['unsubscribe_text'] ?? '')) !== '') {
        $systemLinks[] = '<a href="[unsubscribe_url]" style="color:' . $textColor . ';text-decoration:underline;">' . htmlspecialchars((string) $footer['unsubscribe_text'], ENT_QUOTES, 'UTF-8') . '</a>';
    }
    if (!empty($footer['show_online_view']) && trim((string) ($footer['online_view_text'] ?? '')) !== '') {
        $systemLinks[] = '<a href="[online_view_url]" style="color:' . $textColor . ';text-decoration:underline;">' . htmlspecialchars((string) $footer['online_view_text'], ENT_QUOTES, 'UTF-8') . '</a>';
    }
    if (!empty($footer['show_pause']) && trim((string) ($footer['pause_text'] ?? '')) !== '') {
        $systemLinks[] = '<a href="[pause_url]" style="color:' . $textColor . ';text-decoration:underline;">' . htmlspecialchars((string) $footer['pause_text'], ENT_QUOTES, 'UTF-8') . '</a>';
    }
    if ($systemLinks !== []) {
        $parts[] = '<tr><td align="center" style="padding:0 0 8px 0;font-family:Arial,Helvetica,sans-serif;font-size:12px;line-height:1.6;color:' . $textColor . ';">' . implode(' &nbsp;&middot;&nbsp; ', $systemLinks) . '</td></tr>';
    }

    $footerSection = '';
    if ($parts !== []) {
        $footerSection = '<tr><td style="padding:20px 24px 28px 24px;background:' . $background . ';"><table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">' . implode('', $parts) . '</table></td></tr>';
    }

    return '</td></tr>' . $footerSection . '</table>';
}

function mrPrepareLayoutEditorState(?array $layout): array
{
    $layout = is_array($layout) ? $layout : [];
    $editorMode = mrNormalizeLayoutEditorMode((string) ($layout['editor_mode'] ?? 'html'));
    $sourceContent = trim((string) ($layout['source_content'] ?? ''));

    if ($editorMode === 'layout_builder') {
        $normalized = mrDecodeLayoutBuilderSource($sourceContent);
        $sourceContent = json_encode($normalized, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        $layout['header_html'] = mrRenderLayoutBuilderHeaderHtml($normalized);
        $layout['footer_html'] = mrRenderLayoutBuilderFooterHtml($normalized);
    }

    return array_merge([
        'editor_mode' => $editorMode,
        'source_content' => $sourceContent,
        'builder_schema_version' => (int) ($layout['builder_schema_version'] ?? 1),
        'header_html' => (string) ($layout['header_html'] ?? ''),
        'footer_html' => (string) ($layout['footer_html'] ?? ''),
    ], $layout);
}

function mrPrepareLayoutEditorPayload(array $post): array
{
    $editorMode = mrNormalizeLayoutEditorMode((string) ($post['editor_mode'] ?? 'html'));
    if ($editorMode === 'layout_builder') {
        $source = mrDecodeLayoutBuilderSource((string) ($post['source_content'] ?? ''));
        $normalizedSource = json_encode($source, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        return [
            'editor_mode' => 'layout_builder',
            'source_content' => $normalizedSource,
            'builder_schema_version' => 1,
            'header_html' => mrRenderLayoutBuilderHeaderHtml($source),
            'footer_html' => mrRenderLayoutBuilderFooterHtml($source),
        ];
    }

    return [
        'editor_mode' => 'html',
        'source_content' => '',
        'builder_schema_version' => 1,
        'header_html' => (string) ($post['header_html'] ?? ''),
        'footer_html' => (string) ($post['footer_html'] ?? ''),
    ];
}
