<?php
// PHP Error Reporting for Development (Remove or set to 0 in Production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Ensure session is started only once.
// Check if a session has not been started yet.
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

include 'header.php'; // Assumed to exist and might include initial HTML
include 'db.php';     // Assumed to connect to your database ($conn)

// --- Security: Generate or validate CSRF token for comment form ---
if (!isset($_SESSION['csrf_token']) || empty($_SESSION['csrf_token'])) {
    // Generate a new token if not set or empty
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// --- Initialize variables for feedback and form persistence ---
$comment_status = [
    'type' => '', // 'success' or 'error'
    'message' => ''
];
$author_name_input = '';
$comment_text_input = '';

// --- Fetch the blog post ---------------------------------------
// Validate and sanitize input ID
$blog_id = isset($_GET['id']) ? (int)$_GET['id'] : 0; // Default to 0 if not set

if ($blog_id <= 0) {
    echo "<p class='error-message'>Blog post ID is missing or invalid.</p>";
    include 'footer.php';
    exit;
}

// Use prepared statement for fetching blog post for security
$stmt_blog = $conn->prepare("SELECT id, title, content, cover_image, created_at FROM blogs WHERE id = ?");
if ($stmt_blog === false) {
    echo "<p class='error-message'>Database error preparing blog fetch: " . htmlspecialchars($conn->error) . "</p>";
    include 'footer.php';
    exit;
}
$stmt_blog->bind_param("i", $blog_id);
$stmt_blog->execute();
$result_blog = $stmt_blog->get_result();

if ($result_blog->num_rows === 0) {
    echo "<p class='error-message'>The requested blog post was not found.</p>";
    include 'footer.php';
    exit;
}

$blog_post = $result_blog->fetch_assoc();
$stmt_blog->close(); // Close statement as soon as results are fetched

// --- Generate a URL-friendly slug for the title parameter -----
// Ensure 'title' key exists before using it
$slug = strtolower(preg_replace('/[^A-Za-z0-9]+/', '-', trim($blog_post['title'] ?? 'untitled')));

// Generate the full URL for sharing (handles HTTP/HTTPS correctly)
$current_page_url = "http" . (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "s" : "") . "://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";


// --- Handle Comment Submission ---------------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_comment'])) {
    // Retain submitted values for form persistence in case of errors
    $author_name_input = $_POST['author_name'] ?? '';
    $comment_text_input = $_POST['comment_text'] ?? '';

    // CSRF Token Validation
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        $comment_status['type'] = 'error';
        $comment_status['message'] = 'Security token mismatch. Please try again.';
    } else {
        $form_blog_id   = (int) ($_POST['blog_id'] ?? 0); // Ensure it's an int and defaults to 0
        $author_name    = trim($author_name_input);
        $comment_text   = trim($comment_text_input);

        // --- Server-side Validation ---
        if ($form_blog_id !== $blog_post['id']) {
            $comment_status['type'] = 'error';
            $comment_status['message'] = 'Invalid blog ID for comment submission.';
        } elseif (empty($author_name)) {
            $comment_status['type'] = 'error';
            $comment_status['message'] = "Please enter your name.";
        } elseif (mb_strlen($author_name, 'UTF-8') > 255) { // Using mb_strlen for multi-byte character support
            $comment_status['type'] = 'error';
            $comment_status['message'] = "Your name is too long (max 255 characters).";
        } elseif (empty($comment_text)) {
            $comment_status['type'] = 'error';
            $comment_status['message'] = "Please enter your comment.";
        } elseif (mb_strlen($comment_text, 'UTF-8') > 5000) { // Limit comment length
            $comment_status['type'] = 'error';
            $comment_status['message'] = "Your comment is too long (max 5000 characters).";
        } else {
            // Sanitize inputs before insertion (though prepared statements handle SQL escaping, this cleans general data)
            // Using filter_var for general string sanitization
            $sanitized_author_name = filter_var($author_name, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
            $sanitized_comment_text = filter_var($comment_text, FILTER_SANITIZE_FULL_SPECIAL_CHARS);

            // Prepare and bind parameters for comment insertion
            $stmt_insert_comment = $conn->prepare("INSERT INTO comments (blog_id, author_name, comment_text) VALUES (?, ?, ?)");
            if ($stmt_insert_comment === false) {
                $comment_status['type'] = 'error';
                $comment_status['message'] = 'Database error preparing comment insertion: ' . htmlspecialchars($conn->error);
                error_log('Comment Insert Prepare Error: ' . $conn->error); // Log detailed error
            } else {
                $stmt_insert_comment->bind_param("iss", $form_blog_id, $sanitized_author_name, $sanitized_comment_text);

                if ($stmt_insert_comment->execute()) {
                    $comment_status['type'] = 'success';
                    $comment_status['message'] = 'Your comment has been submitted successfully!';
                    // Clear form fields on success
                    $author_name_input = '';
                    $comment_text_input = '';
                    // Regenerate CSRF token after successful submission to prevent replay attacks
                    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
                } else {
                    $comment_status['type'] = 'error';
                    $comment_status['message'] = 'Error submitting comment: ' . htmlspecialchars($stmt_insert_comment->error);
                    error_log('Comment Insert Execute Error: ' . $stmt_insert_comment->error); // Log detailed error
                }
                $stmt_insert_comment->close();
            }
        }
    }
}

