<?php
declare(strict_types=1);

if (!defined('ABSPATH')) { exit; }

/**
 * Site Footer element renderer (shared).
 *
 * Phase 1, step 32. Frontend (~285 lines) was significantly more
 * featureful than the editor (~200 lines):
 *
 *   - `single_row` layout (compact one-line footer for marketing
 *     pages where a full 4-column footer is overkill)
 *   - Mobile responsive CSS that hides single_row footers entirely
 *     on phones (cleaner reading flow), and collapses multi-column
 *     footers to one column
 *   - Empty-column skip (a footer with no links + no title doesn't
 *     render a ghost heading)
 *   - `impulse_get_social_svg()` helper for social icons (was
 *     hardcoded inline SVG paths in editor)
 *   - Footer ID + scoped CSS selectors (link/hover colors via id)
 *   - Tagline appended to single_row copyright ("© 2026 Brand,
 *     tagline. All rights reserved.")
 *
 * Editor had:
 *   - `impulse_device_val()` for `padding_top` per current preview
 *     device. Preserved here via the `$context`-aware $read helper.
 *
 * Frontend canonical adopted across the board. The editor branch
 * uses `$read('padding_top', 60)` which honours device-overrides
 * only when running in editor context.
 *
 * Page-element lookup: the frontend looks up the header element from
 * the page-level `$elements` list to inherit its logo. Editor used
 * `$elementTree` for the same purpose. The shared renderer reads from
 * `$GLOBALS['impulse_page_elements']` (set by the outer rendering
 * loop in both contexts), falling back to a per-context global.
 *
 * @sideeffect wp_add_inline_style('instinctor-page-inline', $css)
 *             for the per-instance link colors + responsive CSS.
 */
