{% extends "base.html" %}

{% block title %}{{ subject }} - {{ brand_name }}{% endblock %}

{% block content %}
    <div class="ownmail-email-detail">
        <div class="ownmail-email-header">
            <div class="ownmail-email-header-top">
                <h2>{{ subject or '(No subject)' }}</h2>
                <div class="ownmail-email-menu">
                    <button class="ownmail-email-menu-btn" onclick="toggleEmailMenu(event)"><span></span><span></span><span></span></button>
                    <div class="ownmail-email-menu-dropdown" id="ownmail-email-menu-dropdown">
                        {% if has_external_images %}
                        <a href="#" id="menu-load-images" {% if not images_blocked %}style="display: none;"{% endif %} onclick="loadImages(); return false;">Load images</a>
                        <a href="#" id="menu-block-images" {% if images_blocked %}style="display: none;"{% endif %} onclick="blockImages(); return false;">Block images</a>
                        {% if sender_email %}
                        <a href="#" id="menu-trust-sender" {% if sender_is_trusted %}style="display: none;"{% endif %} onclick="trustSender(); return false;">Always trust this sender</a>
                        <a href="#" id="menu-untrust-sender" {% if not sender_is_trusted %}style="display: none;"{% endif %} onclick="untrustSender(); return false;">Untrust this sender</a>
                        {% endif %}
                        <hr class="ownmail-email-menu-divider">
                        {% endif %}
                        <a href="/raw/{{ email_id }}">Show original</a>
                        <a href="/download/{{ email_id }}">Download message</a>
                    </div>
                </div>
            </div>
            <div class="ownmail-email-header-row">
                <span class="ownmail-email-header-label">From:</span>
                <span class="ownmail-email-header-value">{% if sender_name and sender_email %}
                    {{ sender_name }}
                    &lt;<a href="/search?q=from:{{ sender_email | urlencode }}&sort=date_desc" class="ownmail-clickable-header" onclick="showLoading(event)">{{ sender_email }}</a>&gt;
                {% elif sender_email %}
                    <a href="/search?q=from:{{ sender_email | urlencode }}&sort=date_desc" class="ownmail-clickable-header" onclick="showLoading(event)">{{ sender_email }}</a>
                {% else %}
                    {{ sender }}
                {% endif %}</span>
            </div>
            <div class="ownmail-email-header-row">
                <span class="ownmail-email-header-label">To:</span>
                <span class="ownmail-email-header-value">{% for rcpt in recipients_parsed %}
                    {% if not loop.first %}, {% endif %}
                    {% if rcpt.name and rcpt.email %}
                        {{ rcpt.name }}
                        &lt;<a href="/search?q=to:{{ rcpt.email | urlencode }}&sort=date_desc" class="ownmail-clickable-header" onclick="showLoading(event)">{{ rcpt.email }}</a>&gt;
                    {% elif rcpt.email %}
                        <a href="/search?q=to:{{ rcpt.email | urlencode }}&sort=date_desc" class="ownmail-clickable-header" onclick="showLoading(event)">{{ rcpt.email }}</a>
                    {% else %}
                        {{ rcpt.raw }}
                    {% endif %}
                {% endfor %}</span>
            </div>
            <div class="ownmail-email-header-row">
                <span class="ownmail-email-header-label">Date:</span><span class="ownmail-email-header-value">{{ date }}</span>
            </div>
            {% if labels %}
            <div class="ownmail-labels">
                {% for label in labels %}
                <a href="/search?q=label:%22{{ label | urlencode }}%22&sort=date_desc" class="ownmail-label ownmail-clickable-label" onclick="showLoading(event)">{{ label }}</a>
                {% endfor %}
            </div>
            {% endif %}
        </div>

        <div class="ownmail-email-content-area" data-supports-dark="{{ 'true' if supports_dark else 'false' }}">
        {% if images_blocked and has_external_images %}
        <div class="ownmail-image-banner" id="ownmail-image-banner" data-has-banner="true">
            <span class="ownmail-image-banner-text" id="ownmail-image-banner-text">🖼️ External images are blocked for security.</span>
            <div class="ownmail-image-banner-buttons">
                <button id="load-images-btn" onclick="loadImages()">Load Images</button>
                {% if sender_email %}
                <button class="ownmail-trust-btn" onclick="trustSender()">Always trust this sender</button>
                {% endif %}
            </div>
        </div>
        {% endif %}
        {% if has_external_images %}
        <script>
        var senderEmail = {{ sender_email | tojson }};

        function hideBanner() {
            var banner = document.getElementById('ownmail-image-banner');
            if (banner) banner.style.display = 'none';
        }

        function loadImages() {
            var container = document.getElementById('ownmail-email-content');
            if (!container) return;

            // Restore <img data-src="...">
            var imgs = Array.from(container.querySelectorAll('img[data-src]'));
            imgs.forEach(function(img) {
                img.src = img.getAttribute('data-src');
                img.removeAttribute('data-src');
            });

            // Restore CSS background-image from data-bg-urls
            var bgEls = Array.from(container.querySelectorAll('[data-bg-urls]'));
            bgEls.forEach(function(el) {
                var urls = el.getAttribute('data-bg-urls').split(' ');
                var style = el.getAttribute('style') || '';
                // Replace placeholder data URIs back with original URLs
                urls.forEach(function(url) {
                    style = style.replace(
                        /url\(data:image\/gif;base64,[A-Za-z0-9+\/=]+\)/,
                        'url(' + url + ')'
                    );
                });
                el.setAttribute('style', style);
                el.removeAttribute('data-bg-urls');
            });

            hideBanner();
            updateDropdownImageState(true);
        }

        function blockImages() {
            var container = document.getElementById('ownmail-email-content');
            if (!container) return;

            // Block <img src="https://...">
            var imgs = Array.from(container.querySelectorAll('img[src]'));
            imgs.forEach(function(img) {
                var src = img.getAttribute('src');
                if (src && !src.startsWith('data:')) {
                    img.setAttribute('data-src', src);
                    img.src = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';
                }
            });

            updateDropdownImageState(false);
        }

        function trustSender() {
            fetch('/trust-sender', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: 'email=' + encodeURIComponent(senderEmail)
            }).then(function(response) {
                if (response.ok) {
                    loadImages();
                    updateDropdownTrustState(true);
                }
            });
        }

        function untrustSender() {
            fetch('/untrust-sender', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: 'email=' + encodeURIComponent(senderEmail)
            }).then(function(response) {
                if (response.ok) {
                    updateDropdownTrustState(false);
                }
            });
        }

        function updateDropdownImageState(loaded) {
            var loadItem = document.getElementById('menu-load-images');
            var blockItem = document.getElementById('menu-block-images');
            if (loadItem) loadItem.style.display = loaded ? 'none' : '';
            if (blockItem) blockItem.style.display = loaded ? '' : 'none';
        }

        function updateDropdownTrustState(trusted) {
            var trustItem = document.getElementById('menu-trust-sender');
            var untrustItem = document.getElementById('menu-untrust-sender');
            if (trustItem) trustItem.style.display = trusted ? 'none' : '';
            if (untrustItem) untrustItem.style.display = trusted ? '' : 'none';
        }
        </script>
        {% endif %}

        {% if body_html %}
            <div id="ownmail-email-content" class="ownmail-email-content-html{% if needs_padding %} ownmail-email-content-padded{% endif %}">{{ body_html | safe }}</div>
            {% if auto_scale %}
            <script>
            (function() {
                var container = document.querySelector('.ownmail-email-content-area');
                var content = document.getElementById('ownmail-email-content');
                if (!container || !content) return;

                function scaleToFit() {
                    // Reset any previous scaling
                    content.style.zoom = '';
                    content.style.overflow = 'auto';

                    // Force reflow so measurements are fresh
                    void content.offsetWidth;

                    var cw = content.clientWidth;
                    var sw = content.scrollWidth;

                    if (sw > cw + 1 && cw > 0) {
                        var scale = cw / sw;
                        content.style.overflow = 'hidden';
                        content.style.zoom = scale;
                    }
                }

                scaleToFit();
                window.addEventListener('load', scaleToFit);
                window.addEventListener('resize', scaleToFit);
            })();
            </script>
            {% endif %}
        {% else %}
            <div id="ownmail-email-content" class="ownmail-email-content-plain">
                <pre class="ownmail-email-body">{{ body | safe }}</pre>
            </div>
        {% endif %}
        </div>

        {% if attachments %}
        <div class="ownmail-attachments">
            <h4>Attachments</h4>
            <ul class="ownmail-attachment-list">
            {% for att in attachments %}
                <li class="ownmail-attachment-item">
                    <a href="/attachment/{{ email_id }}/{{ loop.index0 }}">📎 {{ att.filename }}</a>
                    ({{ att.size }})
                </li>
            {% endfor %}
            </ul>
        </div>
        {% endif %}
    </div>

