(function ($) {
    'use strict';

    const scriptSrc = document.currentScript ? document.currentScript.src : '';
    const baseUrl = scriptSrc ? scriptSrc.replace(/js\/ajax-data\.js.*$/, '') : '/medsfaq/';
    const apiUrl = baseUrl + 'api/';

    let currentBlogPage = 1;
    let currentBlogCategory = 0;
    let currentBlogCategorySlug = getCategorySlugFromUrl();
    let currentMedicationPage = 1;
    let currentMedicationLetter = '';
    const blogLimit = 6;
    const medicationLimit = 24;

    function escapeHtml(value) {
        return $('<div>').text(value || '').html();
    }

    function formatDate(value) {
        if (!value) return '';

        const date = new Date(String(value).replace(' ', 'T'));
        if (Number.isNaN(date.getTime())) return value;

        return date.toLocaleDateString('en-IN', {
            year: 'numeric',
            month: 'short',
            day: 'numeric'
        });
    }

    function getSlugFromUrl() {
        const params = new URLSearchParams(window.location.search);
        if (params.get('slug')) return params.get('slug');

        const parts = window.location.pathname.split('/').filter(Boolean);
        return parts.length ? decodeURIComponent(parts[parts.length - 1]) : '';
    }

    function getCategorySlugFromUrl() {
        const parts = window.location.pathname.split('/').filter(Boolean);
        const categoryIndex = parts.indexOf('category');

        if (categoryIndex !== -1 && parts[categoryIndex + 1]) {
            return decodeURIComponent(parts[categoryIndex + 1]);
        }

        return '';
    }

    function getCategoryIdFromQuery() {
        const params = new URLSearchParams(window.location.search);
        return Number(params.get('category_id')) || 0;
    }

    function tagLinks(tags) {
        if (!tags) return '';

        return String(tags).split(',')
            .map(tag => tag.trim())
            .filter(Boolean)
            .map(tag => `<a href="#!">${escapeHtml(tag)}</a>`)
            .join(' ');
    }

    function loadCategories() {
        const $categoryContainer = $('#categoryContainer');
        const $categoryList = $('#categoryList');

        if (!$categoryContainer.length && !$categoryList.length) return;

        $.getJSON(apiUrl + 'categories')
            .done(function (categories) {
                const queryCategoryId = getCategoryIdFromQuery();
                const queryCategory = categories.find(category => Number(category.id) === queryCategoryId);

                if (queryCategory && !currentBlogCategorySlug) {
                    window.location.replace(baseUrl + 'blog/category/' + encodeURIComponent(queryCategory.slug));
                    return;
                }

                const activeCategory = categories.find(category => category.slug === currentBlogCategorySlug);
                currentBlogCategory = activeCategory ? Number(activeCategory.id) : 0;

                if ($categoryContainer.length) {
                    const buttons = [
                        `<a href="${baseUrl}blog" class="cat-btn ${currentBlogCategorySlug ? '' : 'active'}" data-category-id="0" data-category-slug="">All</a>`
                    ].concat(categories.map(category =>
                        `<a href="${baseUrl}blog/category/${encodeURIComponent(category.slug)}" class="cat-btn ${category.slug === currentBlogCategorySlug ? 'active' : ''}" data-category-id="${category.id}" data-category-slug="${escapeHtml(category.slug)}">${escapeHtml(category.name)}</a>`
                    ));

                    $categoryContainer.html(buttons.join(''));
                }

                if ($categoryList.length) {
                    $categoryList.html(categories.map(category =>
                        `<li><a href="${baseUrl}blog/category/${encodeURIComponent(category.slug)}">${escapeHtml(category.name)}</a></li>`
                    ).join(''));
                }

                if ($('#blogContainer').length && $('#paginationContainer').length) {
                    loadBlogs(1);
                }
            })
            .fail(function () {
                $categoryContainer.html('<span>Unable to load categories.</span>');
                $categoryList.html('<li>Unable to load categories.</li>');
            });
    }

    function renderBlogCard(blog) {
        const title = escapeHtml(blog.blog_title || 'Untitled blog');
        const slug = encodeURIComponent(blog.blogslug || '');
        const image = baseUrl +( escapeHtml(blog.img || 'img/blog/default-blog.jpg'));

        return `
            <div class="col-md-6 col-xl-4 mt-2-9">
                <article class="card card-style6 h-100">
                    <div class="image-box image-hover">
                        <img src="${image}" class="border-radius-10" alt="${title}">
                    </div>
                    <div class="card-body">
                        <ul class="list-unstyled mb-3">
                            <li class="d-inline-block">
                                <i class="far fa-calendar-check me-2 text-primary align-middle"></i>
                                ${formatDate(blog.created_at)}
                            </li>
                        </ul>
                        <h3 class="h5 mb-3">
                            <a href="${baseUrl}blog/${slug}">${title}</a>
                        </h3>
                        <a href="${baseUrl}blog/${slug}" class="text-primary font-weight-600">Read More</a>
                    </div>
                </article>
            </div>
        `;
    }

    function loadBlogs(page) {
        const $container = $('#blogContainer');
        if (!$container.length || !$('#paginationContainer').length) return;

        currentBlogPage = page || 1;
        $container.html('<div class="col-12 text-center py-5">Loading blogs...</div>');

        $.getJSON(apiUrl + 'blogs', {
            page: currentBlogPage,
            limit: blogLimit,
            category_id: currentBlogCategory,
            category_slug: currentBlogCategorySlug
        }).done(function (response) {
            const blogs = response.blogs || [];

            $container.html(
                blogs.length
                    ? blogs.map(renderBlogCard).join('')
                    : '<div class="col-12 text-center py-5">No blogs found.</div>'
            );

            renderPagination(response.totalPages || 1, currentBlogPage);
        }).fail(function () {
            $container.html('<div class="col-12 text-center py-5">Unable to load blogs.</div>');
        });
    }

function renderPagination(totalPages, activePage) {
    const $pagination = $('#paginationContainer');
    if (!$pagination.length || totalPages <= 1) return;

    let html = '';

    // Previous Button
    if (activePage > 1) {
        html += `
            <li class="pagination-prev">
                <a href="#!" data-blog-page="${activePage - 1}">
                    Prev
                </a>
            </li>
        `;
    }

    // Show current-1, current, current+1
    let startPage = Math.max(1, activePage - 1);
    let endPage = Math.min(totalPages, activePage + 1);

    // Fix when active page is near start
    if (activePage === 1) {
        endPage = Math.min(totalPages, 3);
    }

    // Fix when active page is near end
    if (activePage === totalPages) {
        startPage = Math.max(1, totalPages - 2);
    }

    for (let page = startPage; page <= endPage; page++) {
        html += `
            <li class="${page === activePage ? 'active' : ''}">
                <a href="#!" data-blog-page="${page}">
                    ${page}
                </a>
            </li>
        `;
    }

    // Next Button
    if (activePage < totalPages) {
        html += `
            <li class="pagination-next">
                <a href="#!" data-blog-page="${activePage + 1}">
                    Next
                </a>
            </li>
        `;
    }

    $pagination.html(html);
}
    function renderLatestPost(blog) {
        const title = escapeHtml(blog.blog_title || 'View Post');
        const slug = encodeURIComponent(blog.blogslug || '');
        const image = baseUrl + ( escapeHtml(blog.img || 'img/blog/default-blog.jpg'));

        return `
            <div class="d-flex align-items-center mb-1-9">
                <div class="flex-shrink-0 image-hover">
                    <img src="${image}" class="w-70px border-radius-10" alt="${title}">
                </div>
                <div class="flex-grow-1 ps-3">
                    <h4 class="h6" "><a href="${baseUrl}blog/${slug}">${title}</a></h4>
                    
                </div>
            </div>
        `;
    }

    function loadLatestPosts() {
        const $latestPosts = $('#latestPosts');
        const $footerA = $('#footerRecentPostsA');
        const $footerB = $('#footerRecentPostsB');

        if (!$latestPosts.length && !$footerA.length && !$footerB.length) return;

        $.getJSON(apiUrl + 'blogs', { page: 1, limit: 4 }).done(function (response) {
            const blogs = response.blogs || [];
            $latestPosts.html(blogs.map(renderLatestPost).join('') || '<div>No posts found.</div>');
            $footerA.html(blogs.slice(0, 2).map(renderLatestPost).join(''));
            $footerB.html(blogs.slice(2, 4).map(renderLatestPost).join(''));
        });
    }

    function loadBlogDetail() {
        if (!$('#blogTitle').length && !$('#blogContent').length) return;
        if (window.location.pathname.indexOf('/blog') === -1 && !window.location.pathname.endsWith('/blog-details.php')) return;

        $.getJSON(apiUrl + 'blog', { slug: getSlugFromUrl() })
            .done(function (response) {
                const blog = response.blog || {};
                const title = blog.blog_title || 'Blog Details';

                document.title = title;
                $('#pageTitle').text(title);
                $('#blogTitle').text(title);
                $('#blogContent').html(blog.blog_content || '');

                $('#blogImage').attr('src',
                    baseUrl + (blog.img || 'img/blog/default-blog.jpg')
                ).attr('alt', title);
                $('#blogDate span').text(formatDate(blog.created_at));
                $('#blogMetaDate').text(formatDate(blog.created_at));
                $('#blogTags').html(tagLinks(blog.tags));
            })
            .fail(function () {
                $('#pageTitle').text('Blog not found');
                $('#blogContent').html('<p>Unable to load this blog.</p>');
            });
    }

    function renderAlphabet() {
        const $alphabet = $('#alphabetContainer');
        if (!$alphabet.length) return;

        const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
        const buttons = [`<button type="button" class="alpha-btn active" data-letter="">All</button>`]
            .concat(letters.map(letter => `<button type="button" data-letter="${letter}" class="alpha-btn">${letter}</button>`));

        $alphabet.html(buttons.join(''));
    }

    function renderMedicationItem(medication) {
        const title = escapeHtml(medication.titleTag || 'Medication');
        const slug = encodeURIComponent(medication.slug || '');

        return `
            <div class="medication-item">
                <a href="${baseUrl}medication/${slug}">${title}</a>
            </div>
        `;
    }

    function loadMedications(page, append) {
        const $container = $('#blogContainer');
        if (!$container.length || !$('#alphabetContainer').length) return;

        currentMedicationPage = page || 1;
        if (!append) {
            $container.html('<div class="py-5">Loading medications...</div>');
        }

        $.getJSON(apiUrl + 'medications', {
            page: currentMedicationPage,
            limit: medicationLimit,
            letter: currentMedicationLetter
        }).done(function (response) {
            const medications = (response.medications || []).sort(function (a, b) {
                return String(a.titleTag || '').trim().localeCompare(String(b.titleTag || '').trim(), undefined, {
                    sensitivity: 'base'
                });
            });
            const html = medications.length ? medications.map(renderMedicationItem).join('') : '<div class="py-5">No medications found.</div>';

            if (append) {
                $container.append(html);
            } else {
                $container.html(html);
            }

            const totalPages = response.totalPages || 1;
            $('#showMoreContainer').html(
                currentMedicationPage < totalPages
                    ? '<div class="text-center pb-5"><button type="button" class="butn border-0" id="showMoreMedications">Show More</button></div>'
                    : ''
            );
        }).fail(function () {
            $container.html('<div class="py-5">Unable to load medications.</div>');
        });
    }


    function loadMedicationDetail() {
    if (!$('#pageTitle').length || window.location.pathname.indexOf('/medication') === -1) return;
    if (window.location.pathname.indexOf('/medications') !== -1) return;

    $.getJSON(apiUrl + 'medication', { slug: getSlugFromUrl() })
        .done(function (response) {

            const medication = response.medication || {};
            const title = medication.title || medication.titleTag || 'Medication Details';

            document.title = title;

            $('#pageTitle').text(title);

            $('#blogImage')
                .attr('src', baseUrl + (medication.img || 'img/blog/default-blog.jpg'))
                .attr('alt', title);

            $('#blogDate').text(formatDate(medication.created_at));

            // Create temp container
            const content = $('<div>').html(medication.content || '');

            // Fix relative medication links
            content.find('a').each(function () {

                let href = $(this).attr('href');

                if (href && !href.startsWith('http') && !href.startsWith('#')) {

                    // remove duplicate slash
                    href = href.replace(/^\/+/, '');

                    $(this).attr('href', baseUrl + href);
                }
            });

            $('#blogContent').html(content.html());

            $('#blogTags').html(tagLinks(medication.tags));
        })
        .fail(function () {
            $('#pageTitle').text('Medication not found');
            $('#blogContent').html('<p>Unable to load this medication.</p>');
        });
}

    function bindContactForm() {
        const $form = $('#contactForm');
        if (!$form.length) return;

        $form.on('submit', function (event) {
            event.preventDefault();

            const $currentForm = $(this);
            const data = {
                name: $currentForm.find('[name="name"], #name').first().val(),
                email: $currentForm.find('[name="email"], #email').first().val(),
                phone: $currentForm.find('[name="phone"], #phone').first().val(),
                subject: $currentForm.find('[name="subject"], #subject').first().val(),
                message: $currentForm.find('[name="message"], #message').first().val()
            };

            let $status = $currentForm.find('.ajax-form-status');
            if (!$status.length) {
                $status = $('<div class="ajax-form-status mt-3"></div>').appendTo($currentForm);
            }

            $status.removeClass('text-danger text-success').text('Sending...');

            $.ajax({
                url: apiUrl + 'contacts',
                method: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(data)
            }).done(function () {
                $currentForm[0].reset();
                $status.addClass('text-success').text('Message sent successfully.');
            }).fail(function (xhr) {
                const response = xhr.responseJSON || {};
                $status.addClass('text-danger').text(response.message || 'Unable to send message.');
            });
        });
    }

    $(document).on('click', '[data-blog-page]', function (event) {
        event.preventDefault();
        loadBlogs(Number($(this).data('blog-page')) || 1);
    });

    $(document).on('click', '#categoryContainer [data-category-id]', function (event) {
        event.preventDefault();

        currentBlogCategory = Number($(this).data('category-id')) || 0;
        currentBlogCategorySlug = String($(this).data('category-slug') || '');
        $('#categoryContainer [data-category-id]').removeClass('active');
        $(this).addClass('active');

        const nextUrl = currentBlogCategorySlug
            ? baseUrl + 'blog/category/' + encodeURIComponent(currentBlogCategorySlug)
            : baseUrl + 'blog';

        window.history.pushState({}, '', nextUrl);
        loadBlogs(1);
    });

    $(document).on('click', '#alphabetContainer [data-letter]', function () {
        currentMedicationLetter = String($(this).data('letter') || '');
        $('#alphabetContainer [data-letter]').removeClass('active');
        $(this).addClass('active');
        $('#showMoreContainer').empty();
        loadMedications(1, false);
    });

    $(document).on('click', '#showMoreMedications', function () {
        loadMedications(currentMedicationPage + 1, true);
    });

    function renderHomeBlogCard(blog) {
        const title = escapeHtml(blog.blog_title || 'Untitled Blog');
        const slug = encodeURIComponent(blog.blogslug || '');
        const url = slug ? baseUrl + 'blog/' + slug : '#!';
        const image = baseUrl + escapeHtml(blog.img || 'img/blog/default-blog.jpg');
        const shortDescription = escapeHtml(blog.excerpt || 'Read this informative healthcare article on MedsFAQ.');

        return `
            <div class="col-md-6 col-lg-4 mt-1-9">
                <div class="card card-style h-100">
                    <div class="image-box image-hover">
                        <a href="${url}">
                            <img src="${image}" class="w-100" alt="${title}">
                        </a>
                    </div>
                    <div class="card-body">
                        <div class="mb-3 text-muted small">
                            ${formatDate(blog.created_at)}
                        </div>
                        <h4 class="mb-3">
                            <a href="${url}">${title}</a>
                        </h4>
                    </div>
                </div>
            </div>
        `;
    }

    function fetchHomeBlogs() {
        const $homeBlogList = $('#homeBlogList');
        if (!$homeBlogList.length) return;

        $.getJSON(apiUrl + 'blogs', { page: 1, limit: 3 })
            .done(function (response) {
                const blogs = response.blogs || [];

                $homeBlogList.html(
                    blogs.length
                        ? blogs.map(renderHomeBlogCard).join('')
                        : '<div class="col-12 text-center py-4"><h5>No blog posts found.</h5></div>'
                );
            })
            .fail(function () {
                $homeBlogList.html(
                    '<div class="col-12 text-center py-4"><h5>Failed to load articles. Please try again later.</h5></div>'
                );
            });
    }

    $(function () {
        fetchHomeBlogs();
        loadCategories();
        loadLatestPosts();
        if (!$('#categoryContainer').length) {
            currentBlogCategory = getCategoryIdFromQuery();
            loadBlogs(1);
        }
        renderAlphabet();
        loadMedications(1, false);
        loadBlogDetail();
        loadMedicationDetail();
        bindContactForm();
    });
})(jQuery);
