{% extends 'admin/base.html' %}
{% block title %}{{ t('settings.title') }}{% endblock %}
{% block content %}

<form method="POST">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">

<div class="page-header--with-action">
    <div class="page-header__content">
        <h2>⚙️ {{ t('settings.title') }}</h2>
    </div>
    <button type="submit" class="btn btn-primary">💾 {{ t('settings.save_settings') }}</button>
</div>


        
        <!-- License & Updates -->
        <div class="settings-section">
            <h3>🔑 {{ t('settings.license_updates') }}</h3>
            
            <div class="stat-grid">
                <div class="stat-item text-start">
                    <div class="mini-label">{{ t('settings.license_version') }}</div>
                    <div class="text-lg text-bold">{{ cms_version }}</div>
                </div>
                <div class="stat-item text-start">
                    <div class="mini-label">{{ t('settings.license_status') }}</div>
                    {% if license_info.is_valid %}
                        <div class="text-md text-bold text-success">✅ {{ t('settings.license_active') }}{% if license_info.platform %} <span class="text-sm text-muted text-normal">({{ license_info.platform|title }})</span>{% endif %}</div>
                    {% elif license_info.has_key %}
                        <div class="text-md text-bold text-warning">⚠️ {{ t('settings.license_invalid') }}</div>
                    {% else %}
                        <div class="text-md text-bold text-muted">{{ t('settings.license_free') }}</div>
                    {% endif %}
                </div>
            </div>
            
            <div class="form-group">
                <label for="license_key">{{ t('settings.license_key') }}</label>
                <div class="input-password-wrap">
                    <input type="password" id="license_key" name="license_key" 
                           placeholder="{% if license_info.has_key %}●●●●●●●● ({{ t('settings.license_saved') }}){% else %}{{ t('settings.license_key_placeholder') }}{% endif %}" 
                           value="" autocomplete="off">
                    <button type="button" onclick="togglePasswordVisibility('license_key', this)" 
                            class="btn-password-toggle" title="{{ t('common.show_hide') }}">👁</button>
                </div>
                <div class="help-text">{{ t('settings.license_key_help') }}</div>
            </div>
            
            {% if license_info.has_key %}
            <div class="mb-4">
                <button type="button" onclick="deactivateLicense()" class="btn text-sm text-muted">{{ t('settings.license_deactivate') }}</button>
            </div>
            {% endif %}

            <!-- Software Updates -->
            <div class="info-card">
                <div class="action-row">
                    <div>
                        <div class="text-md text-bold">{{ t('settings.license_updates_check') }}</div>
                        <div id="updateStatus" class="text-sm text-muted mt-1">
                            {% if license_info.is_valid %}
                                {{ t('settings.license_click_check') }}
                            {% else %}
                                {{ t('settings.license_free_note_short') }}
                            {% endif %}
                        </div>
                    </div>
                    {% if license_info.is_valid %}
                    <button type="button" id="checkUpdateBtn" onclick="checkForUpdates()" class="btn btn-primary text-sm whitespace-nowrap">{{ t('settings.check_for_updates') }}</button>
                    {% endif %}
                </div>
                <div id="updateResult" class="result-box"></div>
            </div>
            
            {% if not license_info.is_valid %}
            <div class="help-text mt-3">
                {{ t('settings.license_free_note') }}
            </div>
            {% endif %}
        </div>

        <!-- General Settings -->
        <div class="settings-section">
            <h3>🌐 {{ t('settings.general') }}</h3>
            
            <div class="form-group">
                <label for="site_name">{{ t('settings.site_name') }}</label>
                <input type="text" id="site_name" name="site_name" value="{{ settings.get('site_name', 'AliothPress') }}">
            </div>
            
            <div class="form-group">
                <label for="site_tagline">{{ t('settings.tagline') }}</label>
                <input type="text" id="site_tagline" name="site_tagline" value="{{ settings.get('site_tagline', 'AI-Powered Multilingual CMS') }}">
                <div class="help-text">{{ t('settings.site_description_help') }}</div>
            </div>
            
            <div class="form-group">
                <label for="site_description">{{ t('settings.site_description') }}</label>
                <textarea id="site_description" name="site_description">{{ settings.get('site_description', '') }}</textarea>
                <div class="help-text">{{ t('settings.meta_description_home') }}</div>
            </div>
            
            <div class="form-group">
                <label for="site_logo">{{ t('settings.logo') }}</label>
                <div class="flex gap-2 items-center">
                    <input type="text" id="site_logo" name="site_logo" value="{{ settings.get('site_logo', '') }}" placeholder="{{ t('settings.logo_placeholder') }}" class="flex-1 cursor-default opacity-muted" readonly>
                    <button type="button" class="btn-pick-image" onclick="pickSettingsImage('site_logo')">📷 {{ t('common.choose') }}</button>
                </div>
                <input type="hidden" id="site_logo_width" name="site_logo_width" value="{{ settings.get('site_logo_width', '') }}">
                <input type="hidden" id="site_logo_height" name="site_logo_height" value="{{ settings.get('site_logo_height', '') }}">
                <div id="site_logo_preview_wrap" class="logo-preview-wrap">
                    <img id="site_logo_preview" alt="Preview">
                    <button type="button" onclick="clearSettingsImage('site_logo')" title="{{ t('settings.remove_logo') }}" class="btn-remove-preview">✕</button>
                </div>
                <span id="site_logo_dimensions" class="text-sm text-muted mt-1 d-none"></span>
                <div class="help-text">{{ t('settings.logo_help') }}</div>
            </div>

            <div class="form-group">
                <label for="homepage_group">{{ t('settings.homepage') }}</label>
                <input type="text" id="homepage_filter" placeholder="{{ t('settings.homepage_filter_placeholder') }}" 
                       class="mb-2" autocomplete="off"
                       oninput="filterHomepageOptions()">
                <select id="homepage_group" name="homepage_group" size="1">
                    <option value="">{{ t('settings.homepage_default_option') }}</option>
                    {% if homepage_pages is defined %}
                    {% for page in homepage_pages %}
                    <option value="{{ page.translation_group }}" {% if settings.get('homepage_group', '') == page.translation_group %}selected{% endif %}>
                        {{ page.title }} ({{ page.language|upper }})
                    </option>
                    {% endfor %}
                    {% endif %}
                </select>
                <div class="help-text">{{ t('settings.homepage_help') }}</div>
            </div>
        </div>
        
        <!-- Language Settings -->
        <div class="settings-section">
            <h3>🌍 {{ t('settings.languages') }}</h3>
            
            <div class="form-group">
                <label for="default_language">{{ t('settings.default_language') }}</label>
                <select id="default_language" name="default_language">
                    {% for lang in available_languages %}
                    <option value="{{ lang.code }}" {% if settings.get('default_language', 'en') == lang.code %}selected{% endif %}>{{ lang.name }}</option>
                    {% endfor %}
                </select>
                <div class="help-text">{{ t('settings.default_language_help') }}</div>
            </div>
            
            <div class="form-group">
                <label>{{ t('settings.active_languages') }}</label>
                <div class="help-text mb-3">{{ t('settings.active_languages_help') }}</div>
                <div class="language-grid">
                    {% for lang in available_languages %}
                    <label class="language-item {% if lang.code in active_langs %}active{% endif %}">
                        <input type="checkbox" name="active_languages" value="{{ lang.code }}" 
                               {% if lang.code in active_langs %}checked{% endif %}>
                        {{ lang.name }}
                    </label>
                    {% endfor %}
                </div>
            </div>
            
            <div class="form-group">
                <label class="checkbox-label">
                    <input type="checkbox" name="show_language_switcher" value="true" 
                           {% if settings.get('show_language_switcher', 'true') == 'true' %}checked{% endif %}>
                    {{ t('settings.language_switcher') }}
                </label>
            </div>
        </div>
        
        <!-- Analytics -->
        <div class="settings-section">
            <h3>📊 {{ t('settings.analytics') }}</h3>
            
            <div class="form-group">
                <label for="google_analytics_id">{{ t('settings.google_analytics') }}</label>
                <input type="text" id="google_analytics_id" name="google_analytics_id" 
                       value="{{ settings.get('google_analytics_id', '') }}" 
                       placeholder="{{ t('settings.google_analytics_placeholder') }}">
            </div>
            
            <div class="form-group">
                <label for="google_tag_manager_id">{{ t('settings.tag_manager') }}</label>
                <input type="text" id="google_tag_manager_id" name="google_tag_manager_id" 
                       value="{{ settings.get('google_tag_manager_id', '') }}" 
                       placeholder="{{ t('settings.tag_manager_placeholder') }}">
            </div>
            
            <div class="form-group">
                <label for="custom_analytics_code">{{ t('settings.custom_code') }}</label>
                <textarea id="custom_analytics_code" name="custom_analytics_code" placeholder="{{ t('settings.custom_code_placeholder') }}">{{ settings.get('custom_analytics_code', '') }}</textarea>
                <div class="help-text">{{ t('settings.custom_code_help') }}</div>
            </div>
        </div>
        
        <!-- Email Settings (SMTP) -->
        <div class="settings-section">
            <h3>✉️ {{ t('settings.email') }}</h3>
            
            <!-- Setup Guide (collapsible) -->
            <div class="mb-6">
                <div class="guide-header" onclick="var body=this.nextElementSibling; body.classList.toggle('active'); this.querySelector('.guide-arrow').textContent = body.classList.contains('active') ? '▼' : '▶';">
                    <span class="guide-arrow">▶</span> {{ t('settings.email_guide_title') }}
                </div>
                <div class="guide-body">
                    <p>{{ t('settings.email_intro') }}</p>
                    
                    <p class="text-bold mb-1">{{ t('settings.email_step1') }}</p>
                    <p>{{ t('settings.email_step1_text') }}</p>
                    
                    <p class="text-bold mb-1">{{ t('settings.email_step2') }}</p>
                    <p>{{ t('settings.email_step2_text') }}</p>
                    <table class="guide-table">
                        <tr><th>{{ t('settings.guide_col_field') }}</th><th>{{ t('settings.guide_col_value') }}</th></tr>
                        <tr><td>{{ t('settings.smtp_host') }}</td><td>{{ t('settings.smtp_host_placeholder') }}</td></tr>
                        <tr><td>{{ t('settings.smtp_port') }}</td><td>{{ t('settings.guide_port_value') }}</td></tr>
                        <tr><td>{{ t('settings.smtp_username') }}</td><td>{{ t('settings.smtp_username_placeholder') }}</td></tr>
                        <tr><td>{{ t('settings.smtp_password') }}</td><td>{{ t('settings.smtp_password_help') }}</td></tr>
                    </table>
                    
                    <p class="text-bold mb-1">{{ t('settings.email_step3') }}</p>
                    <p>{{ t('settings.email_step3_text')|replace('{save_label}', t('settings.save_settings'))|safe }}</p>
                </div>
            </div>
            
            <div class="form-group">
                <label for="smtp_host">{{ t('settings.smtp_host') }}</label>
                <input type="text" id="smtp_host" name="smtp_host" 
                       value="{{ settings.get('smtp_host', '') }}" 
                       placeholder="{{ t('settings.smtp_host_placeholder') }}">
            </div>
            
            <div class="form-group">
                <label for="smtp_port">{{ t('settings.smtp_port') }}</label>
                <input type="number" id="smtp_port" name="smtp_port" 
                       value="{{ settings.get('smtp_port', '587') }}" 
                       placeholder="587" class="input-narrow">
                <div class="help-text">{{ t('settings.smtp_port_help') }}</div>
            </div>
            
            <div class="form-group">
                <label for="smtp_username">{{ t('settings.smtp_username') }}</label>
                <input type="text" id="smtp_username" name="smtp_username" 
                       value="{{ settings.get('smtp_username', '') }}" 
                       placeholder="{{ t('settings.smtp_username_placeholder') }}" autocomplete="off">
                <div class="help-text">{{ t('settings.from_email_help') }}</div>
            </div>
            
            <div class="form-group">
                <label for="smtp_password">{{ t('settings.smtp_password') }}</label>
                <div class="input-password-wrap">
                    <input type="password" id="smtp_password" name="smtp_password" 
                           value="" 
                           placeholder="{% if smtp_has_password %}{{ t('settings.smtp_password_saved_placeholder') }}{% else %}{{ t('settings.smtp_password_enter_placeholder') }}{% endif %}" autocomplete="new-password">
                    <button type="button" onclick="togglePasswordVisibility('smtp_password', this)" 
                            class="btn-password-toggle" title="{{ t('common.show_hide_password') }}">👁</button>
                </div>
            </div>
            
            <div class="form-group">
                <label for="smtp_password_confirm">{{ t('settings.smtp_confirm_password') }}</label>
                <div class="input-password-wrap">
                    <input type="password" id="smtp_password_confirm" 
                           value="" 
                           placeholder="{% if smtp_has_password %}{{ t('settings.smtp_password_keep_placeholder') }}{% else %}{{ t('settings.smtp_password_repeat_placeholder') }}{% endif %}" autocomplete="new-password">
                    <button type="button" onclick="togglePasswordVisibility('smtp_password_confirm', this)" 
                            class="btn-password-toggle" title="{{ t('common.show_hide_password') }}">👁</button>
                </div>
                <div id="password_match_hint" class="text-sm mt-1 d-none"></div>
                <div class="help-text">{{ t('settings.smtp_password_stored') }}</div>
            </div>
            
            <div class="form-group">
                <label class="text-bold mb-2 d-block">{{ t('settings.connection_security') }}</label>
                <div class="radio-group">
                    <label class="radio-label">
                        <input type="radio" name="smtp_security" value="tls" 
                               {% if settings.get('smtp_use_ssl', 'false') != 'true' %}checked{% endif %}>
                        {{ t('settings.security_tls_label') }}
                    </label>
                    <label class="radio-label">
                        <input type="radio" name="smtp_security" value="ssl" 
                               {% if settings.get('smtp_use_ssl', 'false') == 'true' %}checked{% endif %}>
                        {{ t('settings.security_ssl_label') }}
                    </label>
                </div>
                <div class="help-text">{{ t('settings.connection_security_help') }}</div>
            </div>
            
            <div class="form-group">
                <label for="smtp_from_email">{{ t('settings.from_email') }}</label>
                <input type="email" id="smtp_from_email" name="smtp_from_email" 
                       value="{{ settings.get('smtp_from_email', '') }}" 
                       placeholder="{{ t('settings.smtp_from_placeholder') }}">
                <div class="help-text">{{ t('settings.smtp_username_help') }}</div>
            </div>
            
            <div class="form-group">
                <label for="smtp_from_name">{{ t('settings.from_name') }}</label>
                <input type="text" id="smtp_from_name" name="smtp_from_name" 
                       value="{{ settings.get('smtp_from_name', '') }}" 
                       placeholder="{{ settings.get('site_name', 'AliothPress') }}">
                <div class="help-text">{{ t('settings.from_name_help') }}</div>
            </div>
            
            <div class="info-card">
                <div class="text-md text-bold mb-2">📨 {{ t('settings.test_email') }}</div>
                <div class="flex gap-2 items-center">
                    <input type="email" id="test_email" value="{{ current_user.email }}" 
                           placeholder="{{ t('settings.test_email_placeholder') }}" 
                           class="flex-1">
                    <button type="button" onclick="sendTestEmail()" class="btn-invite">
                        {{ t('settings.send_test') }}
                    </button>
                </div>
                <div class="help-text mt-2">{{ t('settings.test_email_help') }}</div>
            </div>
        </div>

        <!-- Domain & HTTPS -->
        <div class="settings-section">
            <h3>🔒 {{ t('ssl.title') }}</h3>
            
            {% if ssl_enabled and ssl_domain %}
            <div class="status-banner status-banner-success">
                <span class="emoji-lg">✅</span>
                <div>
                    <div class="text-bold text-success">{{ t('ssl.status_active') }}</div>
                    <div class="text-sm text-secondary mt-1">
                        https://{{ ssl_domain }}
                        · {{ t('ssl.auto_renew') }}
                    </div>
                </div>
            </div>
            {% endif %}

            <div class="form-group">
                <label for="ssl_domain">{{ t('ssl.domain_label') }}</label>
                <input type="text" id="ssl_domain" 
                       value="{{ ssl_domain }}" 
                       placeholder="{{ t('settings.ssl_domain_placeholder') }}">
                <div class="help-text">{{ t('ssl.domain_help') }}</div>
            </div>
            
            <div class="info-card">
                <div class="action-row">
                    <div>
                        <div class="text-md text-bold">{{ t('ssl.enable_title') }}</div>
                        <div id="sslStatus" class="text-sm text-muted mt-1">
                            {% if ssl_enabled %}
                                {{ t('ssl.click_to_renew') }}
                            {% else %}
                                {{ t('ssl.click_to_enable') }}
                            {% endif %}
                        </div>
                    </div>
                    <button type="button" id="sslBtn" onclick="setupSSL()" class="btn btn-primary text-sm whitespace-nowrap">
                        {% if ssl_enabled %}🔄 {{ t('ssl.btn_renew') }}{% else %}🔒 {{ t('ssl.btn_enable') }}{% endif %}
                    </button>
                </div>
                <div id="sslResult" class="result-box"></div>
            </div>
            
            <div class="help-text mt-3">{{ t('ssl.instructions') }}</div>
        </div>

        <!-- Footer Content -->
        <div class="settings-section">
            <h3>🔻 {{ t('settings.footer') }}</h3>
            
            <div class="form-group">
                <label for="footer_copyright">{{ t('settings.copyright') }}</label>
                <input type="text" id="footer_copyright" name="footer_copyright" 
                       value="{{ settings.get('footer_copyright', '') }}"
                       placeholder="{{ t('settings.copyright_placeholder') }}">
                <div class="help-text">{{ t('settings.copyright_help') }}</div>
            </div>
            
            <div class="form-group">
                <label for="footer_license">{{ t('settings.license') }}</label>
                <input type="text" id="footer_license" name="footer_license" 
                       value="{{ settings.get('footer_license', '') }}" 
                       placeholder="{{ t('settings.license_placeholder') }}">
            </div>

            <div class="form-group">
                <label>{{ t('settings.social_links') }}</label>
                <div class="help-text mb-3">{{ t('settings.social_links_help') }}</div>
                
                <div class="social-links-list">
                    <div class="social-link-row">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="#1877F2"><path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z"/></svg>
                        <input type="text" name="social_facebook" value="{{ settings.get('social_facebook', '') }}" placeholder="{{ t('settings.social_facebook_placeholder') }}">
                    </div>
                    <div class="social-link-row">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor" class="text-muted flex-shrink-0"><path 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.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"/></svg>
                        <input type="text" name="social_twitter" value="{{ settings.get('social_twitter', '') }}" placeholder="{{ t('settings.social_twitter_placeholder') }}">
                    </div>
                    <div class="social-link-row">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="#0A66C2"><path d="M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433a2.062 2.062 0 01-2.063-2.065 2.064 2.064 0 112.063 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z"/></svg>
                        <input type="text" name="social_linkedin" value="{{ settings.get('social_linkedin', '') }}" placeholder="{{ t('settings.social_linkedin_placeholder') }}">
                    </div>
                    <div class="social-link-row">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor" class="text-muted flex-shrink-0"><path d="M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12"/></svg>
                        <input type="text" name="social_github" value="{{ settings.get('social_github', '') }}" placeholder="{{ t('settings.social_github_placeholder') }}">
                    </div>
                    <div class="social-link-row">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="#FF0000"><path d="M23.498 6.186a3.016 3.016 0 00-2.122-2.136C19.505 3.545 12 3.545 12 3.545s-7.505 0-9.377.505A3.017 3.017 0 00.502 6.186C0 8.07 0 12 0 12s0 3.93.502 5.814a3.016 3.016 0 002.122 2.136c1.871.505 9.376.505 9.376.505s7.505 0 9.377-.505a3.015 3.015 0 002.122-2.136C24 15.93 24 12 24 12s0-3.93-.502-5.814zM9.545 15.568V8.432L15.818 12l-6.273 3.568z"/></svg>
                        <input type="text" name="social_youtube" value="{{ settings.get('social_youtube', '') }}" placeholder="{{ t('settings.social_youtube_placeholder') }}">
                    </div>
                    <div class="social-link-row">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="#E4405F"><path d="M12 0C8.74 0 8.333.015 7.053.072 5.775.132 4.905.333 4.14.63c-.789.306-1.459.717-2.126 1.384S.935 3.35.63 4.14C.333 4.905.131 5.775.072 7.053.012 8.333 0 8.74 0 12s.015 3.667.072 4.947c.06 1.277.261 2.148.558 2.913.306.788.717 1.459 1.384 2.126.667.666 1.336 1.079 2.126 1.384.766.296 1.636.499 2.913.558C8.333 23.988 8.74 24 12 24s3.667-.015 4.947-.072c1.277-.06 2.148-.262 2.913-.558.788-.306 1.459-.718 2.126-1.384.666-.667 1.079-1.335 1.384-2.126.296-.765.499-1.636.558-2.913.06-1.28.072-1.687.072-4.947s-.015-3.667-.072-4.947c-.06-1.277-.262-2.149-.558-2.913-.306-.789-.718-1.459-1.384-2.126C21.319 1.347 20.651.935 19.86.63c-.765-.297-1.636-.499-2.913-.558C15.667.012 15.26 0 12 0zm0 2.16c3.203 0 3.585.016 4.85.071 1.17.055 1.805.249 2.227.415.562.217.96.477 1.382.896.419.42.679.819.896 1.381.164.422.36 1.057.413 2.227.057 1.266.07 1.646.07 4.85s-.015 3.585-.074 4.85c-.061 1.17-.256 1.805-.421 2.227-.224.562-.479.96-.899 1.382-.419.419-.824.679-1.38.896-.42.164-1.065.36-2.235.413-1.274.057-1.649.07-4.859.07-3.211 0-3.586-.015-4.859-.074-1.171-.061-1.816-.256-2.236-.421-.569-.224-.96-.479-1.379-.899-.421-.419-.69-.824-.9-1.38-.165-.42-.359-1.065-.42-2.235-.045-1.26-.061-1.649-.061-4.844 0-3.196.016-3.586.061-4.861.061-1.17.255-1.814.42-2.234.21-.57.479-.96.9-1.381.419-.419.81-.689 1.379-.898.42-.166 1.051-.361 2.221-.421 1.275-.045 1.65-.06 4.859-.06l.045.03zm0 3.678a6.162 6.162 0 100 12.324 6.162 6.162 0 100-12.324zM12 16c-2.21 0-4-1.79-4-4s1.79-4 4-4 4 1.79 4 4-1.79 4-4 4zm7.846-10.405a1.441 1.441 0 11-2.882 0 1.441 1.441 0 012.882 0z"/></svg>
                        <input type="text" name="social_instagram" value="{{ settings.get('social_instagram', '') }}" placeholder="{{ t('settings.social_instagram_placeholder') }}">
                    </div>
                </div>
            </div>
            
            <div class="form-group">
                <label for="footer_additional">{{ t('settings.additional_footer') }}</label>
                <textarea id="footer_additional" name="footer_additional" rows="5">{{ settings.get('footer_additional', '') }}</textarea>
                <div class="help-text">{{ t('settings.additional_footer_help') }}</div>
            </div>
        </div>

        <!-- AI Visibility (AEO) -->
        <div class="settings-section">
            <h3>🤖 {{ t('settings.aeo_section') }}</h3>
            <div class="help-text section-subtitle">{{ t('settings.aeo_help') }}</div>
            
            <div class="form-group">
                <label for="org_legal_name">{{ t('settings.org_legal_name') }}</label>
                <input type="text" id="org_legal_name" name="org_legal_name" 
                       value="{{ settings.get('org_legal_name', '') }}" 
                       placeholder="{{ t('settings.org_legal_name_placeholder') }}">
            </div>
            
            <div class="form-group">
                <label for="org_founding_year">{{ t('settings.org_founding_year') }}</label>
                <input type="text" id="org_founding_year" name="org_founding_year" 
                       value="{{ settings.get('org_founding_year', '') }}" 
                       placeholder="{{ t('settings.org_founding_year_placeholder') }}">
            </div>
            
            <div class="form-group">
                <label for="org_sameas_wikipedia">{{ t('settings.org_sameas_wikipedia') }}</label>
                <input type="url" id="org_sameas_wikipedia" name="org_sameas_wikipedia" 
                       value="{{ settings.get('org_sameas_wikipedia', '') }}" 
                       placeholder="https://en.wikipedia.org/wiki/Your_Company">
            </div>
            
            <div class="form-group">
                <label for="org_sameas_wikidata">{{ t('settings.org_sameas_wikidata') }}</label>
                <input type="url" id="org_sameas_wikidata" name="org_sameas_wikidata" 
                       value="{{ settings.get('org_sameas_wikidata', '') }}" 
                       placeholder="https://www.wikidata.org/wiki/Q12345">
            </div>
            
            <div class="form-group">
                <label for="org_sameas_crunchbase">{{ t('settings.org_sameas_crunchbase') }}</label>
                <input type="url" id="org_sameas_crunchbase" name="org_sameas_crunchbase" 
                       value="{{ settings.get('org_sameas_crunchbase', '') }}" 
                       placeholder="https://www.crunchbase.com/organization/your-company">
            </div>
        </div>


