<?php
// view_post.php - SEO-Optimized & User-Focused Single Post Page
// Location: /blog/view_post.php

// FIX: Restored all original functionality and styling.
// NEW: Added styling for internal and custom link cards with colorful borders.

error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once __DIR__ . '/config.php';
require_once __DIR__ . '/../shortcode-processor.php';

// Admin Authentication Check - Only start session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

function isAdmin() {
    return isset($_SESSION['admin_id']) && $_SESSION['admin_id'] > 0;
}

// Get the slug from URL
$slug = $_GET['slug'] ?? '';
if (empty($slug)) {
    header('HTTP/1.0 404 Not Found');
    exit('Post not found. No slug provided.');
}

// Fetch post data with featured image
$stmt = $pdo->prepare("
    SELECT p.*, i.file_path as featured_image, i.alt_text as featured_alt_text, i.caption as featured_caption
    FROM posts p 
    LEFT JOIN images i ON p.featured_image_id = i.id 
    WHERE p.slug = ? AND (p.status = 'published' OR ? = 1)
");
$stmt->execute([$slug, isAdmin() ? 1 : 0]);
$post = $stmt->fetch();


if (!$post) {
    header('HTTP/1.0 404 Not Found');
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Page Not Found - MiscCalculators</title>
        <script src="https://cdn.tailwindcss.com"></script>
        <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" rel="stylesheet">
    </head>
    <body class="bg-gray-100 min-h-screen flex items-center justify-center">
        <div class="text-center p-8 max-w-md mx-auto">
            <div class="w-24 h-24 bg-red-100 text-red-500 rounded-full flex items-center justify-center mx-auto mb-6">
                <i class="fas fa-exclamation-triangle text-5xl"></i>
            </div>
            <h1 class="text-5xl font-black text-gray-800 mb-4">404</h1>
            <h2 class="text-2xl font-bold text-gray-700 mb-4">Article Not Found</h2>
            <p class="text-gray-600 mb-8">The financial article you are looking for might have been moved or does not exist.</p>
            <a href="/" class="bg-blue-600 text-white px-8 py-3 rounded-full font-bold hover:bg-blue-700 transition-all">
                <i class="fas fa-home mr-2"></i>Return to Homepage
            </a>
        </div>
    </body>
    </html>
    <?php
    exit;
}

// Store post ID and admin status for use in the page
$postId = $post['id'];
$userIsAdmin = isAdmin();

// Fetch categories for the post
$post_categories = [];
try {
    $categories_stmt = $pdo->prepare("
        SELECT c.name, c.slug 
        FROM categories c 
        JOIN post_categories pc ON c.id = pc.category_id 
        WHERE pc.post_id = ?
    ");
    $categories_stmt->execute([$post['id']]);
    $post_categories = $categories_stmt->fetchAll();
} catch (PDOException $e) {
    // Gracefully handle if tables don't exist
}

// Fetch tags for the post
$post_tags = [];
try {
    $tags_stmt = $pdo->prepare("
        SELECT t.name, t.slug 
        FROM tags t 
        JOIN post_tags pt ON t.id = pt.tag_id 
        WHERE pt.post_id = ?
    ");
    $tags_stmt->execute([$post['id']]);
    $post_tags = $tags_stmt->fetchAll();
} catch (PDOException $e) {
    // Gracefully handle if tables don't exist
}

// Fetch related posts
$related_posts = [];
if (!empty($post_categories)) {
    try {
        $first_category_id_stmt = $pdo->prepare("SELECT category_id FROM post_categories WHERE post_id = ? LIMIT 1");
        $first_category_id_stmt->execute([$post['id']]);
        $first_category_id = $first_category_id_stmt->fetchColumn();

        if ($first_category_id) {
            $related_stmt = $pdo->prepare("
                SELECT DISTINCT p.id, p.title, p.slug, p.excerpt, p.created_at, p.featured_image_id,
                       p.word_count, p.status,
                       i.file_path as featured_image, i.alt_text as featured_alt_text
                FROM posts p
                LEFT JOIN images i ON p.featured_image_id = i.id
                JOIN post_categories pc ON p.id = pc.post_id
                WHERE pc.category_id = ? 
                AND p.id != ? 
                AND p.status = 'published'
                ORDER BY p.created_at DESC 
                LIMIT 4
            ");
            $related_stmt->execute([$first_category_id, $post['id']]);
            $related_posts = $related_stmt->fetchAll();
        }
    } catch (PDOException $e) {
        // Gracefully handle errors
        error_log("Error fetching related posts: " . $e->getMessage());
    }
}


// Meta data and helper values
$page_title = html_entity_decode($post['meta_title'] ?: $post['title']) . ' - MiscCalculators';
$meta_description = $post['meta_description'] ?: ($post['excerpt'] ?? 'Read our latest financial guide on MiscCalculators');
$reading_time = ceil(($post['word_count'] ?? 500) / 200);

// Function to format date
function formatDate($date) {
    return date('F j, Y', strtotime($date));
}

// Function to get time ago
function timeAgo($date) {
    $timestamp = strtotime($date);
    $difference = time() - $timestamp;
    
    if ($difference < 3600) {
        $minutes = floor($difference / 60);
        return $minutes . ' minutes ago';
    } elseif ($difference < 86400) {
        $hours = floor($difference / 3600);
        return $hours . ' hours ago';
    } else {
        $days = floor($difference / 86400);
        return $days . ' days ago';
    }
}

// *** START: Load calculators from tools.json ***
$calculators = [];
$tools_file_path = __DIR__ . '/../tools.json'; // Assumes tools.json is in the parent public_html directory
if (file_exists($tools_file_path)) {
    $tools_json = file_get_contents($tools_file_path);
    $all_tools = json_decode($tools_json, true);
    if (is_array($all_tools)) {
        $calculators = array_filter($all_tools, function($tool) {
            return isset($tool['status']) && $tool['status'] === 'active';
        });
    }
}
// *** END: Load calculators ***


// Admin functions to render admin controls
function renderAdminControls($postId, $elementType, $elementId = '') {
    global $userIsAdmin;

    if (!$userIsAdmin) {
        return '';
    }

    $jsArg = is_numeric($elementId) ? $elementId : ("'" . addslashes($elementId) . "'");

    $controls = '';
    switch ($elementType) {
        case 'title':
            $controls = '
            <div class="admin-controls inline-flex bg-yellow-100 border border-yellow-300 rounded-lg px-2 py-1 ml-2 text-xs">
                <a href="/blog/edit_blog.php?id=' . $postId . '" class="text-blue-600 hover:text-blue-800 mr-2" title="Edit Title">
                    <i class="fas fa-edit"></i>
                </a>
                <a href="/blog/edit_blog.php?id=' . $postId . '" class="text-green-600 hover:text-green-800 mr-2" title="Edit Post">
                    <i class="fas fa-file-edit"></i>
                </a>
                <button onclick="changePostStatus(' . $postId . ')" class="text-purple-600 hover:text-purple-800 mr-2 bg-transparent border-0 cursor-pointer" title="Change Status">
                    <i class="fas fa-exchange-alt"></i>
                </button>
                <a href="/blog/admin.php" class="text-indigo-600 hover:text-indigo-800" title="Go to Admin">
                    <i class="fas fa-cog"></i>
                </a>
            </div>';
            break;

        case 'content':
            $controls = '
            <div class="admin-controls absolute top-2 right-2 bg-yellow-100 border border-yellow-300 rounded-lg px-2 py-1 text-xs opacity-0 group-hover:opacity-100 transition-opacity z-50">
                <a href="/blog/edit_blog.php?id=' . $postId . '" class="text-blue-600 hover:text-blue-800 mr-2" title="Edit Content">
                    <i class="fas fa-edit"></i>
                </a>
                <a href="/blog/edit_blog.php?id=' . $postId . '" class="text-green-600 hover:text-green-800 mr-2" title="Edit Post">
                    <i class="fas fa-file-edit"></i>
                </a>
                <a href="/blog/admin.php" class="text-purple-600 hover:text-purple-800" title="Go to Admin">
                    <i class="fas fa-cog"></i>
                </a>
            </div>';
            break;

        case 'image':
            $controls = '
            <div class="admin-controls absolute top-2 right-2 bg-yellow-100 border border-yellow-300 rounded-lg px-2 py-1 text-xs z-50">
                <a href="/blog/edit_blog.php?id=' . $postId . '" class="text-blue-600 hover:text-blue-800 mr-2" title="Edit Image">
                    <i class="fas fa-image"></i>
                </a>
                <a href="/blog/edit_blog.php?id=' . $postId . '" class="text-green-600 hover:text-green-800 mr-2" title="Edit Post">
                    <i class="fas fa-file-edit"></i>
                </a>
                <a href="/blog/admin.php" class="text-purple-600 hover:text-purple-800" title="Go to Admin">
                    <i class="fas fa-cog"></i>
                </a>
            </div>';
            break;

        case 'excerpt':
            $controls = '
            <div class="admin-controls absolute top-2 right-2 bg-yellow-100 border border-yellow-300 rounded-lg px-2 py-1 text-xs z-50">
                <a href="/blog/edit_blog.php?id=' . $postId . '" class="text-blue-600 hover:text-blue-800 mr-2" title="Edit Excerpt">
                    <i class="fas fa-edit"></i>
                </a>
                <a href="/blog/edit_blog.php?id=' . $postId . '" class="text-green-600 hover:text-green-800 mr-2" title="Edit Post">
                    <i class="fas fa-file-edit"></i>
                </a>
                <a href="/blog/admin.php" class="text-purple-600 hover:text-purple-800" title="Go to Admin">
                    <i class="fas fa-cog"></i>
                </a>
            </div>';
            break;

        case 'related_post':
            $controls = '
            <div class="admin-controls absolute top-2 right-2 bg-yellow-100 border border-yellow-300 rounded-lg px-3 py-2 text-xs z-50 opacity-0 group-hover:opacity-100 transition-opacity">
                <a href="/blog/edit_blog.php?id=' . htmlspecialchars($elementId, ENT_QUOTES) . '" class="text-blue-600 hover:text-blue-800 mr-3" title="Edit This Post">
                    <i class="fas fa-edit"></i> Edit
                </a>
                <a href="/blog/view_post.php?slug=' . htmlspecialchars($elementId, ENT_QUOTES) . '" class="text-green-600 hover:text-green-800 mr-3" title="View Post">
                    <i class="fas fa-eye"></i> View
                </a>
                <button onclick="changePostStatus(' . $jsArg . ')" class="text-purple-600 hover:text-purple-800 mr-3 bg-transparent border-0 cursor-pointer" title="Change Status">
                    <i class="fas fa-exchange-alt"></i> Status
                </button>
                <button onclick="quickDeletePost(' . $jsArg . ')" class="text-red-600 hover:text-red-800 bg-transparent border-0 cursor-pointer" title="Delete Post">
                    <i class="fas fa-trash"></i> Delete
                </button>
            </div>';
            break;

        default:
            $controls = '';
            break;
    }

    return $controls;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars($page_title) ?></title>
    <meta name="description" content="<?= htmlspecialchars($meta_description) ?>">
    
    <meta property="og:type" content="article">
    <meta property="og:url" content="<?= 'https://miscalculators.com/blog/' . htmlspecialchars($post['slug']) ?>">
    <meta property="og:title" content="<?= htmlspecialchars(html_entity_decode($post['title'])) ?>">
    <meta property="og:description" content="<?= htmlspecialchars($meta_description) ?>">
    <?php if (!empty($post['featured_image'])): ?>
    <meta property="og:image" content="<?= 'https://miscalculators.com/' . htmlspecialchars($post['featured_image']) ?>">
    <?php endif; ?>
    <meta property="og:site_name" content="MiscCalculators">
    <meta property="article:published_time" content="<?= date('c', strtotime($post['created_at'])) ?>">
    <meta property="article:author" content="MiscCalculators Team">
    
    <meta name="twitter:card" content="summary_large_image">
    <meta name="twitter:title" content="<?= htmlspecialchars(html_entity_decode($post['title'])) ?>">
    <meta name="twitter:description" content="<?= htmlspecialchars($meta_description) ?>">
    <?php if (!empty($post['featured_image'])): ?>
    <meta name="twitter:image" content="<?= 'https://miscalculators.com/' . htmlspecialchars($post['featured_image']) ?>">
    <?php endif; ?>
    
    <link rel="canonical" href="<?= 'https://miscalculators.com/blog/' . htmlspecialchars($post['slug']) ?>">
    
    
    
    <script type="application/ld+json">
    {
        "@context": "https://schema.org",
        "@type": "Article",
        "headline": "<?= htmlspecialchars(html_entity_decode($post['title'])) ?>",
        "description": "<?= htmlspecialchars($meta_description) ?>",
        <?php if (!empty($post['featured_image'])): ?>
        "image": "<?= 'https://miscalculators.com/' . htmlspecialchars($post['featured_image']) ?>",
        <?php endif; ?>
        "author": {
            "@type": "Organization",
            "name": "MiscCalculators Team"
        },
        "publisher": {
            "@type": "Organization",
            "name": "MiscCalculators",
            "logo": {
                "@type": "ImageObject",
                "url": "https://miscalculators.com/logo.png"
            }
        },
        "datePublished": "<?= date('c', strtotime($post['created_at'])) ?>",
        "dateModified": "<?= date('c', strtotime($post['updated_at'])) ?>",
        "mainEntityOfPage": {
            "@type": "WebPage",
            "@id": "<?= 'https://miscalculators.com/blog/' . htmlspecialchars($post['slug']) ?>"
        }
    }
    </script>
    
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" rel="stylesheet" integrity="sha512-Avb2QiuDEEvB4bZJYdft2mNjVShBftLdPG8FJ0V7irTLQ8Uo0qcPxh4Plq7G5tGm0rU+1SPhVotteLpBERwTkw==" crossorigin="anonymous">
    
    <style>
        .article-text-content .internal-link-card {
            display: flex !important;
            align-items: center !important;
            gap: 1rem !important;
            background-color: #f8fafc !important;
            padding: 1rem !important;
            border-radius: 0.75rem !important;
            text-decoration: none !important;
            margin: 1.5rem 0 !important;
            position: relative;
            overflow: hidden;
            transition: transform 0.2s ease, box-shadow 0.2s ease;
        }

        .article-text-content .internal-link-card::before {
            content: '';
            position: absolute;
            top: 0; right: 0; bottom: 0; left: 0;
            z-index: 0;
            border-radius: inherit;
            border: 2px solid transparent;
            background: linear-gradient(45deg, #3b82f6, #8b5cf6, #ec4899, #f97316) border-box;
            -webkit-mask:
                linear-gradient(#fff 0 0) padding-box, 
                linear-gradient(#fff 0 0);
            -webkit-mask-composite: xor;
            mask-composite: exclude;
            animation: rainbow-border-shift 5s ease-in-out infinite;
            background-size: 400% 400%;
        }

        .article-text-content .internal-link-card:hover {
            transform: translateY(-4px);
            box-shadow: 0 10px 20px rgba(0,0,0,0.08);
        }

        .article-text-content .internal-link-card img, .article-text-content .internal-link-card > div:first-child {
            width: 112px !important; /* w-28 */
            height: 80px !important; /* h-20 */
            object-fit: cover !important;
            border-radius: 0.5rem !important;
            flex-shrink: 0 !important;
            z-index: 1;
        }
        
        .article-text-content .internal-link-card > div:first-child {
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .article-text-content .internal-link-card .flex-grow {
            z-index: 1;
        }

        .article-text-content .internal-link-card h4 {
            font-weight: 700 !important;
            font-size: 1rem !important;
            margin: 0 !important;
            color: #1e293b !important;
            line-height: 1.25 !important;
        }

        .article-text-content .internal-link-card p {
            font-size: 0.875rem !important;
            color: #475569 !important;
            margin: 0.25rem 0 0 0 !important;
            line-height: 1.5 !important;
        }
        
        @keyframes rainbow-border-shift {
            0% { background-position: 0% 50%; }
            50% { background-position: 100% 50%; }
            100% { background-position: 0% 50%; }
        }

        html, body {
            overflow-x: hidden !important;
            width: 100% !important;
            max-width: 100vw !important;
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }
        
        *, *::before, *::after {
            box-sizing: border-box !important;
            max-width: 100% !important;
        }

        .main-container {
            width: 100% !important;
            max-width: 100vw !important;
            margin-left: auto;
            margin-right: auto;
            padding-left: 16px;
            padding-right: 16px;
            overflow-x: hidden;
        }
        
        @media (min-width: 640px) {
            .main-container {
                max-width: 640px !important;
            }
        }
        
        @media (min-width: 768px) {
            .main-container {
                max-width: 768px !important;
                padding-left: 20px;
                padding-right: 20px;
            }
        }
        
        @media (min-width: 1024px) {
            .main-container {
                max-width: 1024px !important;
                padding-left: 24px;
                padding-right: 24px;
            }
        }
        
        @media (min-width: 1280px) {
            .main-container {
                max-width: 1200px !important;
            }
        }
        
        @media (min-width: 1536px) {
            .main-container {
                max-width: 1300px !important;
            }
        }

        .admin-controls {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(5px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            z-index: 100;
        }
        
        .admin-edit-section {
            position: relative;
        }
        
        .admin-edit-section:hover .admin-controls {
            opacity: 1;
        }

        .content-section {
            position: relative;
        }
        
        .content-section:hover {
            background: rgba(255, 247, 237, 0.3);
            border-radius: 8px;
            transition: all 0.2s ease;
            outline: 2px dashed rgba(251, 191, 36, 0.3);
        }

        .sticky-header {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            z-index: 50;
            background: linear-gradient(135deg, #1e40af 0%, #3730a3 100%);
            color: white;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }

        .sticky-breadcrumb {
            position: fixed;
            top: 72px;
            left: 0;
            right: 0;
            z-index: 40;
            background: white;
            border-bottom: 1px solid #e5e7eb;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
            transform: translateY(-100%);
            transition: transform 0.3s ease;
        }
        
        .sticky-breadcrumb.visible {
            transform: translateY(0);
        }
        
        .sticky-progress-container {
            position: relative;
            overflow: hidden;
        }
        
        .sticky-progress-bar {
            position: absolute;
            bottom: 0;
            left: 0;
            height: 4px;
            background: linear-gradient(90deg, #ef4444, #f97316, #eab308, #22c55e, #06b6d4, #3b82f6, #8b5cf6);
            background-size: 700% 100%;
            animation: rainbow-shift 6s ease-in-out infinite;
            transition: width 0.05s linear;
            width: 0%;
            border-radius: 0 2px 2px 0;
        }

        .dynamic-progress-bar {
            position: relative;
            background: #e5e7eb;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.1);
        }
        
        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #ef4444, #f97316, #eab308, #22c55e, #06b6d4, #3b82f6, #8b5cf6);
            background-size: 700% 100%;
            animation: rainbow-shift 6s ease-in-out infinite;
            transition: width 0.05s linear;
            border-radius: 8px;
            position: relative;
            width: 0%;
        }
        
        .progress-fill::after {
            content: '';
            position: absolute;
            top: 0;
            right: 0;
            width: 8px;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.6));
            animation: shimmer 2s ease-in-out infinite;
        }
        
        .progress-text {
            background: linear-gradient(45deg, #ef4444, #f97316, #eab308, #22c55e, #06b6d4, #3b82f6, #8b5cf6);
            background-size: 400% 400%;
            -webkit-background-clip: text;
            background-clip: text;
            -webkit-text-fill-color: transparent;
            animation: gradient-text-shift 4s ease-in-out infinite;
            font-weight: 700;
            font-size: 1.1em;
        }
        
        .progress-percentage {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 4px 8px;
            background: rgba(255, 255, 255, 0.9);
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            border: 1px solid rgba(0, 0, 0, 0.05);
        }
        
        .progress-icon {
            background: linear-gradient(45deg, #ef4444, #f97316, #eab308, #22c55e, #06b6d4, #3b82f6, #8b5cf6);
            background-size: 400% 400%;
            -webkit-background-clip: text;
            background-clip: text;
            -webkit-text-fill-color: transparent;
            animation: gradient-text-shift 4s ease-in-out infinite;
        }

        @keyframes rainbow-shift {
            0% { background-position: 0% 50%; }
            25% { background-position: 25% 50%; }
            50% { background-position: 50% 50%; }
            75% { background-position: 75% 50%; }
            100% { background-position: 100% 50%; }
        }
        
        @keyframes gradient-text-shift {
            0% { background-position: 0% 50%; }
            50% { background-position: 100% 50%; }
            100% { background-position: 0% 50%; }
        }
        
        @keyframes shimmer {
            0% { opacity: 0; transform: translateX(-8px); }
            50% { opacity: 1; transform: translateX(0); }
            100% { opacity: 0; transform: translateX(8px); }
        }

        .active-toc-link {
            background: linear-gradient(135deg, #3b82f6, #1d4ed8) !important;
            color: white !important;
            font-weight: 600;
            border-radius: 8px;
            transform: translateX(4px);
            box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
        }
        
        .sidebar-sticky {
            position: -webkit-sticky;
            position: sticky;
            top: 140px;
            height: fit-content;
            max-height: calc(100vh - 160px);
            overflow-y: auto;
            z-index: 20;
            will-change: transform;
        }
        
        @media (min-width: 1024px) {
            .sidebar-sticky {
                position: -webkit-sticky !important;
                position: sticky !important;
                top: 140px !important;
            }
            
            .breadcrumb-visible .sidebar-sticky {
                top: 180px !important;
                max-height: calc(100vh - 200px) !important;
            }
            
            .sidebar-container {
                position: relative;
                height: fit-content;
            }
        }
        
        .article-wrapper {
            width: 100% !important;
            max-width: 100% !important;
            margin: 0;
            overflow-x: hidden !important;
        }
        
        .article-content-box {
            width: 100% !important;
            max-width: 100% !important;
            background: white;
            border-radius: 0;
            box-shadow: 0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1);
            overflow-x: hidden !important;
        }
        
        @media (min-width: 1024px) {
            .article-content-box {
                border-radius: 16px;
            }
        }
        
        .content-padding {
            padding: 12px;
            width: 100%;
            max-width: 100%;
        }
        
        @media (min-width: 768px) {
            .content-padding {
                padding: 20px;
            }
        }
        
        @media (min-width: 1024px) {
            .content-padding {
                padding: 24px;
            }
        }
        
        .featured-image-wrapper {
            width: 100% !important;
            max-width: 100% !important;
            height: 200px;
            position: relative;
            overflow: hidden !important;
            border-radius: 0;
        }
        
        @media (min-width: 640px) {
            .featured-image-wrapper {
                height: 250px;
            }
        }
        
        @media (min-width: 768px) {
            .featured-image-wrapper {
                height: 300px;
            }
        }
        
        @media (min-width: 1024px) {
            .featured-image-wrapper {
                height: 350px;
                border-radius: 16px 16px 0 0;
            }
        }
        
        .featured-image {
            width: 100% !important;
            height: 100% !important;
            max-width: 100% !important;
            object-fit: cover;
            object-position: center;
            display: block;
        }
        
        .image-overlay {
            position: absolute;
            inset: 0;
            background: linear-gradient(to top, rgba(0, 0, 0, 0.8) 0%, rgba(0, 0, 0, 0.4) 50%, transparent 100%);
        }
        
        .image-text-overlay {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            padding: 16px;
            color: white;
            max-width: 100%;
            word-wrap: break-word;
        }
        
        @media (min-width: 768px) {
            .image-text-overlay {
                padding: 20px;
            }
        }
        
        @media (min-width: 1024px) {
            .image-text-overlay {
                padding: 24px;
            }
        }

        .share-buttons-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 12px;
            width: 100%;
            max-width: 100%;
        }
        
        @media (min-width: 640px) {
            .share-buttons-grid {
                grid-template-columns: repeat(4, 1fr);
            }
        }
        
        .share-button {
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 12px 16px;
            border-radius: 8px;
            font-weight: 500;
            font-size: 14px;
            transition: all 0.2s ease;
            text-align: center;
            white-space: nowrap;
            min-height: 44px;
            cursor: pointer;
            border: none;
            max-width: 100%;
        }
        
        .floating-actions {
            position: fixed;
            right: 16px;
            bottom: 16px;
            z-index: 50;
            display: flex;
            flex-direction: column;
            gap: 12px;
        }
        
        .floating-btn {
            width: 56px;
            height: 56px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
            transition: all 0.3s ease;
            position: relative;
            cursor: pointer;
            border: none;
        }
        
        .floating-btn:hover {
            transform: scale(1.1);
            box-shadow: 0 8px 30px rgba(0, 0, 0, 0.2);
        }
        
        .floating-btn-label {
            position: absolute;
            right: 70px;
            background: rgba(0, 0, 0, 0.85);
            color: white;
            padding: 8px 14px;
            border-radius: 8px;
            font-size: 13px;
            font-weight: 600;
            white-space: nowrap;
            opacity: 0;
            visibility: hidden;
            transition: all 0.3s ease;
            pointer-events: none;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
        }
        
        .floating-btn:hover .floating-btn-label {
            opacity: 1;
            visibility: visible;
            right: 68px;
        }
        
        .quick-jump-menu {
            position: fixed;
            right: 16px;
            bottom: 95px;
            background: white;
            border-radius: 16px;
            box-shadow: 0 12px 50px rgba(0, 0, 0, 0.2);
            border: 1px solid #e5e7eb;
            z-index: 55;
            opacity: 0;
            visibility: hidden;
            transform: translateY(15px) scale(0.95);
            transition: all 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55);
            min-width: 280px;
            max-width: 340px;
            max-height: 550px;
            overflow-y: auto;
        }
        
        .quick-jump-menu.show {
            opacity: 1;
            visibility: visible;
            transform: translateY(0) scale(1);
        }
        
        .quick-jump-menu-header {
            padding: 18px 20px;
            border-bottom: 2px solid #e5e7eb;
            background: linear-gradient(135deg, #f8fafc, #eff6ff);
            border-radius: 16px 16px 0 0;
            font-weight: 700;
            font-size: 16px;
            color: #1e293b;
            display: flex;
            align-items: center;
            justify-content: space-between;
            position: sticky;
            top: 0;
            z-index: 10;
        }
        
        .quick-jump-menu-item {
            display: flex;
            align-items: center;
            padding: 16px 20px;
            color: #374151;
            text-decoration: none;
            border-bottom: 1px solid #f3f4f6;
            transition: all 0.25s ease;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            user-select: none;
        }
        
        .quick-jump-menu-item:hover {
            background: linear-gradient(135deg, #eff6ff, #dbeafe);
            color: #2563eb;
            padding-left: 28px;
            border-left: 4px solid #3b82f6;
        }
        
        .quick-jump-menu-item:last-child {
            border-bottom: none;
            border-radius: 0 0 16px 16px;
        }
        
        .quick-jump-menu-item i {
            width: 24px;
            margin-right: 14px;
            text-align: center;
            font-size: 15px;
        }
        
        <?php if ($userIsAdmin): ?>
        .admin-menu-divider {
            margin: 8px 0;
            border-top: 2px solid #fbbf24;
            background: linear-gradient(90deg, transparent, #fbbf24, transparent);
            height: 2px;
        }
        
        .admin-section-header {
            padding: 12px 20px;
            background: linear-gradient(135deg, #fef3c7, #fde68a);
            font-weight: 700;
            font-size: 13px;
            color: #92400e;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            border-left: 4px solid #f59e0b;
        }
        
        .admin-menu-item {
            background: linear-gradient(135deg, #fffbeb 0%, #fef3c7 100%);
            border-left: 4px solid #f59e0b;
            font-weight: 600;
            color: #92400e;
        }
        
        .admin-menu-item:hover {
            background: linear-gradient(135deg, #fde68a, #fcd34d);
            color: #78350f;
            transform: translateX(6px);
            box-shadow: 0 4px 12px rgba(245, 158, 11, 0.3);
        }
        
        .admin-menu-item i {
            color: #f59e0b;
        }
        <?php endif; ?>
        
        .mobile-menu {
            position: fixed;
            top: 0;
            left: -100%;
            width: 280px;
            height: 100vh;
            background: linear-gradient(135deg, #1e40af 0%, #3730a3 100%);
            z-index: 60;
            transition: left 0.3s ease;
            overflow-y: auto;
        }
        
        .mobile-menu.active {
            left: 0;
        }
        
        .mobile-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 55;
            display: none;
        }
        
        .mobile-overlay.active {
            display: block;
        }

        .article-text-content {
            word-wrap: break-word !important;
            overflow-wrap: break-word !important;
            width: 100% !important;
            max-width: 100% !important;
            overflow-x: hidden !important;
        }
        
        .article-text-content h1,
        .article-text-content h2, 
        .article-text-content h3, 
        .article-text-content h4,
        .article-text-content h5,
        .article-text-content h6 {
            scroll-margin-top: 180px;
            position: relative;
            color: #2c3e50;
            font-weight: 700;
            margin-top: 1px;
            margin-bottom: 1px;
            word-wrap: break-word !important;
            overflow-wrap: break-word !important;
            max-width: 100% !important;
        }

        .article-text-content h2 {
            font-size: clamp(20px, 4vw, 28px);
            line-height: 1.2;
        }
        
        .article-text-content h3 {
            font-size: clamp(18px, 3.5vw, 22px);
            line-height: 1.3;
        }
        
        .article-text-content h4 {
            font-size: clamp(16px, 3vw, 18px);
            line-height: 1.4;
        }
        
        .article-text-content p {
            line-height: 1.8;
            margin-bottom: 24px;
            color: #374151;
            word-wrap: break-word !important;
            overflow-wrap: break-word !important;
            font-size: 16px;
            max-width: 100% !important;
        }
        
        .article-text-content ul, 
        .article-text-content ol {
            margin: 24px 0;
            padding-left: 24px;
            max-width: 100% !important;
            overflow-x: hidden !important;
        }
        
        .article-text-content li {
            margin-bottom: 8px;
            line-height: 1.7;
            word-wrap: break-word !important;
            overflow-wrap: break-word !important;
            max-width: 100% !important;
        }
        
        .article-text-content blockquote {
            border-left: 4px solid #3b82f6;
            padding: 16px 20px;
            margin: 32px 0;
            background: #f8fafc;
            border-radius: 0 8px 8px 0;
            font-style: italic;
            word-wrap: break-word !important;
            overflow-wrap: break-word !important;
            max-width: 100% !important;
        }
        
        .article-text-content table {
            width: 100% !important;
            max-width: 100% !important;
            border-collapse: collapse;
            margin: 24px 0;
            background: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            font-size: 14px;
            table-layout: fixed !important;
        }
        
        .table-wrapper {
            width: 100% !important;
            max-width: 100% !important;
            overflow-x: auto !important;
            margin: 24px 0;
            border-radius: 8px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        
        .table-wrapper table {
            width: 100% !important;
            min-width: 400px !important;
            margin: 0 !important;
            border-radius: 0 !important;
            box-shadow: none !important;
        }
        
        .article-text-content table th {
            background: linear-gradient(135deg, #3b82f6, #1d4ed8);
            color: white;
            padding: 12px 8px;
            text-align: left;
            font-weight: 600;
            font-size: 12px;
            word-wrap: break-word !important;
            overflow-wrap: break-word !important;
            max-width: none !important;
        }
        
        .article-text-content table td {
            padding: 10px 8px;
            border-bottom: 1px solid #e5e7eb;
            word-wrap: break-word !important;
            overflow-wrap: break-word !important;
            max-width: none !important;
            font-size: 12px;
        }
        
        .article-text-content table tbody tr:hover {
            background: #f9fafb;
        }
        
        .article-text-content img {
            max-width: 100% !important;
            width: auto !important;
            height: auto !important;
            border-radius: 8px;
            margin: 24px 0;
            display: block;
        }
        
        .news-ticker {
            background: #f8f9fa;
            border-left: 4px solid #007bff;
        }

        .toc-link {
            display: block;
            padding: 12px 16px;
            text-decoration: none;
            border-radius: 8px;
            transition: all 0.2s ease;
            cursor: pointer;
            user-select: none;
            -webkit-tap-highlight-color: rgba(0, 0, 0, 0.1);
            border: 1px solid transparent;
            max-width: 100%;
            word-wrap: break-word;
        }
        
        .toc-link:hover,
        .toc-link:focus,
        .toc-link:active {
            background: #f0f9ff;
            color: #3b82f6;
            border-color: #93c5fd;
        }
        
        .mobile-toc-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            z-index: 60;
            display: none;
        }
        
        .mobile-toc-overlay.show {
            display: block;
        }
        
        .mobile-toc-panel {
            position: fixed;
            top: 0;
            right: -100%;
            width: 320px;
            height: 100vh;
            background: white;
            z-index: 65;
            transition: right 0.3s ease;
            overflow-y: auto;
            box-shadow: -4px 0 20px rgba(0, 0, 0, 0.15);
        }
        
        .mobile-toc-panel.show {
            right: 0;
        }

        @media (max-width: 768px) {
            .main-container {
                padding-left: 10px !important;
                padding-right: 10px !important;
            }
            
            .content-padding {
                padding: 10px !important;
            }
            
            .sidebar-sticky {
                position: relative !important;
                top: 0 !important;
                max-height: none;
                height: auto;
            }
            
            .share-buttons-grid {
                grid-template-columns: repeat(2, 1fr);
                gap: 8px;
            }
            
            .floating-actions {
                right: 10px;
                bottom: 10px;
                gap: 8px;
            }
            
            .floating-btn {
                width: 50px;
                height: 50px;
            }
            
            .quick-jump-menu {
                right: 10px;
                bottom: 75px;
                min-width: 250px;
                max-width: 300px;
            }
            
            .article-text-content table th,
            .article-text-content table td {
                padding: 6px 4px !important;
                font-size: 11px !important;
            }
            
            .table-wrapper table {
                min-width: 320px !important;
            }
            
            .toc-link {
                padding: 14px 16px;
                font-size: 15px;
                min-height: 44px;
                display: flex;
                align-items: center;
            }
            
            .featured-image-wrapper {
                border-radius: 0 !important;
            }
            
            .article-content-box {
                border-radius: 0 !important;
            }
            
            .desktop-nav {
                display: none;
            }
            
            .mobile-menu-btn {
                display: flex;
            }
        }
        
        @media (min-width: 769px) {
            .desktop-nav {
                display: flex;
            }
            
            .mobile-menu-btn {
                display: none;
            }
        }

        .sidebar-sticky::-webkit-scrollbar,
        .quick-jump-menu::-webkit-scrollbar,
        .mobile-toc-panel::-webkit-scrollbar,
        .table-wrapper::-webkit-scrollbar {
            width: 6px;
            height: 6px;
        }
        
        .sidebar-sticky::-webkit-scrollbar-track,
        .quick-jump-menu::-webkit-scrollbar-track,
        .mobile-toc-panel::-webkit-scrollbar-track,
        .table-wrapper::-webkit-scrollbar-track {
            background: #f1f5f9;
            border-radius: 10px;
        }
        
        .sidebar-sticky::-webkit-scrollbar-thumb,
        .quick-jump-menu::-webkit-scrollbar-thumb,
        .mobile-toc-panel::-webkit-scrollbar-thumb,
        .table-wrapper::-webkit-scrollbar-thumb {
            background: #cbd5e1;
            border-radius: 10px;
        }
        
        .sidebar-sticky::-webkit-scrollbar-thumb:hover,
        .quick-jump-menu::-webkit-scrollbar-thumb:hover,
        .mobile-toc-panel::-webkit-scrollbar-thumb:hover,
        .table-wrapper::-webkit-scrollbar-thumb:hover {
            background: #94a3b8;
        }
        
        html {
            scroll-behavior: smooth;
        }
        
        .page-wrapper {
            width: 100% !important;
            max-width: 100vw !important;
            overflow-x: hidden !important;
            min-height: 100vh;
        }
        
        .grid-container {
            width: 100% !important;
            max-width: 100% !important;
            overflow-x: hidden !important;
        }
        
        @media (min-width: 1024px) {
            .grid-container {
                display: grid;
                grid-template-columns: 2fr 1fr;
                gap: 2rem;
            }
        }

        /* Enhanced Related Posts Cards */
        .related-post-card {
            position: relative;
            transition: all 0.3s ease;
        }

        .related-post-card:hover {
            transform: translateY(-4px);
            box-shadow: 0 12px 24px rgba(0, 0, 0, 0.15);
        }

        .group:hover .admin-controls {
            opacity: 1 !important;
        }


        
        .dropdown {
            position: relative;
            display: inline-block;
        }
        .dropdown > button {
            background: none;
            border: none;
            color: white;
            cursor: pointer;
            font: inherit;
        }

        .dropdown-content {
            display: none;
            position: fixed;
            top: 0; left: 0;
            min-width: 200px;
            max-width: calc(100vw - 20px);
            box-shadow: 0px 10px 30px rgba(0,0,0,0.25);
            z-index: 99999;
            border-radius: 0.5rem;
            max-height: 400px;
            overflow-y: auto;
            border: 1px solid #e5e7eb;
            background-color: #ffffff;
            transform-origin: top left;
            transition: opacity 0.12s ease, transform 0.12s ease;
            opacity: 0;
            pointer-events: none;
        }

        .dropdown-content.show {
            display: block;
            opacity: 1;
            pointer-events: auto;
            transform: translateY(0);
        }

        .dropdown-content[data-placement="bottom"] { transform: translateY(4px); }
        .dropdown-content[data-placement="top"]   { transform: translateY(-4px); }

        .dropdown-content a {
            color: black;
            padding: 12px 16px;
            text-decoration: none;
            display: block;
            font-size: 0.95rem;
            white-space: nowrap;
        }

        .dropdown-content a:hover {
            background-color: #f3f4f6;
        }
    </style>
</head>

</body>
</html>

<body class="bg-gray-50 font-sans page-wrapper">
    <div class="mobile-overlay" id="mobileOverlay" onclick="closeMobileMenu()"></div>
    
    <?php if ($userIsAdmin): ?>
    <div class="bg-gradient-to-r from-yellow-400 via-orange-400 to-amber-500 text-yellow-900 px-4 py-3 text-center text-sm font-medium shadow-lg border-b-2 border-yellow-600" style="margin-top: 72px;">
        <div class="flex items-center justify-center mb-2">
            <div class="flex items-center bg-yellow-900 text-yellow-100 px-3 py-1 rounded-full">
                <i class="fas fa-shield-alt mr-2 text-base"></i>
                <strong class="text-sm uppercase tracking-wide">Administrator Mode</strong>
            </div>
        </div>
        <div class="flex justify-center gap-2 flex-wrap mt-2">
            <a href="/blog/edit_blog.php?id=<?= $postId ?>" class="inline-flex items-center px-4 py-1.5 bg-white bg-opacity-95 rounded-full text-xs hover:bg-yellow-50 hover:scale-105 transition-all shadow-md font-semibold border border-yellow-200">
                <i class="fas fa-edit mr-1.5 text-blue-600"></i>Edit This Post
            </a>
            <a href="/blog/admin.php" class="inline-flex items-center px-4 py-1.5 bg-white bg-opacity-95 rounded-full text-xs hover:bg-yellow-50 hover:scale-105 transition-all shadow-md font-semibold border border-yellow-200">
                <i class="fas fa-plus-circle mr-1.5 text-green-600"></i>Create New Post
            </a>
            <a href="/blog/admin.php" class="inline-flex items-center px-4 py-1.5 bg-white bg-opacity-95 rounded-full text-xs hover:bg-yellow-50 hover:scale-105 transition-all shadow-md font-semibold border border-yellow-200">
                <i class="fas fa-tachometer-alt mr-1.5 text-purple-600"></i>Dashboard
            </a>
            <a href="/blog/admin.php" class="inline-flex items-center px-4 py-1.5 bg-white bg-opacity-95 rounded-full text-xs hover:bg-yellow-50 hover:scale-105 transition-all shadow-md font-semibold border border-yellow-200">
                <i class="fas fa-file-alt mr-1.5 text-indigo-600"></i>All Posts
            </a>
            <a href="/blog/admin.php" class="inline-flex items-center px-4 py-1.5 bg-white bg-opacity-95 rounded-full text-xs hover:bg-yellow-50 hover:scale-105 transition-all shadow-md font-semibold border border-yellow-200">
                <i class="fas fa-images mr-1.5 text-pink-600"></i>Media Library
            </a>
        </div>
    </div>
    <?php endif; ?>
    
    <div class="mobile-menu" id="mobileMenu">
        <div class="p-6">
            <div class="flex items-center justify-between mb-8">
                <div class="flex items-center space-x-3">
                    <div class="w-10 h-10 bg-white bg-opacity-20 rounded-lg flex items-center justify-center">
                        <i class="fas fa-calculator text-xl text-white"></i>
                    </div>
                    <span class="text-xl font-bold text-white">MiscCalculators</span>
                </div>
                <button onclick="closeMobileMenu()" class="text-white text-xl">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            
            <nav class="space-y-4">
                <a href="/" class="flex items-center space-x-3 text-white hover:bg-white hover:bg-opacity-10 p-3 rounded-lg transition-colors">
                    <i class="fas fa-home"></i>
                    <span>Home</span>
                </a>
                <a href="/blog" class="flex items-center space-x-3 text-white hover:bg-white hover:bg-opacity-10 p-3 rounded-lg transition-colors">
                    <i class="fas fa-newspaper"></i>
                    <span>Blog</span>
                </a>
                <a href="/calculators" class="flex items-center space-x-3 text-white hover:bg-white hover:bg-opacity-10 p-3 rounded-lg transition-colors">
                    <i class="fas fa-calculator"></i>
                    <span>Calculators</span>
                </a>
                <a href="/tools" class="flex items-center space-x-3 text-white hover:bg-white hover:bg-opacity-10 p-3 rounded-lg transition-colors">
                    <i class="fas fa-tools"></i>
                    <span>Tools</span>
                </a>
                <div class="border-t border-white border-opacity-20 pt-4">
                    <a href="/about" class="flex items-center space-x-3 text-white hover:bg-white hover:bg-opacity-10 p-3 rounded-lg transition-colors">
                        <i class="fas fa-info-circle"></i>
                        <span>About</span>
                    </a>
                    <a href="/contact" class="flex items-center space-x-3 text-white hover:bg-white hover:bg-opacity-10 p-3 rounded-lg transition-colors">
                        <i class="fas fa-envelope"></i>
                        <span>Contact</span>
                    </a>
                </div>
                <?php if ($userIsAdmin): ?>
                <div class="border-t border-yellow-400 border-opacity-40 pt-4">
                    <a href="/blog/admin.php" class="flex items-center space-x-3 text-yellow-300 hover:bg-yellow-400 hover:bg-opacity-10 p-3 rounded-lg transition-colors font-semibold">
                        <i class="fas fa-shield-alt"></i>
                        <span>Admin Panel</span>
                    </a>
                    <a href="/blog/admin.php" class="flex items-center space-x-3 text-yellow-300 hover:bg-yellow-400 hover:bg-opacity-10 p-3 rounded-lg transition-colors font-semibold">
                        <i class="fas fa-plus"></i>
                        <span>Create Post</span>
                    </a>
                    <a href="/blog/edit_blog.php?id=<?= $postId ?>" class="flex items-center space-x-3 text-yellow-300 hover:bg-yellow-400 hover:bg-opacity-10 p-3 rounded-lg transition-colors font-semibold">
                        <i class="fas fa-edit"></i>
                        <span>Edit This Post</span>
                    </a>
                </div>
                <?php endif; ?>
            </nav>
        </div>
    </div>

    <header class="sticky-header">
        <div class="main-container py-4">
            <div class="flex items-center justify-between">
                <div class="flex items-center space-x-4">
                    <a href="/" class="flex items-center space-x-3">
                        <div class="w-10 h-10 bg-white bg-opacity-20 rounded-lg flex items-center justify-center">
                            <i class="fas fa-calculator text-xl"></i>
                        </div>
                        <span class="text-xl font-bold">MiscCalculators</span>
                    </a>
                </div>
                
                <nav class="desktop-nav hidden md:flex space-x-6">
                    <a href="/" class="hover:text-blue-200 transition-colors">
                        <i class="fas fa-home mr-1"></i>Home
                    </a>
                    <a href="/blog" class="hover:text-blue-200 transition-colors">
                        <i class="fas fa-newspaper mr-1"></i>Blog
                    </a>
                    
                    <div class="dropdown">
                        <button id="calculatorsDropdownBtn" type="button" class="hover:text-blue-200 transition-colors">
                            <i class="fas fa-calculator mr-1"></i>Calculators <i class="fas fa-caret-down text-xs ml-1"></i>
                        </button>
                        <div id="calculatorsDropdownContent" class="dropdown-content">
                            <?php if (!empty($calculators)): ?>
                                <?php foreach ($calculators as $calculator): ?>
                                    <a href="/<?= htmlspecialchars($calculator['url']) ?>"><?= htmlspecialchars($calculator['name']) ?></a>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <a href="#" class="text-gray-500">No calculators found</a>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <?php if ($userIsAdmin): ?>
                    <a href="/blog/admin.php" class="bg-yellow-400 text-yellow-900 px-3 py-1 rounded-full text-sm hover:bg-yellow-300 transition-colors font-semibold shadow-md">
                        <i class="fas fa-shield-alt mr-1"></i>Admin
                    </a>
                    <?php endif; ?>
                </nav>
                
                <button class="mobile-menu-btn md:hidden text-white" onclick="openMobileMenu()">
                    <i class="fas fa-bars text-xl"></i>
                </button>
            </div>
        </div>
    </header>

    <div class="py-2" style="margin-top: <?= $userIsAdmin ? '155px' : '72px' ?>;">
        <div class="main-container">
            </div>
    </div>

    <nav class="bg-white shadow-sm border-b py-3" id="staticBreadcrumb">
        <div class="main-container">
            <ol class="flex items-center space-x-2 text-sm text-gray-600 overflow-x-auto">
                <li class="whitespace-nowrap"><a href="/" class="hover:text-blue-600">
                    <i class="fas fa-home mr-1"></i>Home
                </a></li>
                <li class="whitespace-nowrap"><i class="fas fa-chevron-right text-xs text-gray-400 mx-2"></i></li>
                <li class="whitespace-nowrap"><a href="/blog" class="hover:text-blue-600">Blog</a></li>
                <li class="whitespace-nowrap"><i class="fas fa-chevron-right text-xs text-gray-400 mx-2"></i></li>
                <?php if (!empty($post_categories)): ?>
                <li class="whitespace-nowrap"><a href="#" class="hover:text-blue-600"><?= htmlspecialchars($post_categories[0]['name']) ?></a></li>
                <li class="whitespace-nowrap"><i class="fas fa-chevron-right text-xs text-gray-400 mx-2"></i></li>
                <?php endif; ?>
                <li class="text-gray-900 font-medium truncate max-w-xs"><?= html_entity_decode($post['title']) ?></li>
            </ol>
        </div>
    </nav>

    <div class="sticky-breadcrumb" id="stickyBreadcrumb">
        <div class="sticky-progress-container">
            <div class="main-container py-2">
                <div class="flex items-center justify-between">
                    <ol class="flex items-center space-x-2 text-sm text-gray-600 overflow-x-auto">
                        <li class="whitespace-nowrap"><a href="/" class="hover:text-blue-600">
                            <i class="fas fa-home mr-1"></i>Home
                        </a></li>
                        <li class="whitespace-nowrap"><i class="fas fa-chevron-right text-xs text-gray-400 mx-2"></i></li>
                        <li class="whitespace-nowrap"><a href="/blog" class="hover:text-blue-600">Blog</a></li>
                        <li class="whitespace-nowrap"><i class="fas fa-chevron-right text-xs text-gray-400 mx-2"></i></li>
                        <li class="text-gray-900 font-medium truncate max-w-xs"><?= html_entity_decode($post['title']) ?></li>
                    </ol>
                    <div class="flex items-center space-x-4 text-sm">
                        <div class="progress-percentage">
                            <i class="fas fa-chart-line progress-icon"></i>
                            <span class="progress-text" id="sticky-progress-text">0%</span>
                        </div>
                        <div class="text-gray-600"><?= $reading_time ?> min</div>
                    </div>
                </div>
            </div>
            <div class="sticky-progress-bar" id="stickyProgressBar"></div>
        </div>
    </div>

    <div class="mobile-toc-overlay" id="mobileTocOverlay" onclick="closeMobileToc()"></div>
    
    <div class="mobile-toc-panel" id="mobileTocPanel">
        <div class="p-6">
            <div class="flex items-center justify-between mb-6">
                <h3 class="text-lg font-bold text-gray-800">Table of Contents</h3>
                <button onclick="closeMobileToc()" class="text-gray-500 hover:text-gray-700">
                    <i class="fas fa-times text-xl"></i>
                </button>
            </div>
            <nav id="mobile-toc-nav" class="space-y-1"></nav>
        </div>
    </div>

    <div class="main-container py-6">
        <div class="grid-container">
            
            <main class="article-wrapper">
                <article class="article-content-box">
                    
                    <header class="relative <?= $userIsAdmin ? 'admin-edit-section content-section group' : '' ?>" data-admin-element="header">
                        <?php if ($post['featured_image']): ?>
                        <div class="featured-image-wrapper">
                            <img src="<?= htmlspecialchars($post['featured_image']) ?>" 
                                 alt="<?= htmlspecialchars($post['featured_alt_text'] ?? $post['title']) ?>"
                                 class="featured-image"
                                 loading="lazy">
                            <div class="image-overlay"></div>
                            <?= renderAdminControls($postId, 'image') ?>
                            
                            <div class="image-text-overlay">
                                <?php if (!empty($post_categories)): ?>
                                <div class="flex flex-wrap items-center gap-3 mb-4">
                                    <span class="bg-blue-500 text-white px-3 py-1 rounded-full text-sm font-bold">
                                        <i class="fas fa-tag mr-1"></i><?= htmlspecialchars($post_categories[0]['name']) ?>
                                    </span>
                                    <span class="bg-white bg-opacity-20 backdrop-blur-sm px-3 py-1 rounded-full text-sm">
                                        <i class="fas fa-clock mr-1"></i><?= $reading_time ?> min read
                                    </span>
                                </div>
                                <?php endif; ?>
                                <h1 class="text-lg md:text-xl lg:text-2xl xl:text-3xl font-bold mb-4 leading-tight <?= $userIsAdmin ? 'admin-edit-section' : '' ?>" data-admin-element="title">
                                    <?= html_entity_decode($post['title']) ?>
                                    <?= renderAdminControls($postId, 'title') ?>
                                </h1>
                                <div class="flex flex-wrap items-center gap-4 text-white/90 text-sm">
                                    <span><i class="fas fa-calendar-alt mr-2"></i><?= formatDate($post['created_at']) ?></span>
                                </div>
                            </div>
                        </div>
                        <?php else: ?>
                        <div class="bg-gradient-to-r from-blue-600 to-purple-600 text-white content-padding">
                            <?php if (!empty($post_categories)): ?>
                            <div class="flex flex-wrap items-center gap-3 mb-4">
                                <span class="bg-yellow-400 text-black px-3 py-1 rounded-full text-sm font-bold">
                                    <i class="fas fa-tag mr-1"></i><?= htmlspecialchars($post_categories[0]['name']) ?>
                                </span>
                                <span class="bg-white bg-opacity-20 backdrop-blur-sm px-3 py-1 rounded-full text-sm">
                                    <i class="fas fa-clock mr-1"></i><?= $reading_time ?> min read
                                </span>
                            </div>
                            <?php endif; ?>
                            <h1 class="text-lg md:text-xl lg:text-2xl xl:text-3xl font-bold mb-4 leading-tight <?= $userIsAdmin ? 'admin-edit-section' : '' ?>" data-admin-element="title">
                                <?= html_entity_decode($post['title']) ?>
                                <?= renderAdminControls($postId, 'title') ?>
                            </h1>
                            <div class="flex flex-wrap items-center gap-4 text-white/90 text-sm">
                                <span><i class="fas fa-calendar-alt mr-2"></i><?= formatDate($post['created_at']) ?></span>
                            </div>
                        </div>
                        <?php endif; ?>
                    </header>
                    
                    <div class="content-padding">
                        
                        <div id="key-highlights" class="bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-200 rounded-xl p-4 md:p-6 mb-8 <?= $userIsAdmin ? 'admin-edit-section content-section group' : '' ?> relative" data-admin-element="highlights">
                            <?= renderAdminControls($postId, 'content', 'highlights') ?>
                            <h3 class="flex items-center text-lg md:text-xl font-bold text-blue-900 mb-4">
                                <div class="w-8 h-8 md:w-10 md:h-10 bg-gradient-to-r from-blue-500 to-blue-600 rounded-lg flex items-center justify-center mr-3">
                                    <i class="fas fa-lightbulb text-white text-sm md:text-base"></i>
                                </div>
                                <i class="fas fa-star mr-2"></i>Key Financial Highlights
                            </h3>
                            <div class="grid md:grid-cols-2 gap-4">
                                <div class="flex items-start p-3 bg-white/60 rounded-lg border border-blue-100">
                                    <i class="fas fa-check-circle text-green-500 mr-3 mt-1 flex-shrink-0"></i>
                                    <span class="text-gray-700 text-sm">Essential calculations and formulas</span>
                                </div>
                                <div class="flex items-start p-3 bg-white/60 rounded-lg border border-blue-100">
                                    <i class="fas fa-check-circle text-green-500 mr-3 mt-1 flex-shrink-0"></i>
                                    <span class="text-gray-700 text-sm">Tax benefits and eligibility criteria</span>
                                </div>
                                <div class="flex items-start p-3 bg-white/60 rounded-lg border border-blue-100">
                                    <i class="fas fa-check-circle text-green-500 mr-3 mt-1 flex-shrink-0"></i>
                                    <span class="text-gray-700 text-sm">Investment strategies explained</span>
                                </div>
                                <div class="flex items-start p-3 bg-white/60 rounded-lg border border-blue-100">
                                    <i class="fas fa-check-circle text-green-500 mr-3 mt-1 flex-shrink-0"></i>
                                    <span class="text-gray-700 text-sm">Money-saving opportunities</span>
                                </div>
                            </div>
                        </div>

                        <?php if (!empty($post['excerpt'])): ?>
                        <div id="article-summary" class="text-lg text-gray-700 font-medium leading-relaxed mb-8 p-4 md:p-6 bg-gray-50 rounded-xl border-l-4 border-blue-400 <?= $userIsAdmin ? 'admin-edit-section content-section group' : '' ?> relative" data-admin-element="excerpt">
                            <?= renderAdminControls($postId, 'excerpt') ?>
                            <i class="fas fa-quote-left text-blue-500 mr-2"></i>
                            <?= htmlspecialchars($post['excerpt']) ?>
                        </div>
                        <?php endif; ?>
                        
                        <div id="article-content" class="article-text-content <?= $userIsAdmin ? 'admin-edit-section content-section group' : '' ?> relative" data-admin-element="content">
                            <?= renderAdminControls($postId, 'content', 'main-content') ?>
                            <?= $post['ai_generated_content_html'] ?>
                        </div>
                    </div>
                    
                    <footer class="content-padding bg-gray-50 border-t">
                        <div id="author-info" class="bg-white rounded-xl p-4 md:p-6 shadow-md mb-8">
                            <div class="flex flex-col md:flex-row items-start md:items-center space-y-4 md:space-y-0 md:space-x-4">
                                <div class="w-16 h-16 bg-gradient-to-r from-blue-500 to-purple-600 rounded-full flex items-center justify-center text-white text-2xl font-bold flex-shrink-0">
                                    <i class="fas fa-user-tie"></i>
                                </div>
                                <div class="flex-1">
                                    <h4 class="font-bold text-gray-900 text-xl mb-2">
                                        <i class="fas fa-pen-fancy mr-2"></i>MiscCalculators Team
                                    </h4>
                                    <p class="text-gray-600 leading-relaxed text-sm md:text-base">Our financial experts and analysts provide accurate, up-to-date information to help you make informed financial decisions.</p>
                                    
                                </div>
                            </div>
                        </div>

                        <?php if (!empty($post_tags)): ?>
                        <div id="tags-topics" class="mb-8">
                            <h4 class="font-bold text-gray-800 mb-4 text-lg">
                                <i class="fas fa-tags mr-2 text-blue-500"></i>Related Topics
                            </h4>
                            <div class="flex flex-wrap gap-3">
                                <?php foreach ($post_tags as $tag): ?>
                                <a href="#" class="inline-flex items-center px-3 py-2 bg-gray-200 text-gray-700 rounded-full text-sm font-medium hover:bg-blue-100 hover:text-blue-700 transition-colors">
                                    <i class="fas fa-hashtag mr-1 text-xs"></i><?= htmlspecialchars($tag['name']) ?>
                                </a>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        <?php endif; ?>

                        <div id="share-article" class="border-t pt-6">
                            <h4 class="font-bold text-gray-800 mb-4 text-lg">
                                <i class="fas fa-share-nodes mr-2 text-green-500"></i>Share This Article
                            </h4>
                            <div class="share-buttons-grid">
                                <a href="https://twitter.com/intent/tweet?url=<?= urlencode('https://miscalculators.com/blog/' . $post['slug']) ?>&text=<?= urlencode($post['title']) ?>" target="_blank" rel="noopener noreferrer" class="share-button bg-blue-400 text-white hover:bg-blue-500">
                                    <i class="fab fa-twitter mr-2"></i>Twitter
                                </a>
                                <a href="https://www.facebook.com/sharer/sharer.php?u=<?= urlencode('https://miscalculators.com/blog/' . $post['slug']) ?>" target="_blank" rel="noopener noreferrer" class="share-button bg-blue-600 text-white hover:bg-blue-700">
                                    <i class="fab fa-facebook-f mr-2"></i>Facebook
                                </a>
                                <a href="https://www.linkedin.com/sharing/share-offsite/?url=<?= urlencode('https://miscalculators.com/blog/' . $post['slug']) ?>" target="_blank" rel="noopener noreferrer" class="share-button bg-blue-700 text-white hover:bg-blue-800">
                                    <i class="fab fa-linkedin-in mr-2"></i>LinkedIn
                                </a>
                                <button onclick="copyLink()" class="share-button bg-gray-600 text-white hover:bg-gray-700">
                                    <i class="fas fa-link mr-2"></i>Copy Link
                                </button>
                            </div>
                        </div>
                    </footer>
                </article>
            </main>
            
            <aside class="sidebar-container">
                <div class="sidebar-sticky space-y-6">
                    
                    <div id="toc-container" class="bg-white rounded-xl shadow-lg border p-4 md:p-6">
                        <h3 class="font-bold text-gray-800 mb-6 flex items-center text-lg">
                            <div class="w-8 h-8 bg-gradient-to-r from-blue-500 to-blue-600 rounded-lg flex items-center justify-center mr-3">
                                <i class="fas fa-list-ul text-white text-sm"></i>
                            </div>
                            Table of Contents
                        </h3>
                        <nav id="toc-nav" class="space-y-1"></nav>
                    </div>
                    
                </div>
            </aside>
        </div>
        
        <?php if (!empty($related_posts)): ?>
        <section id="related-articles" class="mt-16">
            <div class="bg-white rounded-2xl shadow-xl p-4 md:p-8 <?= $userIsAdmin ? 'admin-edit-section content-section group' : '' ?> relative">
                <div class="flex items-center justify-between mb-8">
                    <h2 class="text-xl md:text-2xl font-bold text-gray-800 flex items-center">
                        <i class="fas fa-newspaper mr-3 text-blue-500"></i>Related Articles
                    </h2>
                    <?php if ($userIsAdmin): ?>
                    <div class="bg-yellow-100 border border-yellow-300 rounded-lg px-3 py-1 text-xs font-semibold text-yellow-800">
                        <i class="fas fa-tools mr-1"></i>Admin: Hover posts to edit
                    </div>
                    <?php endif; ?>
                </div>
                <div class="grid sm:grid-cols-2 lg:grid-cols-4 gap-6">
                    <?php foreach ($related_posts as $related): ?>
                    <article class="related-post-card bg-white rounded-xl shadow-lg overflow-hidden border border-gray-200 hover:border-blue-400 <?= $userIsAdmin ? 'group' : '' ?> relative">
                        <?php if ($userIsAdmin): ?>
                        <?= renderAdminControls($related['id'], 'related_post', $related['id']) ?>
                        <?php endif; ?>

                        <a href="/blog/<?= htmlspecialchars($related['slug']) ?>" class="block">
                            <?php if ($related['featured_image']): ?>
                            <div class="relative h-48 overflow-hidden">
                                <img src="<?= htmlspecialchars($related['featured_image']) ?>" 
                                     alt="<?= htmlspecialchars($related['featured_alt_text'] ?? $related['title']) ?>"
                                     class="w-full h-full object-cover transform group-hover:scale-110 transition-transform duration-300"
                                     loading="lazy">
                                <div class="absolute inset-0 bg-gradient-to-t from-black/60 to-transparent"></div>

                                <?php if ($userIsAdmin): ?>
                                <div class="absolute bottom-2 left-2 bg-yellow-400 text-yellow-900 text-xs font-bold px-2 py-1 rounded">
                                    <i class="fas fa-hashtag"></i><?= $related['id'] ?>
                                </div>
                                <?php endif; ?>
                            </div>
                            <?php else: ?>
                            <div class="h-48 bg-gradient-to-br from-blue-500 to-purple-600 flex items-center justify-center">
                                <i class="fas fa-newspaper text-6xl text-white opacity-50"></i>
                            </div>
                            <?php endif; ?>

                            <div class="p-4">
                                <h3 class="font-bold text-gray-800 mb-2 line-clamp-2 group-hover:text-blue-600 transition-colors text-sm md:text-base">
                                    <?= htmlspecialchars($related['title']) ?>
                                </h3>

                                <?php if (!empty($related['excerpt'])): ?>
                                <p class="text-sm text-gray-600 mb-3 line-clamp-2">
                                    <?= htmlspecialchars($related['excerpt']) ?>
                                </p>
                                <?php endif; ?>

                                <div class="flex items-center justify-between text-xs text-gray-500">
                                    <span class="flex items-center">
                                        <i class="fas fa-calendar-alt mr-1"></i>
                                        <?= formatDate($related['created_at']) ?>
                                    </span>
                                    <?php if (!empty($related['word_count'])): ?>
                                    <span class="flex items-center">
                                        <i class="fas fa-clock mr-1"></i>
                                        <?= ceil($related['word_count'] / 200) ?> min
                                    </span>
                                    <?php endif; ?>
                                </div>

                           <?php if ($userIsAdmin): ?>
<?php
    $related_status = isset($related['status']) && is_string($related['status']) && $related['status'] !== '' 
                      ? $related['status'] 
                      : 'draft';

    $related_word_count = isset($related['word_count']) && is_numeric($related['word_count']) 
                          ? (int)$related['word_count'] 
                          : 0;
?>
<div class="mt-3 pt-3 border-t border-gray-200 flex items-center justify-between text-xs">
    <span class="px-2 py-1 rounded <?= $related_status === 'published' ? 'bg-green-100 text-green-800' : 'bg-yellow-100 text-yellow-800' ?>">
        <?= htmlspecialchars(ucfirst($related_status)) ?>
    </span>
    <span class="text-gray-500">
        <?= number_format($related_word_count) ?> <?= $related_word_count === 1 ? 'word' : 'words' ?>
    </span>
</div>
<?php endif; ?>

                            </div>
                        </a>
                    </article>
                    <?php endforeach; ?>
                </div>
            </div>
        </section>
        <?php endif; ?>

    </div>
    
    <div class="quick-jump-menu" id="quickJumpMenu"></div>
    
    <div class="floating-actions">
        <button onclick="toggleQuickJump()" class="floating-btn bg-gradient-to-br from-purple-500 to-purple-700 text-white" title="Quick Jump Menu" id="quickJumpBtn">
            <i class="fas fa-compass text-xl"></i>
            <span class="floating-btn-label">Quick Navigation</span>
        </button>
        <button onclick="scrollToTop()" class="floating-btn bg-gradient-to-br from-blue-500 to-blue-700 text-white" title="Back to Top">
            <i class="fas fa-arrow-up text-xl"></i>
            <span class="floating-btn-label">Back to Top</span>
        </button>
        <button onclick="toggleMobileToc()" class="floating-btn bg-gradient-to-br from-green-500 to-green-700 text-white lg:hidden" title="Table of Contents" id="mobileTocBtn">
            <i class="fas fa-list text-xl"></i>
            <span class="floating-btn-label">Contents</span>
        </button>
        
        
        
        
        
    </div>
    
    
    
    

    <script>
        const IS_ADMIN = <?= $userIsAdmin ? 'true' : 'false' ?>;
        const POST_ID = <?= $postId ?>;

        function editElement(elementType, postId, elementId = '') {
            if (!IS_ADMIN) return false;
            window.open(`/blog/edit_blog.php?id=${postId}`, '_blank');
        }

        function openMobileMenu() {
            document.getElementById('mobileMenu').classList.add('active');
            document.getElementById('mobileOverlay').classList.add('active');
            document.body.style.overflow = 'hidden';
        }
        
        function closeMobileMenu() {
            document.getElementById('mobileMenu').classList.remove('active');
            document.getElementById('mobileOverlay').classList.remove('active');
            document.body.style.overflow = 'auto';
        }

        function toggleMobileToc() {
            const overlay = document.getElementById('mobileTocOverlay');
            const panel = document.getElementById('mobileTocPanel');
            if (panel.classList.contains('show')) {
                closeMobileToc();
            } else {
                openMobileToc();
            }
        }
        
        function openMobileToc() {
            document.getElementById('mobileTocOverlay').classList.add('show');
            document.getElementById('mobileTocPanel').classList.add('show');
            document.body.style.overflow = 'hidden';
        }
        
        function closeMobileToc() {
            document.getElementById('mobileTocOverlay').classList.remove('show');
            document.getElementById('mobileTocPanel').classList.remove('show');
            document.body.style.overflow = 'auto';
        }

        let quickJumpVisible = false;
        
        function toggleQuickJump() {
            const menu = document.getElementById('quickJumpMenu');
            const btn = document.getElementById('quickJumpBtn');
            quickJumpVisible = !quickJumpVisible;
            if (quickJumpVisible) {
                menu.classList.add('show');
                btn.innerHTML = '<i class="fas fa-times text-xl"></i><span class="floating-btn-label">Close Menu</span>';
            } else {
                menu.classList.remove('show');
                btn.innerHTML = '<i class="fas fa-compass text-xl"></i><span class="floating-btn-label">Quick Navigation</span>';
            }
        }
        
        function populateQuickJump() {
            const menu = document.getElementById('quickJumpMenu');
            let menuHTML = '<div class="quick-jump-menu-header">';
            menuHTML += '<span><i class="fas fa-compass mr-2"></i>Quick Navigation</span>';
            menuHTML += '<span class="text-xs text-gray-500">' + (IS_ADMIN ? 'Admin' : 'Reader') + '</span>';
            menuHTML += '</div>';
            
            if (IS_ADMIN) {
                menuHTML += '<div class="admin-section-header">⚡ Admin Actions</div>';
                menuHTML += `
                    <div class="quick-jump-menu-item admin-menu-item" onclick="window.open('/blog/edit_blog.php?id=${POST_ID}', '_blank'); toggleQuickJump();">
                        <i class="fas fa-edit"></i>
                        <span>Edit This Post</span>
                    </div>
                    <div class="quick-jump-menu-item admin-menu-item" onclick="window.location.href='/blog/admin.php'; toggleQuickJump();">
                        <i class="fas fa-plus-circle"></i>
                        <span>Create New Post</span>
                    </div>
                    <div class="quick-jump-menu-item admin-menu-item" onclick="window.location.href='/blog/admin.php'; toggleQuickJump();">
                        <i class="fas fa-tachometer-alt"></i>
                        <span>Admin Dashboard</span>
                    </div>
                    <div class="admin-menu-divider"></div>
                `;
            }
            
            const quickJumpItems = [
                { icon: 'fas fa-arrow-up', text: 'Back to Top', selector: 'body' },
                { icon: 'fas fa-star', text: 'Key Highlights', selector: '#key-highlights' },
                { icon: 'fas fa-quote-left', text: 'Article Summary', selector: '#article-summary' },
                { icon: 'fas fa-user-tie', text: 'Author Info', selector: '#author-info' },
                { icon: 'fas fa-tags', text: 'Tags & Topics', selector: '#tags-topics' },
                { icon: 'fas fa-share-nodes', text: 'Share Article', selector: '#share-article' },
                { icon: 'fas fa-newspaper', text: 'Related Articles', selector: '#related-articles' }
            ];
            
            quickJumpItems.forEach(item => {
                if(document.querySelector(item.selector)) {
                    menuHTML += `
                        <div class="quick-jump-menu-item" onclick="scrollToElementById('${item.selector}'); toggleQuickJump();">
                            <i class="${item.icon}"></i>
                            <span>${item.text}</span>
                        </div>
                    `;
                }
            });
            
            menu.innerHTML = menuHTML;
        }
        
        function scrollToElementById(selector) {
            if (selector === 'body') {
                window.scrollTo({ top: 0, behavior: 'smooth' });
                return;
            }
            
            const element = document.querySelector(selector);
            if (element) {
                const headerOffset = 180;
                const elementPosition = element.getBoundingClientRect().top;
                const offsetPosition = elementPosition + window.pageYOffset - headerOffset;
                
                window.scrollTo({
                    top: offsetPosition,
                    behavior: 'smooth'
                });
            }
        }

        document.addEventListener('DOMContentLoaded', function() {
            const content = document.getElementById('article-content');
            const tocNav = document.getElementById('toc-nav');
            const mobileTocNav = document.getElementById('mobile-toc-nav');
            const tocContainer = document.getElementById('toc-container');
            const staticBreadcrumb = document.getElementById('staticBreadcrumb');
            const stickyBreadcrumb = document.getElementById('stickyBreadcrumb');
            
            const progressBar = document.getElementById('reading-progress-bar');
            const stickyProgressBar = document.getElementById('stickyProgressBar');
            
            populateQuickJump();
            
            function wrapTables() {
                if (!content) return;
                const tables = content.querySelectorAll('table');
                tables.forEach(table => {
                    if (table.parentElement.classList.contains('table-wrapper')) return;
                    
                    const wrapper = document.createElement('div');
                    wrapper.className = 'table-wrapper';
                    table.parentNode.insertBefore(wrapper, table);
                    wrapper.appendChild(table);
                });
            }
            
            function handleStickyBreadcrumb() {
                const scrollY = window.scrollY || window.pageYOffset;
                const staticBreadcrumbRect = staticBreadcrumb.getBoundingClientRect();
                const isStaticBreadcrumbVisible = staticBreadcrumbRect.bottom > 72;
                
                if (scrollY > 200 && !isStaticBreadcrumbVisible) {
                    stickyBreadcrumb.classList.add('visible');
                    document.body.classList.add('breadcrumb-visible');
                } else {
                    stickyBreadcrumb.classList.remove('visible');
                    document.body.classList.remove('breadcrumb-visible');
                }
            }
            
            // *** START: CORRECTED - Reading progress calculation ***
            function updateProgress() {
                const contentElement = document.getElementById('article-content');
                if (!contentElement) return;

                const contentRect = contentElement.getBoundingClientRect();
                const contentTop = contentRect.top + window.pageYOffset;
                const contentHeight = contentElement.scrollHeight;
                
                const viewportHeight = window.innerHeight;
                const scrollTop = window.pageYOffset || document.documentElement.scrollTop;

                // Calculate how much of the article is visible or has been scrolled past
                const scrollableDistance = contentHeight - viewportHeight;
                const scrolledPast = scrollTop - contentTop;

                let percent = 0;
                if (scrollableDistance > 0) {
                    percent = (scrolledPast / scrollableDistance) * 100;
                } else if (scrollTop > contentTop) {
                    percent = 100;
                }
                
                percent = Math.max(0, Math.min(100, percent));
                percent = Math.round(percent);

                if (progressBar) progressBar.style.width = percent + '%';
                if (stickyProgressBar) stickyProgressBar.style.width = percent + '%';
                
                const stickyProgressText = document.getElementById('sticky-progress-text');
                if(stickyProgressText) {
                    stickyProgressText.textContent = percent + '%';
                }

                handleStickyBreadcrumb();
            }
            // *** END: CORRECTED ***
            
            document.addEventListener('click', function(e) {
                const menu = document.getElementById('quickJumpMenu');
                const btn = document.getElementById('quickJumpBtn');
                if (quickJumpVisible && !menu.contains(e.target) && !btn.contains(e.target)) {
                    toggleQuickJump();
                }
            });
            
            if (!content || !tocNav) {
                window.addEventListener('scroll', updateProgress, { passive: true });
                window.addEventListener('resize', updateProgress, { passive: true });
                return;
            }
            
            wrapTables();
            
            const headings = content.querySelectorAll('h2, h3, h4');
            const processedHeadings = [];
            
            headings.forEach((heading, index) => {
                const id = 'heading-' + (index + 1);
                heading.id = id;
                processedHeadings.push({
                    element: heading,
                    id: id,
                    text: heading.textContent,
                    level: parseInt(heading.tagName.substring(1))
                });
            });
            
            if (processedHeadings.length > 0) {
                processedHeadings.forEach(heading => {
                    const link = document.createElement('a');
                    link.href = '#' + heading.id;
                    link.textContent = heading.text;
                    link.className = 'toc-link';
                    
                    const mobileLink = link.cloneNode(true);
                    
                    if (heading.level > 2) {
                        link.style.paddingLeft = `${16 + (heading.level - 2) * 16}px`;
                        mobileLink.style.paddingLeft = `${16 + (heading.level - 2) * 16}px`;
                        link.classList.add('text-sm', 'text-gray-600');
                        mobileLink.classList.add('text-sm', 'text-gray-600');
                    } else {
                        link.classList.add('font-medium', 'text-gray-800');
                        mobileLink.classList.add('font-medium', 'text-gray-800');
                    }
                    
                    const handleTocClick = (e) => {
                        e.preventDefault();
                        const target = document.querySelector(e.currentTarget.getAttribute('href'));
                        if (target) {
                            const offsetPosition = target.getBoundingClientRect().top + window.pageYOffset - 140;
                            window.scrollTo({ top: offsetPosition, behavior: 'smooth' });
                        }
                        if (document.getElementById('mobileTocPanel').classList.contains('show')) {
                            closeMobileToc();
                        }
                    };
                    
                    link.addEventListener('click', handleTocClick);
                    mobileLink.addEventListener('click', handleTocClick);
                    
                    tocNav.appendChild(link);
                    if(mobileTocNav) mobileTocNav.appendChild(mobileLink);
                });

                const tocLinks = tocNav.querySelectorAll('a');
                const mobileTocLinks = mobileTocNav ? mobileTocNav.querySelectorAll('a') : [];
                
                const onScroll = () => {
                    let current = '';
                    processedHeadings.forEach(h => {
                        const rect = h.element.getBoundingClientRect();
                        if (rect.top < 150) {
                            current = h.id;
                        }
                    });

                    [...tocLinks, ...mobileTocLinks].forEach(link => {
                        link.classList.remove('active-toc-link');
                        if (link.getAttribute('href') === '#' + current) {
                            link.classList.add('active-toc-link');
                        }
                    });
                    updateProgress();
                };
                
                window.addEventListener('scroll', onScroll, { passive: true });
                onScroll();

            } else {
                if (tocContainer) tocContainer.style.display = 'none';
                window.addEventListener('scroll', updateProgress, { passive: true });
            }

            window.addEventListener('resize', () => {
                if (window.innerWidth >= 768) {
                    closeMobileMenu();
                    closeMobileToc();
                }
            }, { passive: true });
        });
        
        function scrollToTop() {
            window.scrollTo({ top: 0, behavior: 'smooth' });
        }
        
        function copyLink() {
            navigator.clipboard.writeText(window.location.href).then(() => {
                alert('Article link copied to clipboard!');
            });
        }
    </script>

    <script>
        
        
     
document.addEventListener('DOMContentLoaded', function () {
    const btn = document.getElementById('calculatorsDropdownBtn');
    const panel = document.getElementById('calculatorsDropdownContent');

    if (!btn || !panel) return;

    // helper to compute and place the dropdown panel
    function placeDropdown() {
        // reset
        panel.style.minWidth = '';
        panel.style.left = '';
        panel.style.maxHeight = '400px';
        panel.style.overflowY = 'auto';
        panel.style.top = '';
        panel.style.right = '';

        // bounding rect of button
        const rect = btn.getBoundingClientRect();
        const panelRect = panel.getBoundingClientRect();
        const viewportWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
        const viewportHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);

        // prefer to open below the button; if not enough space, open above
        const spaceBelow = viewportHeight - rect.bottom;
        const spaceAbove = rect.top;

        // set width similar to button (but allow bigger)
        const desiredMinWidth = Math.max(rect.width, 200);
        panel.style.minWidth = Math.min(desiredMinWidth, viewportWidth - 20) + 'px';

        // compute left to align start with button but keep inside viewport
        let left = rect.left;
        if (left + panelRect.width > viewportWidth - 10) {
            // try align to right edge of button
            left = rect.right - panelRect.width;
        }
        if (left < 10) left = 10;

        // decide placement top / bottom
        let top;
        let placement = 'bottom';
        // recompute panelRect.width after minWidth change by measuring
        const measuredWidth = panel.offsetWidth || panelRect.width;
        if (spaceBelow >= panel.offsetHeight + 10 || spaceBelow >= spaceAbove) {
            // place below
            top = rect.bottom + 6; // small gap
            placement = 'bottom';
        } else {
            // place above
            top = rect.top - panel.offsetHeight - 6;
            placement = 'top';
        }

        // ensure top inside viewport
        if (top < 8) top = 8;
        if (top + panel.offsetHeight > viewportHeight - 8) {
            top = Math.max(8, viewportHeight - panel.offsetHeight - 8);
        }

        panel.style.left = left + 'px';
        panel.style.top = top + 'px';
        panel.setAttribute('data-placement', placement);
    }

    // toggle
    function openDropdown() {
        panel.classList.add('show');
        placeDropdown();
        // small delay: reposition after styles applied and browser layout settled
        requestAnimationFrame(() => requestAnimationFrame(placeDropdown));
    }
    function closeDropdown() {
        panel.classList.remove('show');
    }

    btn.addEventListener('click', function (e) {
        e.stopPropagation();
        if (panel.classList.contains('show')) {
            closeDropdown();
        } else {
            openDropdown();
        }
    });

    // close on outside click
    window.addEventListener('click', function (ev) {
        if (!panel.contains(ev.target) && !btn.contains(ev.target)) {
            closeDropdown();
        }
    }, { passive: true });

    // reposition on scroll/resize and when keyboard nav changes
    let raf = null;
    function schedulePlace() {
        if (raf) cancelAnimationFrame(raf);
        raf = requestAnimationFrame(placeDropdown);
    }
    window.addEventListener('resize', schedulePlace, { passive: true });
    window.addEventListener('scroll', schedulePlace, { passive: true });

    // keyboard: ESC to close
    document.addEventListener('keydown', function (e) {
        if (e.key === 'Escape') closeDropdown();
    });

    // if the DOM of panel changes (e.g., calculators loaded), reposition
    if ('MutationObserver' in window) {
        const obs = new MutationObserver(() => {
            if (panel.classList.contains('show')) placeDropdown();
        });
        obs.observe(panel, { childList: true, subtree: true });
    }
});


        
        
        
    </script>
    
    <?php if ($userIsAdmin): ?>
    <script>
/* ---------- Reading Progress — Replacement ---------- */
(function () {
    const stickyProgressBar = document.getElementById('stickyProgressBar');
    const stickyProgressText = document.getElementById('sticky-progress-text');
    const stickyBreadcrumb = document.getElementById('stickyBreadcrumb');
    const staticBreadcrumb = document.getElementById('staticBreadcrumb');

    // safe getter for scroll top across browsers
    function getScrollTop() {
        return window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
    }

    function updateProgress() {
        // recalc sizes every call (handles images/late content)
        const scrollTop = getScrollTop();
        const contentElement = document.getElementById('article-content');
        if (!contentElement) return;

        const contentRect = contentElement.getBoundingClientRect();
        const contentTop = contentRect.top + scrollTop;
        const contentHeight = contentElement.scrollHeight;
        const viewportHeight = window.innerHeight;

        const scrollableDistance = contentHeight - viewportHeight;
        const scrolledPast = scrollTop - contentTop;

        let percent = 0;
        if (scrollableDistance > 0) {
            percent = (scrolledPast / scrollableDistance) * 100;
        } else if (scrollTop > contentTop) {
            percent = 100;
        }

        percent = Math.max(0, Math.min(100, Math.round(percent)));


        if (stickyProgressBar) {
            stickyProgressBar.style.width = percent + '%';
        }
        if (stickyProgressText) {
            stickyProgressText.textContent = percent + '%';
        }

        // sticky breadcrumb visibility (reuse your logic)
        try {
            const staticRect = staticBreadcrumb.getBoundingClientRect();
            const isStaticBreadcrumbVisible = staticRect.bottom > 72;
            if (scrollTop > 200 && !isStaticBreadcrumbVisible) {
                stickyBreadcrumb.classList.add('visible');
                document.body.classList.add('breadcrumb-visible');
            } else {
                stickyBreadcrumb.classList.remove('visible');
                document.body.classList.remove('breadcrumb-visible');
            }
        } catch (e) {
            // ignore if elements missing
        }
    }

    // throttle helper to avoid too many updates on very fast scroll
    let scheduled = null;
    function onScrollThrottled() {
        if (scheduled) return;
        scheduled = requestAnimationFrame(() => {
            updateProgress();
            scheduled = null;
        });
    }

    // init on DOM ready + load (images might change scrollHeight)
    document.addEventListener('DOMContentLoaded', updateProgress, { passive: true });
    window.addEventListener('load', updateProgress, { passive: true });

    // listen to scroll + resize
    window.addEventListener('scroll', onScrollThrottled, { passive: true });
    window.addEventListener('resize', onScrollThrottled, { passive: true });

    // also observe body size changes (e.g., images inserted) to recompute
    if ('ResizeObserver' in window) {
        try {
            const ro = new ResizeObserver(updateProgress);
            ro.observe(document.documentElement);
            ro.observe(document.body);
        } catch (e) {
            // ignore if any issue
        }
    }

    // initial call (in case script inserted after DOMContentLoaded)
    updateProgress();
})();



</script>

    <?php endif; ?>
    
    <?php include __DIR__ . '/footer.php'; ?>
    
</body>
</html>