// --- Fetch Comments for this blog post -------------------------
$comments = [];
$stmt_fetch_comments = $conn->prepare("SELECT author_name, comment_text, created_at FROM comments WHERE blog_id = ? ORDER BY created_at DESC");
if ($stmt_fetch_comments === false) {
    error_log('Database error preparing comment fetch: ' . $conn->error);
} else {
    $stmt_fetch_comments->bind_param("i", $blog_id);
    if ($stmt_fetch_comments->execute()) {
        $comments_data = $stmt_fetch_comments->get_result();
        while ($comment_row = $comments_data->fetch_assoc()) {
            $comments[] = $comment_row;
        }
    } else {
        error_log('Database error executing comment fetch: ' . $stmt_fetch_comments->error);
    }
    $stmt_fetch_comments->close();
}

// Close the database connection at the end of the script
$conn->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($blog_post['title'] ?? 'Blog Post'); ?> - Blog</title>
    <style>
        /* General Body and Container Styles */
        body {
            font-family: 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            line-height: 1.6;
            color: #333;
            background-color: #f4f7f6; /* Default desktop background */
            margin: 0;
            padding: 0;
        }

        .main-content-wrapper {
            max-width: 800px; /* Max width for larger screens */
            margin: 40px auto;
            background: #ffffff; /* Explicitly white background for this wrapper */
            padding: 40px; /* Default padding for larger screens */
            border-radius: 10px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08); /* Softer, larger shadow */
        }

        /* Blog Post Content Styling */
        h1 {
            color: #2c3e50;
            font-size: 2.5em;
            margin-bottom: 0.4em;
            line-height: 1.2;
        }

        .blog-meta {
            color: #7f8c8d;
            font-size: 0.95em;
            margin-top: 0.5em;
            margin-bottom: 2em;
            display: block; /* Ensures it takes full width */
        }

        .blog-post-content h1,
        .blog-post-content h2,
        .blog-post-content h3,
        .blog-post-content h4 {
            margin-top: 2em; /* More space above headings */
            margin-bottom: 0.8em;
            color: #34495e;
            line-height: 1.3;
        }
        .blog-post-content h1 { font-size: 2.2em; }
        .blog-post-content h2 { font-size: 1.8em; }
        .blog-post-content h3 { font-size: 1.5em; }
        .blog-post-content h4 { font-size: 1.2em; }

        .blog-post-content p {
            margin-bottom: 1.5em; /* More space below paragraphs */
            line-height: 1.7;
            font-size: 1.05em;
        }
        .blog-post-content ul, .blog-post-content ol {
            margin-bottom: 1.5em;
            padding-left: 25px;
        }
        .blog-post-content li {
            margin-bottom: 0.5em;
        }

        .cover-image {
            width: 100%;
            max-height: 450px; /* Slightly taller */
            object-fit: cover;
            border-radius: 8px; /* Slightly softer corners */
            margin-top: 25px;
            margin-bottom: 30px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }

        /* Share Section */
        .share-section-container {
            margin-top: 40px; /* Increased margin */
            padding-top: 25px;
            border-top: 1px solid #eceff1; /* Lighter border */
        }
        .share-section-container h3 {
            margin-bottom: 20px;
            color: #2c3e50;
            font-size: 1.5em; /* Slightly larger */
            text-align: left; /* Align to left */
        }
        .share-link-box {
            display: flex;
            gap: 12px; /* Increased space */
            align-items: center; /* Vertically align items */
        }
        .share-link-box input[type="text"] {
            flex-grow: 1;
            padding: 12px 18px; /* Increased padding */
            border: 1px solid #dcdfe4;
            border-radius: 6px; /* Slightly softer corners */
            font-size: 1em;
            background-color: #fcfdfe;
            color: #555;
            box-shadow: inset 0 1px 3px rgba(0,0,0,0.05); /* Subtle inner shadow */
        }
        .share-link-box button {
            padding: 12px 25px;
            background-color: #616A6B; /* Dark Grey for Copy Link */
            color: white;
            border: none;
            border-radius: 6px;
            font-weight: 600; /* Bolder text */
            cursor: pointer;
            transition: background-color 0.3s ease, transform 0.2s ease;
        }
        .share-link-box button:hover {
            background-color: #4A4D4D; /* Darker grey on hover */
            transform: translateY(-1px); /* Subtle lift effect */
        }

        /* Comment Section */
        .comment-section-container {
            margin-top: 50px; /* More separation from share section */
            padding-top: 35px;
            border-top: 1px solid #eceff1;
        }
        .comment-section-container h2 {
            margin-bottom: 30px;
            color: #2c3e50;
            font-size: 2em; /* Larger heading */
            text-align: left; /* Align to left */
        }
        .comment-form {
            background: #fdfdfd;
            padding: 30px;
            border-radius: 8px;
            margin-bottom: 40px; /* More space */
            box-shadow: 0 2px 10px rgba(0,0,0,0.05); /* Softer shadow */
        }
        .comment-form h3 {
            font-size: 1.6em;
            color: #34495e;
            margin-bottom: 30px; /* Increased space below "Leave a Comment" */
            text-align: left;
        }
        .comment-form label {
            display: block;
            margin-bottom: 10px;
            font-weight: 600;
            color: #555;
            font-size: 0.95em;
        }
        .comment-form input[type="text"],
        .comment-form textarea {
            width: calc(100% - 24px); /* Account for padding and border */
            padding: 12px;
            margin-bottom: 20px;
            border: 1px solid #dcdfe4;
            border-radius: 6px;
            font-size: 1em;
            box-shadow: inset 0 1px 3px rgba(0,0,0,0.05);
        }
        .comment-form textarea {
            resize: vertical;
            min-height: 120px; /* Taller textarea */
        }
        .comment-form button {
            padding: 14px 30px;
            background-color: #616A6B; /* Dark Grey for Post Comment */
            color: white;
            border: none;
            border-radius: 6px;
            font-size: 1.1em;
            font-weight: 600;
            cursor: pointer;
            transition: background-color 0.3s ease, transform 0.2s ease;
        }
        .comment-form button:hover {
            background-color: #4A4D4D; /* Darker grey on hover */
            transform: translateY(-1px);
        }

        /* Message Styles (Success/Error) */
        .message {
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
            font-weight: bold;
            font-size: 0.95em;
        }
        .message.success {
            color: #1a752a; /* Darker green text */
            background-color: #e6ffe6;
            border: 1px solid #2ecc71; /* Green border */
        }
        .message.error {
            color: #a83232; /* Darker red text */
            background-color: #ffe6e6;
            border: 1px solid #e74c3c; /* Red border */
        }
        .error-message { /* For initial blog not found messages */
            color: #e74c3c;
            background-color: #ffe6e6;
            border: 1px solid #e74c3c;
            padding: 15px;
            border-radius: 5px;
            margin: 20px auto;
            max-width: 800px;
            text-align: center;
        }

        /* Comments List Display */
        .comments-list {
            margin-top: 30px;
        }
        .comments-list .comment-item {
            background: #ffffff;
            border: 1px solid #e0e6ea; /* Lighter border */
            padding: 25px;
            margin-bottom: 25px;
            border-radius: 8px;
            box-shadow: 0 1px 5px rgba(0,0,0,0.03); /* Very subtle shadow */
        }
        .comments-list .comment-author {
            font-weight: 700; /* Bolder */
            color: #3498db; /* Same blue as copy button */
            margin-bottom: 5px;
            font-size: 1.1em;
            display: block;
        }
        .comments-list .comment-date {
            font-size: 0.8em; /* Slightly smaller */
            color: #95a5a6; /* Softer gray */
            margin-bottom: 12px;
            display: block;
        }
        .comments-list .comment-text {
            line-height: 1.7;
            color: #444;
            font-size: 1em;
            white-space: pre-wrap; /* Preserve whitespace and line breaks */
            word-wrap: break-word; /* Break long words */
        }
        .comments-list .no-comments-message {
            text-align: center;
            color: #7f8c8d;
            font-style: italic;
            padding: 20px;
            border: 1px dashed #dcdfe4;
            border-radius: 8px;
        }

        /* ------------------------------------------------------------- */
        /* MEDIA QUERIES FOR RESPONSIVENESS (PHONE & SMALL SCREENS) */
        /* ------------------------------------------------------------- */

        @media (max-width: 768px) {
            /* General Mobile adjustments */
            body {
                /* IMPORTANT: Make body background pure white */
                background-color: #FFFFFF !important;
                background: none !important; /* Override any gradients */
                overflow-x: hidden !important; /* Prevent horizontal scrolling */
            }

            .main-content-wrapper {
                margin: 0 auto; /* Remove top/bottom margin, let container manage spacing */
                padding: 20px; /* Reduced padding for smaller screens */
                border-radius: 0; /* Optional: remove border-radius for edge-to-edge */
                box-shadow: none; /* Optional: remove shadow on very small screens */
                max-width: 100%; /* Ensure it takes full available width */
                width: 100%; /* Ensure it takes full available width */
            }

            h1 {
                font-size: 1.8em; /* Smaller main title */
            }

            .blog-post-content h1 { font-size: 1.6em; }
            .blog-post-content h2 { font-size: 1.4em; }
            .blog-post-content h3 { font-size: 1.2em; }
            .blog-post-content h4 { font-size: 1.1em; }
            .blog-post-content p {
                font-size: 0.95em; /* Slightly smaller paragraph text */
                margin-bottom: 1em;
            }

            .cover-image {
                max-height: 250px; /* Smaller max height for cover image */
                border-radius: 0; /* Edge-to-edge */
            }

            /* Share Section adjustments */
            .share-section-container,
            .comment-section-container {
                margin-top: 30px; /* Reduced margin */
                padding-top: 20px;
            }
            .share-section-container h3,
            .comment-section-container h2 {
                font-size: 1.3em; /* Smaller headings */
                margin-bottom: 15px;
            }
            .share-link-box {
                flex-direction: column; /* Stack input and button vertically */
                gap: 10px; /* Space between stacked items */
                align-items: stretch; /* Make them fill width */
            }
            .share-link-box input[type="text"],
            .share-link-box button {
                width: auto; /* Reset width for flex-item */
                padding: 10px 15px; /* Slightly less padding */
                font-size: 0.95em;
            }

            /* Comment Form adjustments */
            .comment-form {
                padding: 20px; /* Reduced padding */
                margin-bottom: 30px;
            }
            .comment-form h3 {
                font-size: 1.4em;
                margin-bottom: 20px; /* Adjusted space */
            }
            .comment-form label {
                font-size: 0.9em; /* Slightly smaller label text */
            }
            .comment-form input[type="text"],
            .comment-form textarea {
                /* Corrected calculation: 100% minus total horizontal padding+border of the element itself */
                width: calc(100% - 20px); /* 10px padding * 2 sides = 20px */
                padding: 10px;
                margin-bottom: 15px;
                font-size: 0.95em;
            }
            .comment-form textarea {
                min-height: 100px; /* Slightly shorter textarea */
            }
            .comment-form button {
                padding: 12px 20px;
                font-size: 1em;
            }

            /* Comments List adjustments */
            .comments-list .comment-item {
                padding: 15px; /* Reduced padding */
                margin-bottom: 15px;
            }
            .comments-list .comment-author {
                font-size: 1em;
            }
            .comments-list .comment-date {
                font-size: 0.75em;
            }
            .comments-list .comment-text {
                font-size: 0.9em;
            }
            .comments-list .no-comments-message {
                padding: 15px;
            }

            /* Overrides from style-phone.css that might affect main-content-wrapper or body background */
            /* Ensure the body's background is pure white on mobile */
            body {
                background-color: #FFFFFF !important;
                background: none !important; /* Neutralize any gradients */
            }

            /* If .main or .container are still causing issues, force their background too */
            /* You might need to inspect your final compiled HTML to see which element is highest in the DOM */
            /* that is covering the body background. Often it's `body` or `html`. */
            /* The .main-content-wrapper should correctly contain the white background you want. */
            
            /* Remove or adjust other global overrides from style-phone.css if they interfere with blog detail */
            /* Example: if .container or .main is getting a gradient from style-phone.css and covering the body */
            .main, .container {
                background-color: #FFFFFF !important; /* Force content areas to white */
                background: none !important;
            }
        }

        @media (max-width: 480px) { /* Even smaller screens if needed */
            .main-content-wrapper {
                margin: 0 auto;
                padding: 15px; /* Further reduced padding */
            }
            h1 {
                font-size: 1.6em;
            }
            .blog-post-content h1 { font-size: 1.4em; }
            .blog-post-content h2 { font-size: 1.2em; }
            .blog-post-content h3 { font-size: 1.1em; }
            .blog-post-content h4 { font-size: 1em; }
            .blog-post-content p {
                font-size: 0.9em;
            }
            .share-link-box input[type="text"],
            .share-link-box button,
            .comment-form input[type="text"],
            .comment-form textarea,
            .comment-form button {
                font-size: 0.9em;
                padding: 8px 12px;
            }
        }

    </style>