</form>

<script>
/* ── Translation strings (collected here to keep JS lint-clean) ── */
var _t = {
    passwords_match:       '{{ t("settings.passwords_match") }}',
    passwords_no_match:    '{{ t("settings.passwords_no_match") }}',
    update_confirm:        '{{ t("common.update_confirm") }}',
    license_deactivate:    '{{ t("settings.license_deactivate_confirm") }}',
    ssl_error_empty:       '{{ t("ssl.error_empty_domain") }}',
    ssl_error_invalid:     '{{ t("ssl.error_invalid_domain") }}',
    ssl_confirm:           '{{ t("ssl.confirm") }}',
    ssl_setting_up:        '{{ t("ssl.setting_up") }}',
    ssl_setting_up_detail: '{{ t("ssl.setting_up_detail") }}'.replace(/&#39;/g, "'"),
    ssl_status_active:     '{{ t("ssl.status_active_short") }}',
    ssl_reload_hint:       '{{ t("ssl.reload_hint") }}',
    ssl_setup_failed:      '{{ t("ssl.setup_failed") }}',
    connection_error:      '{{ t("settings.connection_error") }}'
};
function filterHomepageOptions() {
    var filter = document.getElementById('homepage_filter').value.toLowerCase();
    var select = document.getElementById('homepage_group');
    var options = select.options;
    for (var i = 0; i < options.length; i++) {
        var text = options[i].text.toLowerCase();
        if (i === 0 || !filter || text.indexOf(filter) !== -1) { options[i].style.display = ''; }
        else { options[i].style.display = 'none'; }
    }
}

function openImagePicker(callback) {
    var modal = document.createElement('div');
    modal.style.cssText = 'position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,0.7);z-index:10000;display:flex;align-items:center;justify-content:center;';
    var mc = document.createElement('div');
    mc.style.cssText = 'background:var(--adm-surface);border-radius:12px;padding:24px;max-width:900px;max-height:80vh;overflow-y:auto;width:90%;';
    mc.innerHTML = '<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:20px;"><h2 style="margin:0;">{{ t("media.select_image") }}</h2><button onclick="this.closest(\'[style*=fixed]\').remove()" style="background:none;border:none;font-size:24px;cursor:pointer;">&times;</button></div><div id="imageGallery" style="display:grid;grid-template-columns:repeat(auto-fill,minmax(150px,1fr));gap:16px;"><div style="grid-column:1/-1;text-align:center;padding:40px;color:var(--adm-text-muted);">{{ t("common.loading") }}</div></div>';
    modal.appendChild(mc);
    document.body.appendChild(modal);
    fetch('/admin/media/api/list').then(function(r){return r.json();}).then(function(imgs){
        var g = document.getElementById('imageGallery');
        if (!imgs.length) {
            g.innerHTML = '<div style="grid-column:1/-1;text-align:center;padding:40px;"><p>{{ t("media.no_images_picker") }}</p><a href="/admin/media/upload" target="_blank" style="color:var(--adm-primary);">{{ t("media.upload_first_link") }}</a></div>';
            return;
        }
        g.innerHTML = imgs.map(function(i){
            return '<div onclick="window._pickImage(\'' + i.url + '\')" style="cursor:pointer;border:2px solid var(--adm-border-light);border-radius:8px;overflow:hidden;"><img src="' + i.url + '" alt="' + i.alt_text + '" style="width:100%;height:150px;object-fit:cover;"><div style="padding:8px;font-size:12px;color:var(--adm-text-muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">' + i.alt_text + '</div></div>';
        }).join('');
    });
    window._pickImage = function(url) { callback(url); modal.remove(); };
}

function pickSettingsImage(inputId) {
    openImagePicker(function(url) {
        document.getElementById(inputId).value = url;
        var preview = document.getElementById(inputId + '_preview');
        var wrap = document.getElementById(inputId + '_preview_wrap');
        if (preview) { preview.src = url; }
        if (wrap) { wrap.style.display = 'block'; }
        // Auto-detect logo dimensions for SEO (CLS prevention & Schema.org)
        if (inputId === 'site_logo') { detectLogoDimensions(url); }
    });
}

function detectLogoDimensions(url) {
    if (!url) return;
    var img = new Image();
    img.onload = function() {
        document.getElementById('site_logo_width').value = img.naturalWidth;
        document.getElementById('site_logo_height').value = img.naturalHeight;
        var dims = document.getElementById('site_logo_dimensions');
        if (dims) {
            dims.textContent = img.naturalWidth + ' × ' + img.naturalHeight + ' px';
            dims.style.display = 'block';
        }
    };
    img.src = url;
}

function clearSettingsImage(inputId) {
    document.getElementById(inputId).value = '';
    var wrap = document.getElementById(inputId + '_preview_wrap');
    if (wrap) wrap.style.display = 'none';
    var dims = document.getElementById(inputId + '_dimensions');
    if (dims) dims.style.display = 'none';
    if (inputId === 'site_logo') {
        document.getElementById('site_logo_width').value = '';
        document.getElementById('site_logo_height').value = '';
    }
}

document.addEventListener('DOMContentLoaded', function() {
    ['site_logo'].forEach(function(id) {
        var input = document.getElementById(id);
        var preview = document.getElementById(id + '_preview');
        var wrap = document.getElementById(id + '_preview_wrap');
        if (input && preview && input.value) { 
            preview.src = input.value;
            if (wrap) wrap.style.display = 'block';
            if (id === 'site_logo') { detectLogoDimensions(input.value); }
        }
    });
    var pw = document.getElementById('smtp_password');
    var pwConfirm = document.getElementById('smtp_password_confirm');
    var hint = document.getElementById('password_match_hint');
    function checkPasswordMatch() {
        if (!pw.value && !pwConfirm.value) { hint.classList.add('d-none'); hint.classList.remove('d-block', 'text-success', 'text-error'); return; }
        hint.classList.remove('d-none');
        hint.classList.add('d-block');
        if (pw.value === pwConfirm.value) { hint.textContent = _t.passwords_match; hint.classList.remove('text-error'); hint.classList.add('text-success'); }
        else { hint.textContent = _t.passwords_no_match; hint.classList.remove('text-success'); hint.classList.add('text-error'); }
    }
    pw.addEventListener('input', checkPasswordMatch);
    pwConfirm.addEventListener('input', checkPasswordMatch);
});

function togglePasswordVisibility(inputId, btn) {
    var input = document.getElementById(inputId);
    if (input.type === 'password') { input.type = 'text'; btn.classList.remove('opacity-muted'); }
    else { input.type = 'password'; btn.classList.add('opacity-muted'); }
}

function sendTestEmail() {
    var email = document.getElementById('test_email').value;
    if (!email) { alert('{{ t("settings.smtp_port_help") }}'); return; }
    var btn = document.querySelector('[onclick="sendTestEmail()"]');
    var origText = btn.textContent;
    btn.disabled = true;
    btn.textContent = '{{ t("settings.sending") }}';
    
    fetch('{{ url_for("admin_email_test") }}', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'X-CSRFToken': document.querySelector('input[name=csrf_token]').value,
            'X-Requested-With': 'XMLHttpRequest'
        },
        body: 'test_email=' + encodeURIComponent(email) + '&csrf_token=' + encodeURIComponent(document.querySelector('input[name=csrf_token]').value)
    }).then(function(r) {
        if (!r.ok) throw new Error(r.status);
        return r.json();
    }).then(function(data) {
        btn.disabled = false;
        btn.textContent = origText;
        var msg = document.getElementById('testEmailMsg');
        if (!msg) {
            msg = document.createElement('div');
            msg.id = 'testEmailMsg';
            msg.style.cssText = 'margin-top:8px;padding:8px 12px;border-radius:6px;font-size:13px;border:1px solid';
            btn.parentNode.parentNode.appendChild(msg);
        }
        if (data.success) {
            msg.style.background = 'var(--adm-success-bg)';
            msg.style.color = 'var(--adm-success-text)';
            msg.style.borderColor = 'var(--adm-success-border)';
            msg.textContent = '\u2705 ' + data.message;
        } else {
            msg.style.background = 'var(--adm-error-bg)';
            msg.style.color = 'var(--adm-error-text)';
            msg.style.borderColor = 'var(--adm-error-border)';
            msg.textContent = '\u274C ' + (data.message || '{{ t("dashboard.connection_error") }}');
        }
        setTimeout(function() { msg.remove(); }, 8000);
    }).catch(function(err) {
        btn.disabled = false;
        btn.textContent = origText;
        var msg = document.getElementById('testEmailMsg');
        if (!msg) {
            msg = document.createElement('div');
            msg.id = 'testEmailMsg';
            msg.style.cssText = 'margin-top:8px;padding:8px 12px;border-radius:6px;font-size:13px;border:1px solid';
            btn.parentNode.parentNode.appendChild(msg);
        }
        msg.style.background = 'var(--adm-error-bg)';
        msg.style.color = 'var(--adm-error-text)';
        msg.style.borderColor = 'var(--adm-error-border)';
        msg.textContent = '\u274C {{ t("dashboard.connection_error") }}';
        setTimeout(function() { msg.remove(); }, 8000);
    });
}