function impulse_element_render_footer($el, array $settings, string $context): string {
    if (is_object($el)) $el = (array) $el;
    $isEditor = ($context === 'editor');
    $device   = $isEditor ? (string) ($GLOBALS['impulse_preview_device'] ?? 'desktop') : 'desktop';

    $read = function (string $key, $default) use ($settings, $isEditor, $device) {
        if ($isEditor && function_exists('impulse_device_val')) {
            return impulse_device_val($settings, $key, $device, $default);
        }
        return $settings[$key] ?? $default;
    };

    $layout       = (string) ($settings['layout']        ?? '4-col');
    $bgColor      = (string) ($settings['bg_color']      ?? '#1d2327');
    $textColor    = (string) ($settings['text_color']    ?? '#999999');
    $headingColor = (string) ($settings['heading_color'] ?? '#ffffff');
    $linkColor      = $textColor;
    $linkHoverColor = $headingColor;
    // Per-footer typography (Sergei 2026-06-24): title/link size + line height.
    // Unset falls back to the prior hardcoded values.
    $fTitleSize = (isset($settings['footer_title_size']) && $settings['footer_title_size'] !== '') ? max(8, min(48, (int) $settings['footer_title_size'])) : 14;
    $fLinkSize  = (isset($settings['footer_link_size'])  && $settings['footer_link_size']  !== '') ? max(8, min(40, (int) $settings['footer_link_size']))  : 14;
    $fLineH     = (isset($settings['footer_line_height']) && $settings['footer_line_height'] !== '') ? max(80, min(260, (int) $settings['footer_line_height'])) : 130;
    $borderColor    = function_exists('impulse_derive_border')
        ? impulse_derive_border($bgColor)
        : '#333333';
    // Neutralise the divider to greyscale. Deriving a border from a tinted
    // near-black (the #030b0d footer bg is faintly teal) amplifies the tint
    // into a visibly coloured line (the "green" divider). Collapse it to a grey
    // of the same lightness so the rule (greyscale UI) holds on any bg. 2026-07-03.
    if (preg_match('/^#([0-9a-fA-F]{6})$/', $borderColor, $_bm)) {
        $_br = hexdec(substr($_bm[1], 0, 2));
        $_bg = hexdec(substr($_bm[1], 2, 2));
        $_bb = hexdec(substr($_bm[1], 4, 2));
        $_grey = (int) round(0.299 * $_br + 0.587 * $_bg + 0.114 * $_bb);
        $borderColor = sprintf('#%02x%02x%02x', $_grey, $_grey, $_grey);
    }
    // Explicit divider colour (footer panel "Line" swatch) overrides the default.
    if (!empty($settings['line_color'])) $borderColor = $settings['line_color'];

    $showLogo = !empty($settings['show_logo']);
    $logoImg  = '';
    $logoHeight = 32;
    if ($showLogo) {
        // Page-level header lookup. Both contexts populate
        // $GLOBALS['impulse_page_elements'] before calling into
        // the chrome renderer, but be defensive — drop the logo
        // if the lookup fails rather than 500.
        $pageEls = $GLOBALS['impulse_page_elements'] ?? null;
        if (is_array($pageEls)) {
            foreach ($pageEls as $_el) {
                $arr = is_object($_el) ? (array) $_el : $_el;
                $t   = $arr['type'] ?? ($arr['section_type'] ?? '');
                if ($t === 'header') {
                    $s = $arr['settings'] ?? [];
                    if (is_object($s)) $s = (array) $s;
                    $logoImg = (string) ($s['logo'] ?? '');
                    break;
                }
            }
        }
    }

    // Column titles + links
    $col1Title = (string) ($settings['col1_title'] ?? 'Company');
    $col2Title = (string) ($settings['col2_title'] ?? 'Support');
    $col3Title = (string) ($settings['col3_title'] ?? 'Legal');

    $showSocial  = ($settings['show_social'] ?? true) !== false;
    $socialLinks = [];
    if ($showSocial && function_exists('impulse_get_social_links')) {
        $socialLinks = impulse_get_social_links();
        if (!is_array($socialLinks)) $socialLinks = [];
    }

    // Store info — short tagline only (long description is for SEO meta).
    // The footer block's own `site_name` overrides the store name for the
    // copyright line, so a demo/sub-brand (e.g. instructor.instinctor.com) can
    // read "Instinctor" in the footer while its store name and email sender stay
    // the demo studio name. Client footers leave site_name unset -> store name.
    $footerSiteName = (string) ($settings['site_name'] ?? '');
    $siteName    = $footerSiteName !== '' ? $footerSiteName : (class_exists('\\Instinctor\\Core\\Config')
        ? (string) \Instinctor\Core\Config::get('instinctor_store_name', (function_exists('get_bloginfo') ? get_bloginfo('name') : ''))
        : (function_exists('get_bloginfo') ? (string) get_bloginfo('name') : ''));
    $siteTagline = class_exists('\\Instinctor\\Core\\Config')
        ? (string) \Instinctor\Core\Config::get('instinctor_store_tagline', '')
        : '';
    $siteDesc    = $siteTagline;

    $showCopyright = ($settings['show_copyright'] ?? true) !== false;
    // Brand name + slogan toggles (Sergei 2026-07-17): the 4-col brand column
    // rendered the site name unconditionally and the tagline whenever the store
    // tagline was set, with no way to switch either off. Default on so existing
    // pages keep their look; unchecking in the panel saves false.
    $showBrand  = ($settings['show_brand']  ?? true) !== false;
    $showSlogan = ($settings['show_slogan'] ?? true) !== false;
    $copyrightText = '© ' . gmdate('Y') . ' ' . $siteName . '. All rights reserved.';
    $showPayments  = !empty($settings['show_payments']);

    $rawId    = (string) ($el['id'] ?? uniqid());
    $rawId    = preg_replace('/[^a-z0-9_-]/i', '', $rawId);
    $footerId = 'impulse-footer-' . esc_attr($rawId); // Late-escape per WP coding standards

    // ── CSS ──────────────────────────────────────────────────────────────
    ob_start();
    echo '#' . esc_attr($footerId) . ' a{color:' . esc_attr($linkColor) . ';text-decoration:none;transition:color 0.2s}';
    echo '#' . esc_attr($footerId) . ' a:hover{color:' . esc_attr($linkHoverColor) . '}';
    echo '#' . esc_attr($footerId) . ' .footer-column ul{list-style:none;margin:0;padding:0}';
    // Denser line spacing (Sergei 2026-06-23).
    echo '#' . esc_attr($footerId) . ' .footer-column li{margin-bottom:6px;line-height:' . (int) $fLineH . '%;break-inside:avoid}';
    echo '#' . esc_attr($footerId) . ' .footer-column li a{font-size:' . (int) $fLinkSize . 'px;line-height:' . (int) $fLineH . '%}';
    echo '#' . esc_attr($footerId) . ' .footer-column img{height:' . (int) $logoHeight . 'px}';
    // Last column right-aligned on desktop (rest of footer aligns to
    // divider edges; without this the right side reads empty).
    echo '@media (min-width:769px){';
    echo '#' . esc_attr($footerId) . ' .footer-columns > .footer-column:last-child{text-align:right}';
    // Multi-column link lists read cleaner left-aligned, even at the right edge.
    echo '#' . esc_attr($footerId) . ' .footer-columns > .footer-column.footer-col-multi:last-child{text-align:left}';
    echo '}';
    // Mobile: stack columns and centre.
    echo '@media (max-width:768px){';
    echo '#' . esc_attr($footerId) . ' .footer-columns{grid-template-columns:1fr!important;text-align:center}';
    echo '#' . esc_attr($footerId) . ' .footer-column ul{display:inline-block;text-align:center}';
    // Never split a link list into sub-columns on phones.
    echo '#' . esc_attr($footerId) . ' .footer-column ul{column-count:1!important}';
    // Single_row (slim legal) footer stays visible on mobile and stacks:
    // copyright over the links, centered, so the legal links stay reachable.
    if ($layout === 'single_row') {
        echo '#' . esc_attr($footerId) . ' > div{flex-direction:column;text-align:center;gap:10px}';
        echo '#' . esc_attr($footerId) . ' > div > div:last-child{justify-content:center}';
    }
    echo '}';
    // Tablet: 2 columns.
    echo '@media (max-width:1024px) and (min-width:769px){';
    echo '#' . esc_attr($footerId) . ' .footer-columns{grid-template-columns:1fr 1fr!important}';
    echo '}';
    $css = ob_get_clean();
    if (function_exists('wp_add_inline_style')) {
        wp_add_inline_style('instinctor-page-inline', $css);
    }

    // Grid columns count.
    $gridCols = $layout === '3-col' ? 3 : 4;
    if ($layout === 'centered' || $layout === 'minimal') $gridCols = 1;

    // Padding. Single_row uses tight fixed padding; multi-column honours
    // the saved/device-resolved padding_top.
    if ($layout === 'single_row') {
        $fPad       = 14;
        $fPadBottom = 14;
        $fSidePad   = 32;
    } else {
        $fPad       = intval($read('padding_top', 60));
        $fPadBottom = max(intval($fPad * 0.5), 20);
        $fSidePad   = 40;
    }

    // ── Markup ───────────────────────────────────────────────────────────
    ob_start();
    $footerStyle = 'background:' . esc_attr($bgColor) . ';color:' . esc_attr($textColor) . ';padding:' . $fPad . 'px ' . $fSidePad . 'px ' . $fPadBottom . 'px ' . $fSidePad . 'px';
    echo '<footer id="' . esc_attr($footerId) . '" class="impulse-footer" style="' . esc_attr($footerStyle) . '">';

    if ($layout === 'single_row') {
        $allLinks = array_merge(
            $settings['col1_links'] ?? [],
            $settings['col2_links'] ?? [],
            $settings['col3_links'] ?? []
        );
        echo '<div style="max-width:var(--impulse-content-max-width, 1280px);margin:0 auto;display:flex;align-items:center;justify-content:space-between;gap:24px;flex-wrap:wrap">';
        echo '<div style="font-size:13px;color:' . esc_attr($textColor) . '">';
        if ($showCopyright) {
            $year  = gmdate('Y');
            // Slim legal line: brand + rights only (no tagline).
            $line  = '© ' . $year . ' ' . $siteName . '. All rights reserved.';
            echo esc_html(html_entity_decode((string) $line, ENT_QUOTES, 'UTF-8'));
        }
        echo '</div>';
        echo '<div style="display:flex;align-items:center;gap:24px;font-size:14px">';
        foreach ($allLinks as $link) {
            $lbl = trim((string) ($link['label'] ?? ''));
            $url = trim((string) ($link['url']   ?? ''));
            if ($lbl === '' || $url === '' || $url === '#') continue;
            echo '<a href="' . esc_url($url) . '" style="color:' . esc_attr($textColor) . '">' . esc_html(html_entity_decode((string) $lbl, ENT_QUOTES, 'UTF-8')) . '</a>';
        }
        if ($showSocial && !empty($socialLinks)) {
            echo '<div style="display:flex;gap:14px;align-items:center">';
            impulse_site_footer__render_socials($socialLinks, $linkColor);
            echo '</div>';
        }
        echo '</div>';
        echo '</div>';
    } elseif ($layout === 'minimal') {
        echo '<div style="max-width:var(--impulse-content-max-width, 1200px);margin:0 auto;display:flex;flex-direction:column;align-items:center;gap:16px">';
        if ($showCopyright) {
            echo '<div style="font-size:13px">' . esc_html(html_entity_decode((string) $copyrightText, ENT_QUOTES, 'UTF-8')) . '</div>';
        }
        if ($showSocial && !empty($socialLinks)) {
            echo '<div style="display:flex;gap:16px">';
            impulse_site_footer__render_socials($socialLinks, $linkColor);
            echo '</div>';
        }
        echo '</div>';
    } elseif ($layout === 'centered') {
        echo '<div style="max-width:600px;margin:0 auto;text-align:center">';
        if ($showLogo && $logoImg !== '') {
            echo '<img src="' . esc_url($logoImg) . '" alt="Logo" style="' . esc_attr('height:' . (int) $logoHeight . 'px;margin-bottom:24px') . '">';
        } elseif ($showLogo) {
            echo '<div style="font-size:24px;font-weight:700;color:' . esc_attr($headingColor) . ';margin-bottom:24px">' . esc_html(html_entity_decode((string) $siteName, ENT_QUOTES, 'UTF-8')) . '</div>';
        }
        if ($showSocial && !empty($socialLinks)) {
            echo '<div style="display:flex;gap:16px;justify-content:center;margin-bottom:30px">';
            impulse_site_footer__render_socials($socialLinks, $linkColor);
            echo '</div>';
        }
        if ($showCopyright) {
            echo '<div style="font-size:13px">' . esc_html(html_entity_decode((string) $copyrightText, ENT_QUOTES, 'UTF-8')) . '</div>';
        }
        echo '</div>';
    } else {
        // Multi-column (3-col / 4-col).
        echo '<div class="footer-columns" style="display:grid;grid-template-columns:repeat(' . (int) $gridCols . ',1fr);gap:40px;max-width:var(--impulse-content-max-width, 1200px);margin:0 auto">';

        if ($layout === '4-col') {
            echo '<div class="footer-column">';
            if ($showLogo && $logoImg !== '') {
                echo '<img src="' . esc_url($logoImg) . '" alt="Logo" style="' . esc_attr('height:' . (int) $logoHeight . 'px;margin-bottom:20px') . '">';
            }
            if ($showBrand) {
                echo '<div style="font-size:18px;font-weight:600;color:' . esc_attr($headingColor) . ';margin-bottom:12px">' . esc_html(html_entity_decode((string) $siteName, ENT_QUOTES, 'UTF-8')) . '</div>';
            }
            if ($showSlogan && $siteDesc !== '') {
                echo '<p style="font-size:14px;line-height:1.6;margin:0">' . esc_html(html_entity_decode((string) $siteDesc, ENT_QUOTES, 'UTF-8')) . '</p>';
            }
            echo '</div>';
        }

        $renderColumn = function ($title, $links) use ($headingColor, $fTitleSize) {
            $hasLinks = !empty($links) && is_array($links);
            if ($title === '' && !$hasLinks) return;
            // No column shows more than 3 items: split into ceil(n/3)
            // sub-columns (5 links → 2, 6 → 2). Sergei 2026-06-23.
            $valid = 0;
            if ($hasLinks) { foreach ($links as $l) { if (!empty($l['label'])) $valid++; } }
            $ulCols = max(1, (int) ceil($valid / 3));
            echo '<div class="footer-column' . ($ulCols > 1 ? ' footer-col-multi' : '') . '">';
            if ($title !== '') {
                echo '<div style="font-size:' . (int) $fTitleSize . 'px;font-weight:600;color:' . esc_attr($headingColor) . ';margin-bottom:16px">' . esc_html(html_entity_decode((string) $title, ENT_QUOTES, 'UTF-8')) . '</div>';
            }
            if ($hasLinks) {
                if ($ulCols > 1) {
                    echo '<ul style="' . esc_attr('column-count:' . (int) $ulCols . ';column-gap:36px') . '">';
                } else {
                    echo '<ul>';
                }
                foreach ($links as $link) {
                    if (!empty($link['label'])) {
                        echo '<li><a href="' . esc_url((string) ($link['url'] ?? '#')) . '">' . esc_html(html_entity_decode((string) $link['label'], ENT_QUOTES, 'UTF-8')) . '</a></li>';
                    }
                }
                echo '</ul>';
            }
            echo '</div>';
        };

        $col1Links = $settings['col1_links'] ?? [];
        $col2Links = $settings['col2_links'] ?? [];
        $col3Links = $settings['col3_links'] ?? [];
        if (is_string($col1Links)) $col1Links = json_decode($col1Links, true) ?: [];
        if (is_string($col2Links)) $col2Links = json_decode($col2Links, true) ?: [];
        if (is_string($col3Links)) $col3Links = json_decode($col3Links, true) ?: [];

        $renderColumn($col1Title, $col1Links);
        $renderColumn($col2Title, $col2Links);
        $renderColumn($col3Title, $col3Links);

        echo '</div>';

        // Bottom bar
        if ($showCopyright || ($showSocial && !empty($socialLinks))) {
            echo '<div style="max-width:var(--impulse-content-max-width, 1200px);margin:40px auto 0;padding-top:30px;border-top:1px solid ' . esc_attr($borderColor) . ';display:flex;flex-direction:column;align-items:center;gap:16px">';
            if ($showCopyright) {
                echo '<div style="font-size:13px">' . esc_html(html_entity_decode((string) $copyrightText, ENT_QUOTES, 'UTF-8')) . '</div>';
            }
            if ($showSocial && !empty($socialLinks)) {
                echo '<div style="display:flex;gap:16px">';
                impulse_site_footer__render_socials($socialLinks, $linkColor);
                echo '</div>';
            }
            if ($showPayments) {
                echo '<div style="display:flex;gap:8px">';
                if (($settings['pay_visa']       ?? null) !== false) echo '<div style="background:#fff;padding:4px 8px;border-radius:4px"><svg width="32" height="20" viewBox="0 0 32 20"><rect fill="#1A1F71" width="32" height="20" rx="2"/><text x="16" y="13" fill="#fff" font-size="6" text-anchor="middle">VISA</text></svg></div>';
                if (($settings['pay_mastercard'] ?? null) !== false) echo '<div style="background:#fff;padding:4px 8px;border-radius:4px"><svg width="32" height="20" viewBox="0 0 32 20"><circle cx="12" cy="10" r="7" fill="#EB001B"/><circle cx="20" cy="10" r="7" fill="#F79E1B"/></svg></div>';
                if (($settings['pay_amex']       ?? null) !== false) echo '<div style="background:#006FCF;padding:4px 8px;border-radius:4px"><svg width="32" height="20"><text x="16" y="13" fill="#fff" font-size="6" font-weight="bold" text-anchor="middle">AMEX</text></svg></div>';
                if (($settings['pay_paypal']     ?? null) !== false) echo '<div style="background:#fff;padding:4px 8px;border-radius:4px"><svg width="32" height="20"><text x="16" y="13" fill="#003087" font-size="6" font-weight="bold" text-anchor="middle">PayPal</text></svg></div>';
                echo '</div>';
            }
            echo '</div>';
        }
    }

    echo '</footer>';

    return (string) ob_get_clean();
}