<script>
function toggleEmailMenu(event) {
    event.stopPropagation();
    const dropdown = document.getElementById('ownmail-email-menu-dropdown');
    dropdown.classList.toggle('ownmail-show');
}

// Called by base.html theme system whenever site theme changes
function updateEmailDarkMode(siteIsDark) {
    var area = document.querySelector('.ownmail-email-content-area');
    if (!area) return;
    var supportsDark = area.getAttribute('data-supports-dark') === 'true';
    area.classList.toggle('ownmail-email-dark', siteIsDark && supportsDark);

    // Override @media (prefers-color-scheme: dark) blocks in email CSS
    // so they follow the ownmail theme, not the OS preference.
    if (!supportsDark) return;
    var content = document.getElementById('ownmail-email-content');
    if (!content) return;
    var styles = content.querySelectorAll('style');
    for (var i = 0; i < styles.length; i++) {
        var el = styles[i];
        // Save original CSS on first call
        if (!el.hasAttribute('data-original-css')) {
            el.setAttribute('data-original-css', el.textContent);
        }
        var original = el.getAttribute('data-original-css');
        if (original.indexOf('prefers-color-scheme') === -1) continue;
        if (siteIsDark) {
            // Dark mode: unwrap @media dark blocks so rules always apply
            el.textContent = original.replace(
                /@media[^{]*prefers-color-scheme\s*:\s*dark[^{]*\{((?:[^{}]*\{[^{}]*\})*[^{}]*)\}/gi,
                '$1'
            );
        } else {
            // Light mode: remove @media dark blocks entirely
            el.textContent = original.replace(
                /@media[^{]*prefers-color-scheme\s*:\s*dark[^{]*\{(?:[^{}]*\{[^{}]*\})*[^{}]*\}/gi,
                ''
            );
        }
    }
}
// Apply on load
(function() {
    var pref = localStorage.getItem('ownmail-theme') || 'auto';
    var dark = pref === 'dark' || (pref === 'auto' && window.matchMedia('(prefers-color-scheme: dark)').matches);
    updateEmailDarkMode(dark);
})();

// Close dropdown when clicking outside
document.addEventListener('click', function(event) {
    const dropdown = document.getElementById('ownmail-email-menu-dropdown');
    if (dropdown && dropdown.classList.contains('ownmail-show')) {
        dropdown.classList.remove('ownmail-show');
    }
});
</script>
{% endblock %}