document.querySelector('form').addEventListener('submit', function(e) {
    var pw = document.getElementById('smtp_password').value;
    var pwConfirm = document.getElementById('smtp_password_confirm').value;
    if (pw || pwConfirm) {
        if (pw !== pwConfirm) {
            e.preventDefault();
            alert('{{ t("settings.smtp_passwords_mismatch") }}');
            document.getElementById('smtp_password_confirm').focus();
            return false;
        }
    }
});

function checkForUpdates() {
    var btn = document.getElementById('checkUpdateBtn');
    var status = document.getElementById('updateStatus');
    var result = document.getElementById('updateResult');
    var origText = btn.textContent;
    btn.disabled = true;
    btn.textContent = '{{ t("settings.checking_updates") }}';
    status.textContent = '{{ t("settings.checking_updates") }}';
    
    fetch('{{ url_for("admin_update_check") }}', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': document.querySelector('input[name=csrf_token]').value
        }
    }).then(function(r) { return r.json(); }).then(function(data) {
        btn.disabled = false;
        btn.textContent = origText;
        
        if (data.error) {
            status.textContent = data.error;
            result.classList.remove('visible', 'success', 'error');
            return;
        }
        
        if (data.update_available) {
            status.innerHTML = '🎉 <strong>' + data.latest_version + '</strong> {{ t("settings.update_available_short") }}';
            result.classList.remove('error');
            result.classList.add('visible', 'success');
            var changelog = data.changelog ? '<div class="mt-2 text-sm text-secondary whitespace-preline">' + data.changelog + '</div>' : '';
            result.innerHTML = '<div class="action-row">' +
                '<div><strong>v' + data.latest_version + '</strong> <span class="text-sm text-muted">(' + (data.release_date || '') + ')</span></div>' +
                '<button type="button" onclick="performUpdate()" id="performUpdateBtn" class="btn btn-primary text-sm">{{ t("common.update_now") }}</button>' +
                '</div>' + changelog;
        } else {
            status.textContent = '{{ t("settings.up_to_date") }}'.replace(/&#39;/g, "'");
            result.classList.remove('error');
            result.classList.add('visible', 'success');
            result.innerHTML = '<span class="text-success">✅ {{ t("settings.up_to_date") }}</span>';
        }
    }).catch(function() {
        btn.disabled = false;
        btn.textContent = origText;
        status.textContent = '{{ t("settings.connection_error") }}';
    });
}

