<?php

namespace App\Services;

class EmailRenderer
{
    private ?int $campaignId = null;
    private ?int $contactId  = null;
    private ?string $token   = null;
    private ?array $utmData  = null;

    public function setUtmData(?array $utmData): self
    {
        $this->utmData = $utmData;
        return $this;
    }

    public function render(array $blocks, array $mergeData = [], ?int $campaignId = null, ?int $contactId = null, ?string $preHeader = null): string
    {
        // Needed to resolve business/email settings (footer text, sender
        // fallback) even in contexts with no contact yet, e.g. previews 
        // tracking-specific state below still requires both to be set.
        $this->campaignId = $campaignId;

        // Tracking can be turned off tenant-wide (Settings > Email Settings)
        // for legal/compliance reasons  when off, no token is issued, which
        // already suppresses both the open pixel and click-link rewriting below.
        if ($campaignId && $contactId && BusinessSettings::trackingEnabled($campaignId)) {
            $this->contactId = $contactId;
            $this->token     = TrackingHelper::token($campaignId, $contactId);
        }
        if (empty($blocks)) {
            $blocks = $this->defaultBlocks();
        }

        $inner = $this->renderBlocks($blocks);

        $footer = '';
        if (!$this->hasFooterBlock($blocks)) {
            // Only auto-append a footer when the user hasn't dragged in their
            // own Footer block  that block already renders these same
            // settings (see the 'footer' case below), so appending both
            // would show the notice/links/copyright twice.
            $emailSettings  = BusinessSettings::emailSettings($campaignId);
            $unsubscribeUrl = $this->trackingUrl('unsubscribe');

            $links = [];
            if ($emailSettings['footer_show_unsubscribe']) {
                $links[] = '<a href="' . $unsubscribeUrl . '" style="color:#4285f4;text-decoration:none;">Unsubscribe</a>';
            }
            if ($emailSettings['footer_show_privacy']) {
                $privacyUrl = $emailSettings['footer_privacy_url'] ?: '#';
                $links[] = '<a href="' . e($privacyUrl) . '" style="color:#4285f4;text-decoration:none;">Privacy Policy</a>';
            }
            $linksRow = $links ? '<p style="margin:0">' . implode(' · ', $links) . '</p>' : '';

            $footer =
                '<div style="border-top:1px solid #e5e7eb;padding:16px 24px;text-align:center;font-size:11px;color:#9ca3af;line-height:1.8;background:#f9fafb;">' .
                '<p style="margin:0">' . nl2br(e($emailSettings['footer_notice'])) . '</p>' .
                $linksRow .
                '<p style="margin:0">' . e($emailSettings['footer_copyright']) . '</p>' .
                '</div>';
        }

        // Tracking pixel
        $pixel = '';
        if ($this->token) {
            $pixelUrl = $this->trackingUrl('open');
            $pixel    = '<img src="' . $pixelUrl . '" width="1" height="1" border="0" alt="" style="display:none;width:1px;height:1px;" />';
        }

        $preHeaderHtml = '';
        if ($preHeader) {
            $resolvedPreHeader = $preHeader;
            foreach ($mergeData as $key => $value) {
                $resolvedPreHeader = str_replace('{{' . $key . '}}', $value, $resolvedPreHeader);
            }
            $preHeaderHtml = '<div style="display:none;max-height:0px;max-width:0px;opacity:0;overflow:hidden;mso-hide:all;font-size:1px;line-height:1px;">' . e($resolvedPreHeader) . '</div>';
        }

        $bodyBlock = null;
        foreach ($blocks as $b) {
            if (isset($b['type']) && $b['type'] === 'body') {
                $bodyBlock = $b;
                break;
            }
        }

        $outerBgColor = $bodyBlock['bgColor'] ?? '#f3f4f6';
        $outerBgImage = $bodyBlock['bgImage'] ?? '';
        $outerBgPattern = $bodyBlock['bgPattern'] ?? '';
        $innerBgColor = $bodyBlock['contentBgColor'] ?? '#ffffff';
        $innerBgImage = $bodyBlock['contentBgImage'] ?? '';
        $contentWidth = $bodyBlock['contentWidth'] ?? 600;

        $outerStyle = 'background-color:' . $outerBgColor . ';padding:24px 0;';

        $bgStyle = '';
        if ($outerBgImage) {
            $bgStyle = 'background-image:url(' . $this->absoluteUrl($outerBgImage) . ');background-repeat:repeat;';
        } elseif ($outerBgPattern) {
            if ($outerBgPattern === 'dots') {
                $bgStyle = 'background-image:radial-gradient(rgba(0,0,0,0.1) 1px, transparent 1px);background-size:16px 16px;';
            } elseif ($outerBgPattern === 'grid') {
                $bgStyle = 'background-image:linear-gradient(rgba(0,0,0,0.04) 1px, transparent 1px), linear-gradient(90deg, rgba(0,0,0,0.04) 1px, transparent 1px);background-size:20px 20px;';
            } elseif ($outerBgPattern === 'stripes') {
                $bgStyle = 'background-image:repeating-linear-gradient(45deg, rgba(0,0,0,0.02) 0px, rgba(0,0,0,0.02) 1px, transparent 1px, transparent 10px);';
            } elseif ($outerBgPattern === 'abstract') {
                $bgStyle = 'background-image:linear-gradient(45deg, rgba(0,0,0,0.015) 25%, transparent 25%), linear-gradient(-45deg, rgba(0,0,0,0.015) 25%, transparent 25%);background-size:30px 30px;';
            }
        }

        $innerStyle = 'width:100%;max-width:' . $contentWidth . 'px;margin:0 auto;background-color:' . $innerBgColor . ';font-family:-apple-system,BlinkMacSystemFont,\'Segoe UI\',Roboto,sans-serif;' . $bgStyle;
        $innerBackgroundAttr = $outerBgImage ? ' background="' . e($this->absoluteUrl($outerBgImage)) . '"' : '';

        $html =
            '<div style="' . $outerStyle . '">' .
            $preHeaderHtml .
            '<!--[if mso]><table align="center" role="presentation" cellspacing="0" cellpadding="0" border="0" width="' . $contentWidth . '"><tr><td><![endif]-->' .
            '<table align="center" role="presentation" cellspacing="0" cellpadding="0" border="0" width="100%"' . $innerBackgroundAttr . ' style="' . $innerStyle . '">' .
            '<tr><td style="padding:0;background-color:' . $innerBgColor . ';' . $bgStyle . '"' . $innerBackgroundAttr . '>' .
            $inner .
            $footer .
            '</td></tr></table>' .
            '<!--[if mso]></td></tr></table><![endif]-->' .
            $pixel .
            '</div>';

        // Wrap all content links for click tracking
        if ($this->token) {
            $html = $this->wrapLinks($html);
        } elseif ($this->utmData) {
            $html = $this->appendUtmToAllLinks($html);
        }

        // Replace merge tags: {{contact.first_name}}, {{business_name}}, etc.
        // Business tags come from Settings > Business Setup and don't depend
        // on a contact, so they resolve in every context this renders in
        // (preview, test send, real send)  not just real per-contact sends.
        $mergeData = array_merge(BusinessSettings::mergeTags($campaignId), $mergeData);
        foreach ($mergeData as $key => $value) {
            $html = str_replace('{{' . $key . '}}', e($value), $html);
        }

        // Reset state so this instance can be reused
        $this->campaignId = null;
        $this->contactId  = null;
        $this->token      = null;
        $this->utmData    = null;

        return $html;
    }

