<%- include('../partials/header') %>
<%- include('../partials/sidebar') %>

<style>
  :root {
    --adm-bg: #f8fafc;
    --adm-surface: #ffffff;
    --adm-border: #e2e8f0;
    --adm-primary: #4f46e5;
    --adm-primary-hover: #4338ca;
    --adm-primary-lt: #eef2ff; 
    --adm-text: #0f172a;
    --adm-text-muted: #64748b;
    --adm-code-font: ui-monospace, 'SFMono-Regular', Menlo, Consolas, monospace;
  }

  .landing-manager-wrapper {
    flex-grow: 1;
    padding: clamp(14px, 2.5vw, 28px);
    max-width: 1100px;
    width: 100%;
    margin: 0 auto;
    background-color: var(--adm-bg);
  }

  .landing-card {
    background: var(--adm-surface);
    border: 1px solid var(--adm-border);
    border-radius: 14px;
    padding: clamp(16px, 3vw, 24px);
    margin-bottom: 20px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.03);
  }

  .card-section-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-bottom: 12px;
    margin-bottom: 16px;
    border-bottom: 1px solid var(--adm-border);
  }

  .card-section-title {
    font-size: 1.05rem;
    font-weight: 800;
    color: var(--adm-text);
    display: flex;
    align-items: center;
    gap: 8px;
    margin: 0;
  }

  .preview-thumbnail-box {
    width: 44px;
    height: 44px;
    border-radius: 10px;
    border: 1.5px dashed var(--adm-border);
    background: #f8fafc;
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
    flex-shrink: 0;
  }
  .preview-thumbnail-box img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .og-banner-preview {
    width: 100%;
    max-width: 240px;
    height: 90px;
    border-radius: 8px;
    border: 1.5px dashed var(--adm-border);
    background: #f8fafc;
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
  }
  .og-banner-preview img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .tech-code-input {
    background: #090d16 !important;
    color: #38bdf8 !important;
    font-family: var(--adm-code-font) !important;
    font-size: 0.85rem !important;
    line-height: 1.5 !important;
    border: 1px solid #1e293b !important;
  }
</style>