function performUpdate() {
    var confirmMsg = _t.update_confirm;
    if (!confirm(confirmMsg)) return;
    
    var btn = document.getElementById('performUpdateBtn');
    btn.disabled = true;
    btn.textContent = '{{ t("common.updating") }}';
    
    fetch('{{ url_for("admin_update_perform") }}', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': document.querySelector('input[name=csrf_token]').value
        }
    }).then(function(r) { return r.json(); }).then(function(data) {
        if (data.success) {
            var result = document.getElementById('updateResult');
            var restartHtml = '';
            if (data.needs_manual_restart) {
                restartHtml = '<div class="result-box visible warning mt-2">' +
                    '⚠️ ' + (data.restart_msg || '') + '</div>' +
                    '<div class="mt-2"><button type="button" onclick="location.reload()" class="btn btn-primary text-sm">{{ t("common.reload") }}</button></div>';
            } else {
                restartHtml = '<div class="mt-2 text-sm text-muted">' +
                    (data.restart_msg || '{{ t("common.restart_hint") }}') + '</div>' +
                    '<div class="mt-2"><button type="button" onclick="location.reload()" class="btn btn-primary text-sm">{{ t("common.reload") }}</button></div>';
            }
            result.innerHTML = '<span class="text-success">✅ ' + data.message + '</span>' + restartHtml;
        } else {
            alert(data.error || '{{ t("settings.connection_error") }}');
            btn.disabled = false;
            btn.textContent = '{{ t("common.update_now") }}';
        }
    }).catch(function() {
        alert('{{ t("settings.connection_error") }}');
        btn.disabled = false;
        btn.textContent = '{{ t("common.update_now") }}';
    });
}