    private function hasFooterBlock(array $blocks): bool
    {
        foreach ($blocks as $block) {
            if (($block['type'] ?? null) === 'footer') {
                return true;
            }
            if (($block['type'] ?? null) === 'column') {
                foreach ($block['columns'] ?? [] as $column) {
                    if ($this->hasFooterBlock($column['blocks'] ?? [])) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    private function wrapLinks(string $html): string
    {
        return preg_replace_callback(
            '/href="([^"]+)"/i',
            function ($m) {
                $url = $m[1];

                // Skip non-trackable links
                if (
                    $url === '#' ||
                    str_starts_with($url, 'mailto:') ||
                    str_starts_with($url, 'tel:') ||
                    str_contains($url, '/track/') ||
                    str_contains($url, '/unsubscribe/')
                ) {
                    return $m[0];
                }

                // Append UTM parameters first if available
                $url = $this->appendUtmParameters($url);

                $clickBase = $this->trackingUrl('click');
                $trackUrl  = $clickBase . '?url=' . rawurlencode($url);
                return 'href="' . $trackUrl . '"';
            },
            $html
        );
    }

    private function absoluteUrl(string $src): string
    {
        // Already absolute (http/https/data URI)
        if (preg_match('#^(https?://|data:)#i', $src)) {
            return $src;
        }
        // Relative path - prepend APP_URL
        return rtrim(config('app.url'), '/') . '/' . ltrim($src, '/');
    }

    private function trackingUrl(string $type): string
    {
        if (!$this->token) {
            return '#';
        }
        return match ($type) {
            'open'        => route('track.open',        ['campaign' => $this->campaignId, 'contact' => $this->contactId, 'token' => $this->token]),
            'click'       => route('track.click',       ['campaign' => $this->campaignId, 'contact' => $this->contactId, 'token' => $this->token]),
            'unsubscribe' => route('track.unsubscribe', ['campaign' => $this->campaignId, 'contact' => $this->contactId, 'token' => $this->token]),
            default       => '#',
        };
    }

    public function renderBlocks(array $blocks): string
    {
        $html = '';
        foreach ($blocks as $block) {
            $html .= $this->renderBlock($block);
        }
        return $html;
    }

    public function renderBlock(array $block): string
    {
        $type = $block['type'] ?? '';
        $s    = $block['styles'] ?? [];

        $pt = $s['paddingTop']    ?? 16;
        $pr = $s['paddingRight']  ?? 24;
        $pb = $s['paddingBottom'] ?? 16;
        $pl = $s['paddingLeft']   ?? 24;
        $mt = $s['marginTop']     ?? 0;
        $mb = $s['marginBottom']  ?? 0;
        
        // Handle margin left/right (including alignment auto-margins)
        $ml = $s['marginLeft'] ?? 0;
        $mr = $s['marginRight'] ?? 0;
        if (isset($s['width']) && $s['width'] !== 'auto' && (int)$s['width'] < 100) {
            $align = $s['blockAlign'] ?? 'left';
            if ($align === 'center') {
                $ml = 'auto';
                $mr = 'auto';
            } elseif ($align === 'right') {
                $ml = 'auto';
                $mr = 0;
            } else {
                $ml = 0;
                $mr = 'auto';
            }
        }
        
        $mlStr = $ml === 'auto' ? 'auto' : "{$ml}px";
        $mrStr = $mr === 'auto' ? 'auto' : "{$mr}px";
        
        // Calculate block width style
        $widthStyle = "";
        if (isset($s['width']) && $s['width'] !== 'auto' && $type !== 'button' && $type !== 'logo') {
            $wVal = (int)$s['width'];
            if ($wVal < 100) {
                $mlNum = is_numeric($ml) ? (int)$ml : 0;
                $mrNum = is_numeric($mr) ? (int)$mr : 0;
                if ($mlNum || $mrNum) {
                    $widthStyle = "width:calc({$wVal}% - " . ($mlNum + $mrNum) . "px);";
                } else {
                    $widthStyle = "width:{$wVal}%;";
                }
            }
        }

        $wrapStyle = "box-sizing:border-box;padding:{$pt}px {$pr}px {$pb}px {$pl}px;margin:{$mt}px {$mrStr} {$mb}px {$mlStr};{$widthStyle}";
        if (!empty($s['bgColor']))      $wrapStyle .= "background:{$s['bgColor']};";
        if (!empty($s['bgImageUrl']))   $wrapStyle .= "background-image:url(" . $this->absoluteUrl($s['bgImageUrl']) . ");background-size:cover;";
        
        // Skip border-radius for button block
        if (!empty($s['borderRadius']) && $type !== 'button') {
            $wrapStyle .= "border-radius:{$s['borderRadius']}px;";
        }
        
        // Borders (Apply to all sides vs individual sides)
        $borderColor = $s['borderColor'] ?? '#e5e7eb';
        $borderAllSides = $s['borderAllSides'] ?? true;
        if ($borderAllSides) {
            if (!empty($s['borderWidth'])) {
                $wrapStyle .= "border:{$s['borderWidth']}px solid {$borderColor};";
            }
        } else {
            $top = $s['borderTopWidth'] ?? 0;
            $right = $s['borderRightWidth'] ?? 0;
            $bottom = $s['borderBottomWidth'] ?? 0;
            $left = $s['borderLeftWidth'] ?? 0;
            if ($top)    $wrapStyle .= "border-top:{$top}px solid {$borderColor};";
            if ($right)  $wrapStyle .= "border-right:{$right}px solid {$borderColor};";
            if ($bottom) $wrapStyle .= "border-bottom:{$bottom}px solid {$borderColor};";
            if ($left)   $wrapStyle .= "border-left:{$left}px solid {$borderColor};";
        }

        switch ($type) {

            case 'body': {
                return "";
            }

            case 'text': {
                $color   = $s['color']      ?? '#374151';
                $size    = $s['fontSize']   ?? 14;
                $align   = $s['textAlign']  ?? 'left';
                $lh      = $s['lineHeight'] ?? 1.6;
                $content = nl2br(e($block['content'] ?? ''));
                return "<div style=\"{$wrapStyle}\"><p style=\"margin:0;color:{$color};font-size:{$size}px;text-align:{$align};line-height:{$lh}\">{$content}</p></div>";
            }

            case 'heading': {
                $color   = $s['color']      ?? '#111827';
                $size    = $s['fontSize']   ?? 24;
                $align   = $s['textAlign']  ?? 'left';
                $weight  = $s['fontWeight'] ?? 700;
                $content = e($block['content'] ?? '');
                return "<div style=\"{$wrapStyle}\"><h2 style=\"margin:0;color:{$color};font-size:{$size}px;text-align:{$align};font-weight:{$weight};\">{$content}</h2></div>";
            }

            case 'image': {
                $src   = $block['src'] ?? '';
                $alt   = e($block['alt'] ?? '');
                $align = $s['blockAlign'] ?? $s['textAlign'] ?? 'left';
                $width = $s['width']     ?? 100;
                $link  = $block['link']  ?? '';
                if (!$src) {
                    return "<div style=\"{$wrapStyle}text-align:{$align}\"><div style=\"background:#f3f4f6;border:2px dashed #d1d5db;border-radius:6px;height:80px;\"></div></div>";
                }
                $src = e($this->absoluteUrl($src));
                $widthVal = $width === 'auto' ? 'auto' : "{$width}%";
                $imgHtml = "<img src=\"{$src}\" alt=\"{$alt}\" style=\"max-width:100%;width:{$widthVal};display:inline-block;vertical-align:top;\" />";
                $content = $link ? "<a href=\"" . e($link) . "\" target=\"_blank\" style=\"text-decoration:none;\">{$imgHtml}</a>" : $imgHtml;
                return "<div style=\"{$wrapStyle}text-align:{$align}\">{$content}</div>";
            }

            case 'button': {
                $text   = e($block['text']       ?? 'Click here');
                $href   = $block['href']         ?? '#';
                $bg     = $s['backgroundColor'] ?? '#4285f4';
                $color  = $s['textColor']        ?? '#ffffff';
                $radius = ($s['borderRadius']    ?? 6) . 'px';
                $size   = ($s['fontSize']        ?? 14) . 'px';
                $align  = $s['blockAlign']       ?? $s['textAlign'] ?? 'left';
                
                // Tooltip text
                $tooltip = !empty($block['linkTooltip']) ? ' title="' . e($block['linkTooltip']) . '"' : '';
                
                // mailto/tel prefix
                $linkType = $block['linkType'] ?? 'url';
                if ($linkType === 'email' && $href !== '#') {
                    if (!str_starts_with($href, 'mailto:')) {
                        $href = 'mailto:' . $href;
                    }
                } elseif ($linkType === 'phone' && $href !== '#') {
                    if (!str_starts_with($href, 'tel:')) {
                        $href = 'tel:' . $href;
                    }
                }
                
                // Custom Width style for button itself
                $btnWidthStyle = "display:inline-block;";
                if (isset($s['width']) && $s['width'] !== 'auto' && (int)$s['width'] < 100) {
                    $btnWidthStyle = "display:inline-block;width:" . ((int)$s['width']) . "%;box-sizing:border-box;";
                }
                
                $hrefAttr = 'href="' . e($href) . '"';
                return "<div style=\"{$wrapStyle}text-align:{$align}\"><a {$hrefAttr}{$tooltip} target=\"_blank\" style=\"{$btnWidthStyle}background:{$bg};color:{$color};border-radius:{$radius};font-size:{$size};font-weight:600;padding:10px 24px;text-decoration:none;\">{$text}</a></div>";
            }

            case 'divider': {
                $color  = $s['borderColor'] ?? '#e5e7eb';
                $bw     = ($s['dividerThickness'] ?? $s['borderWidth'] ?? 1) . 'px';
                $bstyle = $s['borderStyle']  ?? 'solid';
                $width  = $s['width'] ?? 100;
                $align  = $s['blockAlign'] ?? $s['textAlign'] ?? 'left';
                $margin = $align === 'center' ? '0 auto' : ($align === 'right' ? '0 0 0 auto' : '0 auto 0 0');
                return "<div style=\"{$wrapStyle}\"><hr style=\"border:none;border-top:{$bw} {$bstyle} {$color};width:{$width}%;margin:{$margin};\" /></div>";
            }

            case 'spacer': {
                $height = ($s['height'] ?? 24) . 'px';
                return "<div style=\"height:{$height};\"></div>";
            }

            case 'column': {
                $columnCount = $block['columnCount'] ?? 2;
                $columns     = $block['columns']     ?? [];
                $colWidths   = $block['colWidths']   ?? [];
                $gap         = 12;

                $tds = '';
                foreach ($columns as $idx => $col) {
                    $inner    = $this->renderBlocks($col['blocks'] ?? []);
                    $firstPad = $idx === 0 ? 'padding-left:0;' : '';
                    $pct = isset($colWidths[$idx]) ? $colWidths[$idx] : round(100 / max(1, $columnCount), 2);
                    $tds     .= "<td style=\"width:{$pct}%;vertical-align:top;padding-left:{$gap}px;{$firstPad}\">{$inner}</td>";
                }

                return
                    "<div style=\"{$wrapStyle}\">" .
                    "<table width=\"100%\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\" style=\"border-collapse:collapse;table-layout:fixed;\">" .
                    "<tr>{$tds}</tr>" .
                    "</table></div>";
            }

            case 'html':
                return "<div style=\"{$wrapStyle}\">" . ($block['html'] ?? $block['content'] ?? '') . "</div>";
                
            case 'video': {
                $url = $block['url'] ?? '';
                if (!$url) {
                    return "<div style=\"{$wrapStyle}\"><div style=\"background:#f3f4f6;border:2px dashed #d1d5db;border-radius:6px;height:120px;\"></div></div>";
                }
                $isThirdParty = preg_match('/youtube\.com|youtu\.be|vimeo\.com|dailymotion\.com|wistia\.com/', $url);
                if ($isThirdParty) {
                    $embedUrl = $url;
                    if (preg_match('/(?:youtube\.com\/watch\?v=|youtu\.be\/)([^&\s?]+)/', $url, $matches)) {
                        $embedUrl = "https://www.youtube.com/embed/" . $matches[1];
                    } elseif (preg_match('/vimeo\.com\/(\d+)/', $url, $matches)) {
                        $embedUrl = "https://player.vimeo.com/video/" . $matches[1];
                    }
                    return "<div style=\"{$wrapStyle}\"><iframe src=\"" . e($embedUrl) . "\" frameborder=\"0\" allowfullscreen style=\"width:100%;aspect-ratio:16/9;display:block;border:0;\"></iframe></div>";
                } else {
                    $url = e($this->absoluteUrl($url));
                    return "<div style=\"{$wrapStyle}\"><video src=\"{$url}\" controls style=\"width:100%;display:block;border-radius:4px;\"></video></div>";
                }
            }

            case 'social': {
                $align = $s['textAlign'] ?? 'center';
                $spaceBetween = $block['spaceBetween'] ?? 8;
                $iconSize = $block['iconSize'] ?? 'small';
                $iconShape = $block['iconShape'] ?? 'rounded';
                $iconTheme = $block['iconTheme'] ?? 'colored';

                $sizes = ['small' => '28px', 'medium' => '36px', 'large' => '44px'];
                $sizeVal = $sizes[$iconSize] ?? (is_numeric($iconSize) ? "{$iconSize}px" : (intval($iconSize) ? intval($iconSize) . "px" : '28px'));
                $circleSize = intval($sizeVal);
                $imgSize = round($circleSize * 0.5);

                $platforms = $this->getSocialPlatforms();
                $links = $block['links'] ?? [];
                $iconsHtml = '';
                $halfSpace = round($spaceBetween / 2);

                $radiusVal = match ($iconShape) {
                    'circle' => '50%',
                    'square' => '0',
                    default  => '6px',
                };

                foreach ($links as $link) {
                    $platformId = $link['platform'] ?? '';
                    if (!isset($platforms[$platformId])) continue;

                    $p = $platforms[$platformId];
                    $url = $link['url'] ?? '#';

                    $bg = '#6b7280';
                    if ($iconTheme === 'black') {
                        $bg = '#000000';
                    } elseif ($iconTheme === 'white') {
                        $bg = '#ffffff';
                    } else {
                        $bg = $p['color'] ?? '#6b7280';
                    }

                    $isWhiteTheme = $iconTheme === 'white';
                    $imgUrl = $isWhiteTheme ? ($p['colored_img'] ?? '') : ($p['white_img'] ?? '');
                    
                    $imgHtml = "<img src=\"{$imgUrl}\" width=\"{$imgSize}\" height=\"{$imgSize}\" alt=\"{$p['name']}\" style=\"display:inline-block;vertical-align:middle;border:0;outline:none;text-decoration:none;\" />";
                    
                    $aStyle = "display:inline-block;vertical-align:middle;text-align:center;width:{$sizeVal};height:{$sizeVal};line-height:{$sizeVal};border-radius:{$radiusVal};background:{$bg};text-decoration:none;margin:0 {$halfSpace}px 6px {$halfSpace}px;";
                    
                    $iconsHtml .= "<a href=\"" . e($url) . "\" target=\"_blank\" style=\"{$aStyle}\">{$imgHtml}</a>";
                }
                
                return "<div style=\"{$wrapStyle}text-align:{$align};\"><div style=\"display:inline-block;width:100%;text-align:{$align};\">{$iconsHtml}</div></div>";
            }

            case 'logo': {
                $business  = BusinessSettings::business($this->campaignId);
                $brandText = e($block['brandText'] ?? 'BrandName');
                if (($brandText === 'BrandName' || $brandText === 'CRMfic' || !$brandText) && !empty($business['name'])) {
                    $brandText = e($business['name']);
                }

                $src       = $block['src'] ?? '';
                if (!$src && !empty($business['logo'])) {
                    $src = $business['logo'];
                }
                $alt       = e($block['alt'] ?? '');
                $align     = $s['blockAlign'] ?? $s['textAlign'] ?? 'center';
                $width     = $s['width']     ?? 25;
                $link      = $block['link']  ?? '';
                $logoType  = $block['logoType'] ?? 'image';

                $innerHtml = '';
                if ($logoType === 'image') {
                    if ($src) {
                        $absSrc = e($this->absoluteUrl($src));
                        $innerHtml .= "<img src=\"{$absSrc}\" alt=\"{$alt}\" style=\"max-width:100%;width:{$width}%;display:inline-block;vertical-align:middle;\" />";
                    }
                } elseif ($logoType === 'text') {
                    $ff = $s['fontFamily'] ?? 'sans-serif';
                    $fw = $s['fontWeight'] ?? 'bold';
                    $fs = ($s['fontSize'] ?? 24) . 'px';
                    $color = $s['color'] ?? '#333333';
                    $innerHtml .= "<span style=\"font-family:{$ff};font-weight:{$fw};font-size:{$fs};color:{$color};line-height:1;display:inline-block;vertical-align:middle;\">{$brandText}</span>";
                } else {
                    $ff = $s['fontFamily'] ?? 'sans-serif';
                    $fw = $s['fontWeight'] ?? 'bold';
                    $fs = ($s['fontSize'] ?? 24) . 'px';
                    $color = $s['color'] ?? '#333333';

                    $imgHtml = '';
                    if ($src) {
                        $absSrc = e($this->absoluteUrl($src));
                        $marginStyle = ($logoType === 'image-text-stacked') ? 'margin-bottom:8px;' : 'margin-right:12px;';
                        $imgHtml = "<img src=\"{$absSrc}\" alt=\"{$alt}\" style=\"max-width:100%;width:{$width}%;display:inline-block;vertical-align:middle;{$marginStyle}\" />";
                    }
                    $textHtml = "<span style=\"font-family:{$ff};font-weight:{$fw};font-size:{$fs};color:{$color};line-height:1;display:inline-block;vertical-align:middle;\">{$brandText}</span>";

                    if ($logoType === 'image-text-stacked') {
                        $innerHtml = $imgHtml . "<br />" . $textHtml;
                    } else {
                        $innerHtml = $imgHtml . $textHtml;
                    }
                }

                $aStyle = "display:inline-block;text-decoration:none;vertical-align:middle;";
                $content = $link ? "<a href=\"" . e($link) . "\" target=\"_blank\" style=\"{$aStyle}\">{$innerHtml}</a>" : "<div style=\"{$aStyle}\">{$innerHtml}</div>";
                return "<div style=\"{$wrapStyle}text-align:{$align}\">{$content}</div>";
            }

            case 'footer': {
                $emailSettings = BusinessSettings::emailSettings($this->campaignId);

                $color   = $s['color']      ?? '#9ca3af';
                $size    = $s['fontSize']   ?? 11;
                $align   = $s['textAlign']  ?? 'center';
                $lh      = $s['lineHeight'] ?? 1.8;

                $content = e($block['content'] ?? '');
                $defaultNotice1 = "You're receiving this email because you subscribed to our newsletter.";
                $defaultNotice2 = "You're receiving this email because you opted in at our website.";
                
                $isDefaultNotice = !$content || 
                                   $content === $defaultNotice1 || 
                                   $content === $defaultNotice2 || 
                                   str_contains(strtolower($content), 'themefic') || 
                                   str_contains(strtolower($content), 'your company') ||
                                   str_contains(strtolower($content), 'subscribed to our newsletter');

                if ($isDefaultNotice) {
                    $content = e($emailSettings['footer_notice']);
                }

                $copyright = e($block['copyright'] ?? '');
                $year = date('Y');
                $defaultCopyright1 = "© {$year} Your Company · All rights reserved";
                $defaultCopyright2 = "© {$year} CRMfic · All rights reserved";
                $defaultCopyright3 = "© {$year} CRMfic - All rights reserved";
                
                $isDefaultCopyright = !$copyright || 
                                      $copyright === $defaultCopyright1 || 
                                      $copyright === $defaultCopyright2 || 
                                      $copyright === $defaultCopyright3 || 
                                      str_contains(strtolower($copyright), 'themefic') ||
                                      str_contains(strtolower($copyright), 'crmfic') || 
                                      str_contains(strtolower($copyright), 'your company');

                if ($isDefaultCopyright) {
                    $copyright = e($emailSettings['footer_copyright']);
                }
                $unsubscribeUrl = $this->trackingUrl('unsubscribe');

                $links = [];
                if ($emailSettings['footer_show_unsubscribe']) {
                    $links[] = "<a href=\"{$unsubscribeUrl}\" style=\"color:#4285f4;text-decoration:none;\">Unsubscribe</a>";
                }
                if ($emailSettings['footer_show_privacy']) {
                    $privacyUrl = e($emailSettings['footer_privacy_url'] ?: '#');
                    $links[] = "<a href=\"{$privacyUrl}\" style=\"color:#4285f4;text-decoration:none;\">Privacy Policy</a>";
                }
                $linksRow = $links ? '<p style="margin:0 0 4px 0;">' . implode(' · ', $links) . '</p>' : '';

                return "<div style=\"{$wrapStyle}text-align:{$align};line-height:{$lh};font-size:{$size}px;color:{$color};\">" .
                    "<p style=\"margin:0 0 4px 0;\">{$content}</p>" .
                    $linksRow .
                    "<p style=\"margin:0;\">{$copyright}</p>" .
                    "</div>";
            }
        }

        return '';
    }

    private function getSocialPlatforms(): array
    {
        return [
            'facebook'  => [
                'name' => 'Facebook',
                'color' => '#1877F2',
                'white_img' => 'https://img.icons8.com/ios-filled/48/ffffff/facebook-new.png',
                'colored_img' => 'https://img.icons8.com/color/48/facebook-new.png',
            ],
            'instagram' => [
                'name' => 'Instagram',
                'color' => '#E4405F',
                'white_img' => 'https://img.icons8.com/ios-filled/48/ffffff/instagram-new.png',
                'colored_img' => 'https://img.icons8.com/color/48/instagram-new.png',
            ],
            'twitter'   => [
                'name' => 'X (Twitter)',
                'color' => '#000000',
                'white_img' => 'https://img.icons8.com/ios-filled/48/ffffff/twitterx--v1.png',
                'colored_img' => 'https://img.icons8.com/color/48/twitterx--v1.png',
            ],
            'linkedin'  => [
                'name' => 'LinkedIn',
                'color' => '#0A66C2',
                'white_img' => 'https://img.icons8.com/ios-filled/48/ffffff/linkedin.png',
                'colored_img' => 'https://img.icons8.com/color/48/linkedin.png',
            ],
            'youtube'   => [
                'name' => 'YouTube',
                'color' => '#FF0000',
                'white_img' => 'https://img.icons8.com/ios-filled/48/ffffff/youtube-play.png',
                'colored_img' => 'https://img.icons8.com/color/48/youtube-play.png',
            ],
            'tiktok'    => [
                'name' => 'TikTok',
                'color' => '#010101',
                'white_img' => 'https://img.icons8.com/ios-filled/48/ffffff/tiktok.png',
                'colored_img' => 'https://img.icons8.com/color/48/tiktok.png',
            ],
            'pinterest' => [
                'name' => 'Pinterest',
                'color' => '#BD081C',
                'white_img' => 'https://img.icons8.com/ios-filled/48/ffffff/pinterest.png',
                'colored_img' => 'https://img.icons8.com/color/48/pinterest--v1.png',
            ],
            'discord'   => [
                'name' => 'Discord',
                'color' => '#5865F2',
                'white_img' => 'https://img.icons8.com/ios-filled/48/ffffff/discord-logo.png',
                'colored_img' => 'https://img.icons8.com/color/48/discord-logo.png',
            ],
            'whatsapp'  => [
                'name' => 'WhatsApp',
                'color' => '#25D366',
                'white_img' => 'https://img.icons8.com/ios-filled/48/ffffff/whatsapp.png',
                'colored_img' => 'https://img.icons8.com/color/48/whatsapp--v1.png',
            ],
            'telegram'  => [
                'name' => 'Telegram',
                'color' => '#229ED9',
                'white_img' => 'https://img.icons8.com/ios-filled/48/ffffff/telegram-app.png',
                'colored_img' => 'https://img.icons8.com/color/48/telegram-app.png',
            ],
            'github'    => [
                'name' => 'GitHub',
                'color' => '#181717',
                'white_img' => 'https://img.icons8.com/ios-filled/48/ffffff/github.png',
                'colored_img' => 'https://img.icons8.com/color/48/github--v1.png',
            ],
            'reddit'    => [
                'name' => 'Reddit',
                'color' => '#FF4500',
                'white_img' => 'https://img.icons8.com/ios-filled/48/ffffff/reddit.png',
                'colored_img' => 'https://img.icons8.com/color/48/reddit.png',
            ],
            'twitch'    => [
                'name' => 'Twitch',
                'color' => '#9146FF',
                'white_img' => 'https://img.icons8.com/ios-filled/48/ffffff/twitch.png',
                'colored_img' => 'https://img.icons8.com/color/48/twitch.png',
            ],
            'spotify'   => [
                'name' => 'Spotify',
                'color' => '#1DB954',
                'white_img' => 'https://img.icons8.com/ios-filled/48/ffffff/spotify.png',
                'colored_img' => 'https://img.icons8.com/color/48/spotify.png',
            ],
            'behance'   => [
                'name' => 'Behance',
                'color' => '#1769FF',
                'white_img' => 'https://img.icons8.com/ios-filled/48/ffffff/behance.png',
                'colored_img' => 'https://img.icons8.com/color/48/behance.png',
            ],
            'dribbble'  => [
                'name' => 'Dribbble',
                'color' => '#EA4C89',
                'white_img' => 'https://img.icons8.com/ios-filled/48/ffffff/dribbble.png',
                'colored_img' => 'https://img.icons8.com/color/48/dribbble.png',
            ],
            'medium'    => [
                'name' => 'Medium',
                'color' => '#000000',
                'white_img' => 'https://img.icons8.com/ios-filled/48/ffffff/medium.png',
                'colored_img' => 'https://img.icons8.com/color/48/medium-monogram.png',
            ],
            'snapchat'  => [
                'name' => 'Snapchat',
                'color' => '#FFFC00',
                'white_img' => 'https://img.icons8.com/ios-filled/48/ffffff/snapchat.png',
                'colored_img' => 'https://img.icons8.com/color/48/snapchat.png',
            ],
        ];
    }

    private function appendUtmToAllLinks(string $html): string
    {
        return preg_replace_callback(
            '/href="([^"]+)"/i',
            function ($m) {
                $url = $m[1];

                // Skip non-trackable links
                if (
                    $url === '#' ||
                    str_starts_with($url, 'mailto:') ||
                    str_starts_with($url, 'tel:') ||
                    str_contains($url, '/track/') ||
                    str_contains($url, '/unsubscribe/')
                ) {
                    return $m[0];
                }

                $url = $this->appendUtmParameters($url);
                return 'href="' . e($url) . '"';
            },
            $html
        );
    }

    private function appendUtmParameters(string $url): string
    {
        if (!$this->utmData) {
            return $url;
        }

        // Clean up empty params
        $params = array_filter([
            'utm_source'   => $this->utmData['utm_source'] ?? null,
            'utm_medium'   => $this->utmData['utm_medium'] ?? null,
            'utm_campaign' => $this->utmData['utm_campaign'] ?? null,
            'utm_term'     => $this->utmData['utm_term'] ?? null,
            'utm_content'  => $this->utmData['utm_content'] ?? null,
        ]);

        if (empty($params)) {
            return $url;
        }

        $query = http_build_query($params);

        // Parse existing URL
        $parsed = parse_url($url);
        if ($parsed === false) {
            return $url;
        }

        $scheme   = isset($parsed['scheme']) ? $parsed['scheme'] . '://' : '';
        $host     = $parsed['host'] ?? '';
        $port     = isset($parsed['port']) ? ':' . $parsed['port'] : '';
        $user     = $parsed['user'] ?? '';
        $pass     = isset($parsed['pass']) ? ':' . $parsed['pass']  : '';
        $pass     = ($user || $pass) ? "$pass@" : '';
        $path     = $parsed['path'] ?? '';
        $existingQuery = $parsed['query'] ?? '';
        $fragment = isset($parsed['fragment']) ? '#' . $parsed['fragment'] : '';

        if ($existingQuery) {
            $newQuery = $existingQuery . '&' . $query;
        } else {
            $newQuery = $query;
        }

        return "{$scheme}{$user}{$pass}{$host}{$port}{$path}?{$newQuery}{$fragment}";
    }

    public function defaultBlocks(string $title = 'Welcome'): array
    {
        return [
            [
                'id' => 'default_logo',
                'type' => 'logo',
                'logoType' => 'text',
                'brandText' => 'themefic',
                'styles' => [
                    'paddingTop' => 32, 'paddingRight' => 24, 'paddingBottom' => 16, 'paddingLeft' => 24,
                    'fontSize' => 24, 'color' => '#4f46e5', 'textAlign' => 'center', 'fontWeight' => 'bold'
                ]
            ],
            [
                'id' => 'default_heading',
                'type' => 'heading',
                'content' => $title,
                'styles' => [
                    'paddingTop' => 8, 'paddingRight' => 24, 'paddingBottom' => 8, 'paddingLeft' => 24,
                    'fontSize' => 26, 'color' => '#111827', 'textAlign' => 'center', 'fontWeight' => 700
                ]
            ],
            [
                'id' => 'default_text',
                'type' => 'text',
                'content' => 'Thank you for being a valued member of our community. Get ready for exciting updates and exclusive content delivered straight to your inbox.',
                'styles' => [
                    'paddingTop' => 16, 'paddingRight' => 40, 'paddingBottom' => 24, 'paddingLeft' => 40,
                    'fontSize' => 16, 'color' => '#4b5563', 'textAlign' => 'center'
                ]
            ]
        ];
    }
}