<div class="landing-manager-wrapper">

    <!-- Top Sticky Header -->
    <div class="d-flex justify-content-between align-items-center mb-4 flex-wrap gap-2">
        <div>
            <h1 class="fw-bold text-dark mb-0 fs-2 d-flex align-items-center gap-2">
                <i class="ti ti-layout-dashboard text-primary"></i> Landing Page Manager
            </h1>
            <div class="text-muted small">Configure homepage hero banner, favicon icons, AdSense slots, and SEO meta tags</div>
        </div>
        <div class="d-flex align-items-center gap-2">
            <a href="/" target="_blank" class="btn btn-outline-secondary rounded-3 px-3 py-2 fw-bold small">
                <i class="ti ti-external-link me-1"></i> View Live Site
            </a>
            <button type="button" onclick="document.getElementById('landingForm').requestSubmit()" class="btn btn-primary fw-bold shadow-sm rounded-3 px-4 py-2">
                <i class="ti ti-device-floppy me-1"></i> Save All
            </button>
        </div>
    </div>

    <!-- Save Alert -->
    <div id="saveAlert" class="alert alert-success d-none mb-3 shadow-sm rounded-3 border-0 d-flex align-items-center gap-2" role="alert">
        <i class="ti ti-circle-check fs-2 text-success"></i>
        <div><strong>Settings Saved!</strong> All homepage banners, favicons, and meta tags are live now.</div>
    </div>

    <form id="landingForm">
        
        <!-- 1. FAVICON & BRAND ASSETS UPLOAD -->
        <div class="landing-card">
            <div class="card-section-header">
                <h2 class="card-section-title">
                    <i class="ti ti-photo text-primary fs-2"></i> Favicon & Brand Icons
                </h2>
                <span class="badge bg-primary-lt text-primary">Browser Tab Branding</span>
            </div>

            <div class="row g-3">
                <!-- Favicon Upload -->
                <div class="col-md-6">
                    <label class="form-label fw-bold small text-dark">Website Favicon (.ico / .png / .svg)</label>
                    <div class="d-flex align-items-center gap-3">
                        <div class="preview-thumbnail-box" id="faviconPreviewBox">
                            <% if (typeof landing !== 'undefined' && landing.seo && landing.seo.favicon) { %>
                                <img src="<%= landing.seo.favicon %>" id="faviconPreviewImg" alt="Favicon">
                            <% } else { %>
                                <i class="ti ti-flame text-muted fs-3" id="faviconFallbackIcon"></i>
                                <img src="" id="faviconPreviewImg" class="d-none" alt="Favicon">
                            <% } %>
                        </div>
                        <div class="flex-grow-1">
                            <input type="file" id="faviconFileInput" accept=".ico,.png,.svg" class="d-none" onchange="handleImageUpload(this, 'faviconUrlInput', 'faviconPreviewImg', 'faviconFallbackIcon')">
                            <button type="button" class="btn btn-sm btn-outline-primary rounded-pill px-3" onclick="document.getElementById('faviconFileInput').click()">
                                <i class="ti ti-upload me-1"></i> Upload Favicon
                            </button>
                            <input type="text" name="favicon" id="faviconUrlInput" class="form-control form-control-sm rounded-3 mt-2 font-monospace" placeholder="/favicon.ico or URL" value="<%= (typeof landing !== 'undefined' && landing.seo && landing.seo.favicon) ? landing.seo.favicon : '' %>" oninput="updateFaviconFromUrl(this.value)">
                        </div>
                    </div>
                </div>

                <!-- Apple Touch Icon Upload -->
                <div class="col-md-6">
                    <label class="form-label fw-bold small text-dark">Apple Touch Icon (180x180 png)</label>
                    <div class="d-flex align-items-center gap-3">
                        <div class="preview-thumbnail-box" id="appleTouchPreviewBox">
                            <% if (typeof landing !== 'undefined' && landing.seo && landing.seo.appleTouchIcon) { %>
                                <img src="<%= landing.seo.appleTouchIcon %>" id="appleTouchPreviewImg" alt="Apple Touch Icon">
                            <% } else { %>
                                <i class="ti ti-device-mobile text-muted fs-3" id="appleTouchFallbackIcon"></i>
                                <img src="" id="appleTouchPreviewImg" class="d-none" alt="Apple Touch Icon">
                            <% } %>
                        </div>
                        <div class="flex-grow-1">
                            <input type="file" id="appleTouchFileInput" accept=".png" class="d-none" onchange="handleImageUpload(this, 'appleTouchUrlInput', 'appleTouchPreviewImg', 'appleTouchFallbackIcon')">
                            <button type="button" class="btn btn-sm btn-outline-primary rounded-pill px-3" onclick="document.getElementById('appleTouchFileInput').click()">
                                <i class="ti ti-upload me-1"></i> Upload Apple Icon
                            </button>
                            <input type="text" name="appleTouchIcon" id="appleTouchUrlInput" class="form-control form-control-sm rounded-3 mt-2 font-monospace" placeholder="/apple-touch-icon.png or URL" value="<%= (typeof landing !== 'undefined' && landing.seo && landing.seo.appleTouchIcon) ? landing.seo.appleTouchIcon : '' %>" oninput="updateAppleTouchFromUrl(this.value)">
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 2. TOP ANNOUNCEMENT RIBBON -->
        <div class="landing-card">
            <div class="card-section-header">
                <h2 class="card-section-title">
                    <i class="ti ti-speakerphone text-primary fs-2"></i> Top Announcement Ribbon
                </h2>
                <span class="badge bg-primary-lt text-primary">Header Top</span>
            </div>

            <div class="p-3 rounded-3 bg-light border">
                <div class="form-check form-switch mb-2">
                    <input class="form-check-input" type="checkbox" id="announcementEnabled" name="announcementEnabled" <%= (typeof landing !== 'undefined' && landing.announcement && landing.announcement.enabled) ? 'checked' : '' %>>
                    <label class="form-check-label fw-bold text-dark" for="announcementEnabled">Enable Announcement Ribbon at Top of Website</label>
                </div>
                <div class="row g-2 mt-1">
                    <div class="col-md-8">
                        <label class="form-label small text-muted">Announcement Message</label>
                        <input type="text" name="announcementText" class="form-control rounded-3" placeholder="e.g. 🎉 New: Unused CSS Remover is now live!" value="<%= (typeof landing !== 'undefined' && landing.announcement) ? landing.announcement.text : '' %>">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label small text-muted">Action Link URL (Optional)</label>
                        <input type="text" name="announcementLink" class="form-control rounded-3" placeholder="/tool/css-cleaner" value="<%= (typeof landing !== 'undefined' && landing.announcement) ? landing.announcement.link : '' %>">
                    </div>
                </div>
            </div>
        </div>

        <!-- 3. HERO BANNER & SEARCH BAR -->
        <div class="landing-card">
            <div class="card-section-header">
                <h2 class="card-section-title">
                    <i class="ti ti-layout-navbar text-success fs-2"></i> Hero Banner & Headline
                </h2>
                <span class="badge bg-success-lt text-success">Above The Fold</span>
            </div>
            
            <div class="row g-3">
                <div class="col-md-6">
                    <label class="form-label fw-bold small text-dark">Hero Badge Text</label>
                    <input type="text" name="heroBadge" class="form-control rounded-3" value="<%= (typeof landing !== 'undefined' && landing.heroBadge) ? landing.heroBadge : '⚡ 100% Free & Client-Side Secure' %>">
                </div>
                <div class="col-md-6">
                    <label class="form-label fw-bold small text-dark">Search Bar Placeholder</label>
                    <input type="text" name="searchPlaceholder" class="form-control rounded-3" value="<%= (typeof landing !== 'undefined' && landing.searchPlaceholder) ? landing.searchPlaceholder : 'Search tools... (Press \'/\' to focus)' %>">
                </div>
                <div class="col-12">
                    <label class="form-label fw-bold small text-dark">Main Hero Headline</label>
                    <input type="text" name="heroTitle" class="form-control rounded-3 fw-bold fs-3" value="<%= (typeof landing !== 'undefined' && landing.heroTitle) ? landing.heroTitle : 'Smarter Online Tools for' %>">
                    <small class="text-muted">The word 'Creators' is automatically styled with a neon gradient.</small>
                </div>
                <div class="col-12">
                    <label class="form-label fw-bold small text-dark">Hero Subtitle Paragraph</label>
                    <textarea name="heroSubtitle" class="form-control rounded-3" rows="2"><%= (typeof landing !== 'undefined' && landing.heroSubtitle) ? landing.heroSubtitle : 'Blazing-fast utilities built with privacy, no installations, and zero data tracking.' %></textarea>
                </div>
            </div>
        </div>

        <!-- 4. GOOGLE SEO, SOCIAL BANNER & ANALYTICS -->
        <div class="landing-card">
            <div class="card-section-header">
                <h2 class="card-section-title">
                    <i class="ti ti-search text-warning fs-2"></i> Google SEO, OG Image & Analytics
                </h2>
                <span class="badge bg-warning-lt text-warning">Ranking Engine</span>
            </div>
            
            <div class="row g-3">
                <div class="col-12">
                    <label class="form-label fw-bold small text-dark">Homepage Meta Title (Max 60 chars)</label>
                    <input type="text" name="metaTitle" class="form-control rounded-3" value="<%= (typeof landing !== 'undefined' && landing.seo) ? landing.seo.metaTitle : '' %>">
                </div>
                <div class="col-12">
                    <label class="form-label fw-bold small text-dark">Meta Description (Max 160 chars)</label>
                    <textarea name="metaDescription" class="form-control rounded-3" rows="2"><%= (typeof landing !== 'undefined' && landing.seo) ? landing.seo.metaDescription : '' %></textarea>
                </div>
                <div class="col-md-6">
                    <label class="form-label fw-bold small text-dark">Keywords (Comma separated)</label>
                    <input type="text" name="keywords" class="form-control rounded-3" value="<%= (typeof landing !== 'undefined' && landing.seo) ? landing.seo.keywords : '' %>">
                </div>
                <div class="col-md-6">
                    <label class="form-label fw-bold small text-dark">Google Analytics (GA4) ID</label>
                    <input type="text" name="gaId" class="form-control rounded-3" placeholder="e.g. G-XXXXXXXXXX" value="<%= (typeof landing !== 'undefined' && landing.seo) ? landing.seo.gaId : '' %>">
                </div>
                <div class="col-12">
                    <label class="form-label fw-bold small text-dark">Google Search Console Verification Meta Tag</label>
                    <input type="text" name="gscTag" class="form-control rounded-3 font-monospace" placeholder='<meta name="google-site-verification" content="..." />' value="<%= (typeof landing !== 'undefined' && landing.seo) ? landing.seo.gscTag : '' %>">
                </div>
                
                <!-- Social Share OG Banner Upload -->
                <div class="col-12">
                    <label class="form-label fw-bold small text-dark">Social Share Banner (OG Image 1200x630)</label>
                    <div class="d-flex align-items-center gap-3 flex-wrap">
                        <div class="og-banner-preview" id="ogPreviewBox">
                            <% if (typeof landing !== 'undefined' && landing.seo && landing.seo.ogImage) { %>
                                <img src="<%= landing.seo.ogImage %>" id="ogPreviewImg" alt="Social Banner">
                            <% } else { %>
                                <i class="ti ti-photo text-muted fs-1" id="ogFallbackIcon"></i>
                                <img src="" id="ogPreviewImg" class="d-none" alt="Social Banner">
                            <% } %>
                        </div>
                        <div class="flex-grow-1" style="min-width: 250px;">
                            <input type="file" id="ogFileInput" accept=".jpg,.jpeg,.png,.webp" class="d-none" onchange="handleImageUpload(this, 'ogUrlInput', 'ogPreviewImg', 'ogFallbackIcon')">
                            <button type="button" class="btn btn-sm btn-outline-primary rounded-pill px-3" onclick="document.getElementById('ogFileInput').click()">
                                <i class="ti ti-upload me-1"></i> Upload Social Banner
                            </button>
                            <input type="text" name="ogImage" id="ogUrlInput" class="form-control form-control-sm rounded-3 mt-2 font-monospace" placeholder="https://tools.heyswan.cloud/banner.png" value="<%= (typeof landing !== 'undefined' && landing.seo) ? landing.seo.ogImage : '' %>" oninput="updateOgFromUrl(this.value)">
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 5. MONETIZATION & HIGH-CTR AD SLOTS -->
        <div class="landing-card">
            <div class="card-section-header">
                <h2 class="card-section-title">
                    <i class="ti ti-coin text-danger fs-2"></i> Monetization & Ad Placements
                </h2>
                <span class="badge bg-danger-lt text-danger">Revenue</span>
            </div>
            
            <div class="row g-3">
                <div class="col-12">
                    <label class="form-label fw-bold small text-dark">1. Header Top Banner Ad Code (Displays Below Search)</label>
                    <textarea name="headerAd" class="form-control tech-code-input" rows="2" placeholder="<!-- Paste AdSense / Adsterra Header Banner Script -->"><%= (typeof landing !== 'undefined' && landing.ads) ? landing.ads.headerAd : '' %></textarea>
                </div>
                <div class="col-12">
                    <label class="form-label fw-bold small text-dark">2. In-Grid Native Ad Code (Displays Between Tool Cards)</label>
                    <textarea name="gridAd" class="form-control tech-code-input" rows="2" placeholder="<!-- Paste Native Responsive Ad Script -->"><%= (typeof landing !== 'undefined' && landing.ads) ? landing.ads.gridAd : '' %></textarea>
                </div>
                <div class="col-12">
                    <label class="form-label fw-bold small text-dark">3. Footer Banner Ad Code</label>
                    <textarea name="footerAd" class="form-control tech-code-input" rows="2" placeholder="<!-- Paste Footer Ad Script -->"><%= (typeof landing !== 'undefined' && landing.ads) ? landing.ads.footerAd : '' %></textarea>
                </div>
            </div>
        </div>

        <!-- 6. FOOTER & SOCIAL MEDIA -->
        <div class="landing-card">
            <div class="card-section-header">
                <h2 class="card-section-title">
                    <i class="ti ti-world text-info fs-2"></i> Footer Bio & Social Links
                </h2>
                <span class="badge bg-info-lt text-info">Branding</span>
            </div>
            
            <div class="row g-3">
                <div class="col-12">
                    <label class="form-label fw-bold small text-dark">Footer About Us Statement</label>
                    <textarea name="aboutText" class="form-control rounded-3" rows="2"><%= (typeof landing !== 'undefined' && landing.footer) ? landing.footer.aboutText : '' %></textarea>
                </div>
                <div class="col-md-6">
                    <label class="form-label fw-bold small text-dark">GitHub URL</label>
                    <input type="url" name="github" class="form-control rounded-3" value="<%= (typeof landing !== 'undefined' && landing.footer) ? landing.footer.github : '' %>">
                </div>
                <div class="col-md-6">
                    <label class="form-label fw-bold small text-dark">Twitter / X URL</label>
                    <input type="url" name="twitter" class="form-control rounded-3" value="<%= (typeof landing !== 'undefined' && landing.footer) ? landing.footer.twitter : '' %>">
                </div>
                <div class="col-md-6">
                    <label class="form-label fw-bold small text-dark">Discord URL</label>
                    <input type="url" name="discord" class="form-control rounded-3" value="<%= (typeof landing !== 'undefined' && landing.footer) ? landing.footer.discord : '' %>">
                </div>
                <div class="col-md-6">
                    <label class="form-label fw-bold small text-dark">LinkedIn URL</label>
                    <input type="url" name="linkedin" class="form-control rounded-3" value="<%= (typeof landing !== 'undefined' && landing.footer) ? landing.footer.linkedin : '' %>">
                </div>
                <div class="col-12">
                    <label class="form-label fw-bold small text-dark">Copyright Statement</label>
                    <input type="text" name="copyright" class="form-control rounded-3" value="<%= (typeof landing !== 'undefined' && landing.footer) ? landing.footer.copyright : '' %>">
                </div>
            </div>
        </div>

        <!-- 7. CUSTOM SCRIPTS INJECTION -->
        <div class="landing-card mb-4">
            <div class="card-section-header">
                <h2 class="card-section-title">
                    <i class="ti ti-code text-purple fs-2"></i> Custom Code Injection
                </h2>
                <span class="badge bg-purple-lt text-purple">Advanced</span>
            </div>
            
            <div class="row g-3">
                <div class="col-12">
                    <label class="form-label fw-bold small text-dark">Custom Header Code (Injected into &lt;head&gt;)</label>
                    <textarea name="headerScripts" class="form-control tech-code-input" rows="2" placeholder="<style>...</style> or <script>...</script>"><%= (typeof landing !== 'undefined' && landing.customCode) ? landing.customCode.headerScripts : '' %></textarea>
                </div>
                <div class="col-12">
                    <label class="form-label fw-bold small text-dark">Custom Footer Code (Injected before &lt;/body&gt;)</label>
                    <textarea name="footerScripts" class="form-control tech-code-input" rows="2" placeholder="<script>/* Live Chat / Custom tracking */</script>"><%= (typeof landing !== 'undefined' && landing.customCode) ? landing.customCode.footerScripts : '' %></textarea>
                </div>
            </div>
        </div>

        <!-- Bottom Save Button Bar -->
        <div class="p-3 bg-white rounded-4 shadow-sm border d-flex justify-content-between align-items-center mb-5 flex-wrap gap-2">
            <span class="text-muted small">All changes reflect live instantly without restarting the server.</span>
            <button type="submit" class="btn btn-primary fw-bold px-4 py-2 rounded-3 shadow-sm">
                <i class="ti ti-device-floppy me-1"></i> Save All Landing Settings
            </button>
        </div>

    </form>