function deactivateLicense() {
    var confirmMsg = _t.license_deactivate;
    if (!confirm(confirmMsg)) return;
    fetch('{{ url_for("admin_license_deactivate") }}', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': document.querySelector('input[name=csrf_token]').value
        }
    }).then(function(r) { return r.json(); }).then(function(data) {
        if (data.success) { location.reload(); }
        else { alert(data.error || '{{ t("settings.deactivation_failed") }}'); }
    }).catch(function() { alert('{{ t("settings.connection_error") }}'); });
}

function setupSSL() {
    var domain = document.getElementById('ssl_domain').value.trim().toLowerCase();
    if (!domain) {
        alert(_t.ssl_error_empty);
        return;
    }
    
    // Basic client-side check
    if (!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*\.[a-z]{2,}$/.test(domain)) {
        alert(_t.ssl_error_invalid);
        return;
    }
    
    var confirmMsg = _t.ssl_confirm;
    if (!confirm(confirmMsg.replace('{domain}', domain))) return;
    
    var btn = document.getElementById('sslBtn');
    var status = document.getElementById('sslStatus');
    var result = document.getElementById('sslResult');
    var origText = btn.textContent;
    
    btn.disabled = true;
    btn.textContent = _t.ssl_setting_up;
    status.textContent = _t.ssl_setting_up_detail;
    result.classList.remove('visible', 'success', 'error');
    
    fetch('{{ url_for("admin_ssl_setup") }}', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': document.querySelector('input[name=csrf_token]').value
        },
        body: JSON.stringify({ domain: domain })
    }).then(function(r) { return r.json(); }).then(function(data) {
        btn.disabled = false;
        btn.textContent = origText;
        
        if (data.success) {
            status.innerHTML = _t.ssl_status_active;
            result.classList.remove('error');
            result.classList.add('visible', 'success');
            result.innerHTML = '✅ ' + data.message + 
                '<div class="mt-2 text-sm text-muted">' +
                _t.ssl_reload_hint + '</div>';
        } else {
            status.textContent = _t.ssl_setup_failed;
            result.classList.remove('success');
            result.classList.add('visible', 'error');
            result.textContent = data.error;
        }
    }).catch(function(err) {
        btn.disabled = false;
        btn.textContent = origText;
        status.textContent = _t.connection_error;
    });
}
</script>
{% endblock %}