</head>
<body>

<div class="main-content-wrapper">
    <h1><?php echo htmlspecialchars($blog_post['title'] ?? 'Untitled Post'); ?></h1>

    <p class="blog-meta">
        <?php echo htmlspecialchars(date("F j, Y", strtotime($blog_post['created_at'] ?? 'now'))); ?>
    </p>

    <?php if (!empty($blog_post['cover_image'])): ?>
        <img
            src="/<?= ltrim(htmlspecialchars($blog_post['cover_image']), '/') ?>"
            alt="<?php echo htmlspecialchars($blog_post['title'] ?? 'Blog Post'); ?> Cover Image"
            class="cover-image"
        >
    <?php endif; ?>

    <div class="blog-post-content">
        <?php
        /*
         * IMPORTANT: If $blog_post['content'] comes from a rich text editor where
         * HTML can be input by administrators, consider using a library like
         * HTML Purifier to sanitize the HTML before outputting it.
         * E.g., require_once 'htmlpurifier/library/HTMLPurifier.auto.php';
         * $config = HTMLPurifier_Config::createDefault();
         * $purifier = new HTMLPurifier($config);
         * echo $purifier->purify($blog_post['content']);
         *
         * If it's pure Markdown converted to HTML or trusted content,
         * then direct output is fine as long as the source is secure.
         * For this example, we assume content from a trusted source (admin editor)
         * and do not apply htmlspecialchars to allow HTML formatting.
         */
        echo $blog_post['content'] ?? 'No content available.';
        ?>
    </div>

    <div class="share-section-container">
        <h3>Share This Blog</h3>
        <div class="share-link-box">
            <input type="text" id="blogPermalink" value="<?php echo htmlspecialchars($current_page_url); ?>" readonly>
            <button onclick="copyPermalink()">Copy Link</button>
        </div>
    </div>

    <div class="comment-section-container">
        <h2>Comments (<span id="comment-count"><?php echo count($comments); ?></span>)</h2>

        <?php if (!empty($comment_status['message'])): ?>
            <p class="message <?php echo htmlspecialchars($comment_status['type']); ?>">
                <?php echo htmlspecialchars($comment_status['message']); ?>
            </p>
        <?php endif; ?>

        <div class="comment-form">
            <h3>Leave a Comment</h3>
            <form action="" method="POST">
                <input type="hidden" name="blog_id" value="<?php echo htmlspecialchars($blog_post['id'] ?? ''); ?>">
                <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token'] ?? ''); ?>">

                <label for="author_name">Your Name:</label>
                <input type="text" id="author_name" name="author_name" required maxlength="255"
                       placeholder="Enter your name"
                       value="<?php echo htmlspecialchars($author_name_input); ?>">

                <label for="comment_text">Your Comment:</label>
                <textarea id="comment_text" name="comment_text" rows="7" required maxlength="5000"
                          placeholder="Write your comment here..."
                          ><?php echo htmlspecialchars($comment_text_input); ?></textarea>

                <button type="submit" name="submit_comment">Post Comment</button>
            </form>
        </div>

        <div class="comments-list">
            <?php if (empty($comments)): ?>
                <p class="no-comments-message">No comments yet. Be the first to comment!</p>
            <?php else: ?>
                <?php foreach ($comments as $comment): ?>
                    <div class="comment-item">
                        <span class="comment-author"><?php echo htmlspecialchars($comment['author_name'] ?? 'Anonymous'); ?></span>
                        <span class="comment-date"><?php echo htmlspecialchars(date("F j, Y, g:i a", strtotime($comment['created_at'] ?? 'now'))); ?></span>
                        <p class="comment-text"><?php echo nl2br(htmlspecialchars($comment['comment_text'] ?? '')); ?></p>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>