</div>

<script>
    // ── IMAGE FILE TO BASE64 UPLOADER (ZERO SERVER OVERHEAD) ──
    function handleImageUpload(inputEl, targetInputId, previewImgId, fallbackIconId) {
        const file = inputEl.files[0];
        if (!file) return;

        const reader = new FileReader();
        reader.onload = function(e) {
            const dataUrl = e.target.result;
            document.getElementById(targetInputId).value = dataUrl;
            
            const previewImg = document.getElementById(previewImgId);
            previewImg.src = dataUrl;
            previewImg.classList.remove('d-none');
            
            const fallbackIcon = document.getElementById(fallbackIconId);
            if (fallbackIcon) fallbackIcon.classList.add('d-none');
        };
        reader.readAsDataURL(file);
    }

    function updateFaviconFromUrl(url) {
        const img = document.getElementById('faviconPreviewImg');
        const fallback = document.getElementById('faviconFallbackIcon');
        if (url && url.trim()) {
            img.src = url;
            img.classList.remove('d-none');
            if (fallback) fallback.classList.add('d-none');
        } else {
            img.classList.add('d-none');
            if (fallback) fallback.classList.remove('d-none');
        }
    }

    function updateAppleTouchFromUrl(url) {
        const img = document.getElementById('appleTouchPreviewImg');
        const fallback = document.getElementById('appleTouchFallbackIcon');
        if (url && url.trim()) {
            img.src = url;
            img.classList.remove('d-none');
            if (fallback) fallback.classList.add('d-none');
        } else {
            img.classList.add('d-none');
            if (fallback) fallback.classList.remove('d-none');
        }
    }

    function updateOgFromUrl(url) {
        const img = document.getElementById('ogPreviewImg');
        const fallback = document.getElementById('ogFallbackIcon');
        if (url && url.trim()) {
            img.src = url;
            img.classList.remove('d-none');
            if (fallback) fallback.classList.add('d-none');
        } else {
            img.classList.add('d-none');
            if (fallback) fallback.classList.remove('d-none');
        }
    }

    // Form Save Handler
    document.getElementById('landingForm').onsubmit = async (e) => {
        e.preventDefault();
        const formData = new FormData(e.target);
        const body = Object.fromEntries(formData.entries());
        body.announcementEnabled = formData.get('announcementEnabled') === 'on';

        const res = await fetch('/api/admin/landing', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(body)
        });

        if (res.ok) {
            const alertBox = document.getElementById('saveAlert');
            alertBox.classList.remove('d-none');
            window.scrollTo({ top: 0, behavior: 'smooth' });
            setTimeout(() => alertBox.classList.add('d-none'), 3500);
        } else {
            alert('Failed to save settings. Please try again.');
        }
    };
</script>

<%- include('../partials/footer') %>