/**
 * Render the social icon list. Uses `impulse_get_social_svg()` when
 * available (frontend ships it as a shared helper); falls back to a
 * minimal inline-icon set otherwise. Kept out of the main function so
 * the four layout branches can each pull it in without duplication.
 */
function impulse_site_footer__render_socials(array $socialLinks, string $linkColor): void {
    $fallbackSvg = [
        'facebook'  => '<path fill="' . esc_attr($linkColor) . '" d="M18 2h-3a5 5 0 0 0-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 0 1 1-1h3z"/>',
        'instagram' => '<rect fill="none" stroke="' . esc_attr($linkColor) . '" stroke-width="2" x="2" y="2" width="20" height="20" rx="5"/><path fill="none" stroke="' . esc_attr($linkColor) . '" stroke-width="2" d="M16 11.37A4 4 0 1 1 12.63 8 4 4 0 0 1 16 11.37z"/>',
        'x'         => '<path fill="' . esc_attr($linkColor) . '" d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231z"/>',
        'linkedin'  => '<path fill="' . esc_attr($linkColor) . '" d="M16 8a6 6 0 0 1 6 6v7h-4v-7a2 2 0 0 0-2-2 2 2 0 0 0-2 2v7h-4v-7a6 6 0 0 1 6-6z"/><rect fill="' . esc_attr($linkColor) . '" x="2" y="9" width="4" height="12"/><circle fill="' . esc_attr($linkColor) . '" cx="4" cy="4" r="2"/>',
        'youtube'   => '<path fill="' . esc_attr($linkColor) . '" d="M22.54 6.42a2.78 2.78 0 0 0-1.94-2C18.88 4 12 4 12 4s-6.88 0-8.6.46a2.78 2.78 0 0 0-1.94 2A29 29 0 0 0 1 11.75a29 29 0 0 0 .46 5.33A2.78 2.78 0 0 0 3.4 19c1.72.46 8.6.46 8.6.46s6.88 0 8.6-.46a2.78 2.78 0 0 0 1.94-2 29 29 0 0 0 .46-5.25 29 29 0 0 0-.46-5.33z"/><polygon fill="#fff" points="9.75 15.02 15.5 11.75 9.75 8.48 9.75 15.02"/>',
    ];

    foreach ($socialLinks as $link) {
        $platform = (string) ($link['platform'] ?? 'facebook');
        $url      = (string) ($link['url']      ?? '');
        if ($url === '' || $url === '#') continue;
        if (function_exists('impulse_get_social_svg')) {
            echo '<a href="' . esc_url($url) . '" target="_blank" rel="noopener">' . wp_kses(impulse_get_social_svg($platform, $linkColor), impulse_svg_allowed()) . '</a>';
        } else {
            $svg = $fallbackSvg[$platform] ?? $fallbackSvg['facebook'];
            echo '<a href="' . esc_url($url) . '" target="_blank" rel="noopener"><svg width="20" height="20" viewBox="0 0 24 24">' . wp_kses($svg, impulse_svg_allowed()) . '</svg></a>';
        }
    }
}