</div>

<?php include 'footer.php'; // Assumed to exist ?>

<script>
    // Self-executing anonymous function to prevent global scope pollution
    (function(){
        // Using optional chaining and nullish coalescing for safety
        const blogId = <?php echo json_encode($blog_post['id'] ?? null); ?>;
        const slugTitle = <?php echo json_encode($slug ?? null); ?>;

        // Only proceed if blogId and slugTitle are valid
        if (blogId !== null && slugTitle !== null) {
            const currentUrl = new URL(window.location.href);

            // Set/update the 'id' and 'title' parameters
            currentUrl.searchParams.set('id', blogId);
            currentUrl.searchParams.set('title', slugTitle);

            // Clean up potentially old 'slug' parameter if it exists
            if (currentUrl.searchParams.has('slug')) {
                currentUrl.searchParams.delete('slug');
            }

            // Only update history if the URL actually changes
            if (window.location.href !== currentUrl.toString()) {
                window.history.replaceState(null, '', currentUrl.toString());
            }
        }
    })();

    // Function to copy the permalink
    function copyPermalink() {
        const permalinkInput = document.getElementById('blogPermalink');
        if (permalinkInput) {
            permalinkInput.select();
            permalinkInput.setSelectionRange(0, 99999); // For mobile devices

            // Use Clipboard API for modern browsers
            navigator.clipboard.writeText(permalinkInput.value).then(() => {
                // Better visual feedback than alert
                const button = document.querySelector('.share-link-box button');
                const originalText = button.textContent;
                const originalBg = button.style.backgroundColor; // Store original background
                button.textContent = 'Copied!';
                button.style.backgroundColor = '#2ecc71'; // Green for success
                setTimeout(() => {
                    button.textContent = originalText;
                    button.style.backgroundColor = originalBg; // Restore original color
                }, 1500);
            }).catch(err => {
                console.error('Failed to copy: ', err);
                // Fallback for older browsers or if Clipboard API fails
                alert('Could not copy link. Please copy it manually: ' + permalinkInput.value);
            });
        }
    }
</script>
</body>
</html>