document.addEventListener("DOMContentLoaded", function () {
    const STORAGE_KEY = "whatsNewDismissUntil";
    const DEFAULT_VERSION = "v104";

    // get version from meta[name="app-version"] or #app-version element or fallback
    const meta = document.querySelector('meta[name="app-version"]');
    const el = document.getElementById("app-version");
    const version = (meta && meta.content) || (el && el.dataset.version) || DEFAULT_VERSION;

    // if dismissed and not expired -> do nothing
    const dismissedUntil = parseInt(localStorage.getItem(STORAGE_KEY) || "0", 10);
    if (dismissedUntil && Date.now() < dismissedUntil) return;

    setTimeout(() => {
        // remove existing whats-new if present (replace old content)
        const existing = document.getElementById("whats-new");
        if (existing) existing.remove();

        const container = document.querySelector(".swagger-ui");
        if (!container) return;

        // build banner
        const whatsNewDiv = document.createElement("div");
        whatsNewDiv.id = "whats-new";
        whatsNewDiv.setAttribute("role", "region");
        whatsNewDiv.setAttribute("aria-label", "What's New");
        whatsNewDiv.style.cssText = [
            "background:#ffffff",
            "border:1px solid rgba(0,0,0,0.06)",
            "padding:16px",
            "border-radius:8px",
            "margin:16px auto",
            "max-width:980px",
            "box-shadow:0 6px 18px rgba(0,0,0,0.06)",
            "font-family:Inter,Segoe UI,Roboto,Helvetica,Arial,sans-serif",
            "color:#222",
            "transition:opacity .28s ease,transform .28s ease",
            "opacity:0",
            "transform:translateY(-6px)"
        ].join(";");

        // close button
        const closeBtn = document.createElement("button");
        closeBtn.type = "button";
        closeBtn.title = "Dismiss for 7 days";
        closeBtn.innerHTML = "&times;";
        closeBtn.style.cssText = "position:absolute;right:12px;top:10px;border:0;background:transparent;font-size:22px;line-height:1;color:#666;cursor:pointer;";
        closeBtn.addEventListener("click", () => {
            // dismiss for 7 days
            const days = 7;
            localStorage.setItem(STORAGE_KEY, String(Date.now() + days * 24 * 60 * 60 * 1000));
            whatsNewDiv.remove();
        });

        // header / version
        const header = document.createElement("div");
        header.style.cssText = "display:flex;align-items:center;gap:12px;margin-bottom:8px;";
        header.innerHTML = `<div style="width:44px;height:44px;border-radius:8px;background:linear-gradient(135deg,#007bff,#00b5ff);display:flex;align-items:center;justify-content:center;color:white;font-weight:600;font-size:18px">v</div>
            <div>
                <div style="font-size:18px;color:#0b5ed7;font-weight:600">What's New <span style='font-weight:400;color:#666;font-size:13px;margin-left:8px'>${version}</span></div>
                <div style="font-size:13px;color:#6b7280;margin-top:2px">Latest changes and endpoints</div>
            </div>`;

        // body list (replace old entries)
        const list = document.createElement("ul");
        list.style.cssText = "margin:10px 0 14px 0;padding-left:18px;color:#333";
        const items = [
            "<strong>OrderImport PUT</strong>: updates PdfUrl and Deltio when provided — PUT /api/OrderImport/{requestID}",
            "<strong>New POST</strong> /api/Apothiki — create Apothiki_Temp (use ApothikiCreateDto)",
            "<strong>Vehicles</strong>: added userID to responses",
            "<strong>Messages</strong>: GET /api/Messages/{userId} returns today's messages",
            "<strong>Services_Jobs</strong>: DELETE /api/Services_Jobs/{requestID} added"
        ];
        items.forEach(i => {
            const li = document.createElement("li");
            li.style.cssText = "margin:6px 0;font-size:14px;line-height:1.35";
            li.innerHTML = i;
            list.appendChild(li);
        });

        // footer actions
        const footer = document.createElement("div");
        footer.style.cssText = "display:flex;gap:10px;align-items:center;justify-content:flex-end;margin-top:8px";
        const changelog = document.createElement("a");
        changelog.href = "/OrbitApi/v104/swagger.json"; // point to current OAS / OrbitApi/v104
        changelog.textContent = "Open OAS (v104)";
        changelog.style.cssText = "font-size:13px;color:#0b5ed7;text-decoration:none";
        const dismissNow = document.createElement("button");
        dismissNow.type = "button";
        dismissNow.textContent = "Dismiss";
        dismissNow.style.cssText = "background:#f1f5f9;border:1px solid #e2e8f0;padding:6px 10px;border-radius:6px;font-size:13px;cursor:pointer";
        dismissNow.addEventListener("click", () => {
            localStorage.setItem(STORAGE_KEY, String(Date.now() + 24 * 60 * 60 * 1000)); // 1 day
            whatsNewDiv.remove();
        });

        footer.appendChild(changelog);
        footer.appendChild(dismissNow);

        // assemble
        whatsNewDiv.appendChild(closeBtn);
        whatsNewDiv.appendChild(header);
        whatsNewDiv.appendChild(list);
        whatsNewDiv.appendChild(footer);

        // insert after topbar if present
        const topbar = document.querySelector(".swagger-ui .topbar");
        if (topbar) {
            topbar.after(whatsNewDiv);
        } else {
            container.prepend(whatsNewDiv);
        }

        // animate in
        requestAnimationFrame(() => {
            whatsNewDiv.style.opacity = "1";
            whatsNewDiv.style.transform = "translateY(0)";
        });
    }, 300);

    // small enhancement for the Authorize dialog message (keeps previous behavior)
    setTimeout(function () {
        const authButton = document.querySelector(".swagger-ui .btn.authorize");
        if (authButton) {
            authButton.addEventListener("click", function () {
                setTimeout(function () {
                    const authContainer = document.querySelector(".swagger-ui .dialog-ux .modal-ux-content");
                    if (authContainer) {
                        const existingMessage = document.getElementById("custom-auth-message");
                        if (!existingMessage) {
                            const descriptionText = document.createElement("p");
                            descriptionText.id = "custom-auth-message";
                            descriptionText.style.fontSize = "14px";
                            descriptionText.style.color = "#333";
                            descriptionText.style.marginBottom = "10px";
                            descriptionText.innerHTML = "Enter your API Key (header: <code>X-API-Key</code>).<br><b>Example:</b> <code>c2ac2151-fba3-441c-bd3b-e0a0891cc687</code>";
                            authContainer.insertBefore(descriptionText, authContainer.firstChild);
                        }
                    }
                }, 250);
            });
        }
    }, 600);
});

