<?php
// save_text.php - User's story management, viewer, and interaction page
session_start();
// Start output buffering early to prevent header errors
if (ob_get_level() === 0) ob_start(); 
// config.php MUST be included before any session or database operations
include('config.php'); 

// =================================================================
// Configuration
// =================================================================
const SOURCE_LANG_AUTO = 'auto';
const STORY_LOAD_LIMIT = 10; // Load 10 stories per request

// =================================================================
// 1. NON-LOGGED IN CHECK (MUST be before any output)
// =================================================================
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}
$user_id = $_SESSION['user_id']; 

// =================================================================
// 2. HANDLE POST REQUEST (Story Save/Update)
// =================================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    $number = $_POST['story_number'] ?? '';
    $title = $_POST['story_title'] ?? '';
    $category = $_POST['category'] ?? '';
    $content = $_POST['content'] ?? '';
    // Custom field is captured here but not currently used in the database query
    $custom_field = $_POST['custom_field'] ?? ''; 

    if (!$number || !$title || !$content) {
        header("Location: save_text.php?error=fields_required");
        exit();
    }
    
    // Ensure $conn exists before proceeding with DB operations
    if (!$conn) {
        header("Location: save_text.php?error=db_connection_fail");
        exit();
    }

    // Check if story exists (Update or Insert)
    $checkStmt = $conn->prepare("SELECT id FROM stories WHERE user_id = ? AND story_number = ?");
    $checkStmt->bind_param("is", $user_id, $number);
    $checkStmt->execute();
    $checkResult = $checkStmt->get_result();
    $checkStmt->close();

    if ($checkResult->num_rows > 0) {
        // UPDATE existing story
        $updateStmt = $conn->prepare("UPDATE stories SET story_title = ?, category = ?, content = ? WHERE user_id = ? AND story_number = ?");
        $updateStmt->bind_param("sssis", $title, $category, $content, $user_id, $number);
        if ($updateStmt->execute()) {
            $updateStmt->close();
            $conn->close(); 
            header("Location: save_text.php?updated=true");
            exit(); 
        } 
        $updateStmt->close();
    } else {
        // INSERT new story
        $insertStmt = $conn->prepare("INSERT INTO stories (user_id, story_number, story_title, category, content) VALUES (?, ?, ?, ?, ?)");
        $insertStmt->bind_param("issss", $user_id, $number, $title, $category, $content);
        if ($insertStmt->execute()) {
            $insertStmt->close();
            $conn->close();
            header("Location: save_text.php?saved=true");
            exit(); 
        }
        $insertStmt->close();
    }
    
    // Fallback error 
    $conn->close();
    header("Location: save_text.php?error=db_fail");
    exit();
}

// =================================================================
// 3. AJAX HANDLER (Output stories only, then exit)
// =================================================================
if (isset($_GET['ajax_load'])) {
    
    $offset = (int)($_GET['offset'] ?? 0);
    $limit = (int)($_GET['limit'] ?? STORY_LOAD_LIMIT);
    
    if (!$conn) {
        // Silent fail for AJAX if DB connection is missing
        exit;
    }

    $search = $_GET['search'] ?? '';
    $filter = $_GET['filter'] ?? '';

    // Prepare query with filter + search logic
    $types = "i";
    $params = [$user_id];
    $query = "SELECT story_number, story_title, category, content FROM stories WHERE user_id = ?";

    if (!empty($filter) && $filter !== 'All') {
        $query .= " AND category = ?";
        $types .= "s";
        $params[] = $filter;
    }
    if (!empty($search)) {
        $query .= " AND (story_title LIKE ? OR category LIKE ? OR content LIKE ?)";
        $types .= "sss";
        $searchTerm = "%" . $search . "%";
        $params[] = $searchTerm;
        $params[] = $searchTerm;
        $params[] = $searchTerm;
    }
    
    $query .= " ORDER BY story_number DESC LIMIT ? OFFSET ?";
    $types .= "ii";
    $params[] = $limit;
    $params[] = $offset;

    $stmt = $conn->prepare($query);
    
    // FIX: Use call_user_func_array for binding dynamic parameters by reference
    if ($stmt && !empty($params)) {
        $bind_names = [$types]; 
        for ($i = 0; $i < count($params); $i++) {
            $bind_names[] = &$params[$i]; // Pass parameters by reference
        }
        call_user_func_array([$stmt, 'bind_param'], $bind_names);
    }
    // END FIX

    $result = null;
    if ($stmt && $stmt->execute()) {
        $result = $stmt->get_result();
        $stmt->close();
    } else {
        error_log("AJAX query failed: " . ($stmt ? $stmt->error : 'Statement failed preparation.'));
    }
    
    // Output stories HTML without the main page wrapper
    if ($result && $result->num_rows > 0) {
        ob_clean(); // Ensure only the stories HTML is output
        while ($row = $result->fetch_assoc()) {
            $num = htmlspecialchars($row['story_number']);
            $title = htmlspecialchars($row['story_title']);
            $cat = htmlspecialchars($row['category']);
            $cont = $row['content']; 

            // NOTE: story-actions now uses class names that align with the provided CSS
            echo "<div class='story-entry' id='story-$num' data-category='$cat'>
                <div class='story-header'>
                    <strong>Story #$num</strong> — <em class='story-category'>$cat</em>
                </div>
                <h4>$title</h4>
                <div class='story-content'>$cont</div>
                <div class='story-actions'>
                    <button class='action-btn primary-btn' onclick='toggleTranslation($num, this)'>🔄 Show Translation</button>
                    <button class='action-btn primary-btn' onclick='speakFullStory($num)'>🔊 Speak Story</button>
                    <a class='action-btn action-link' href='edit_story.php?story_number=$num'>✏️ Edit</a>
                    <a class='action-btn delete-link' href='delete_story.php?story_number=$num'>🗑️ Delete</a>
                </div>

                <div class='translation-box' id='translations-$num' style='display:none;'>
                    <h4>🌐 English:</h4>
                    <p class='english'>[Translating...]</p>
                    <h4>🌐 Bangla:</h4>
                    <p class='bangla'>[Translating...]</p>
                </div>
                </div>";
        }
    }
    
    $conn->close();
    exit; 
}

// =================================================================
// 4. MAIN PAGE SETUP (USER-SPECIFIC CATEGORY FETCH)
// =================================================================
// Fetching categories *before* output buffer ends
$search = $_GET['search'] ?? '';
$filter = $_GET['filter'] ?? '';
$showSuccess = isset($_GET['saved']) && $_GET['saved'] === 'true';
$showUpdateSuccess = isset($_GET['updated']) && $_GET['updated'] === 'true';
$showError = isset($_GET['error']);

$categories = ['All'];
if (isset($conn)) {
    $catStmt = $conn->prepare("SELECT DISTINCT category FROM stories WHERE user_id = ? AND category IS NOT NULL AND category != '' ORDER BY category ASC");
    $catStmt->bind_param("i", $user_id);
    $catStmt->execute();
    $catResult = $catStmt->get_result();

    while ($row = $catResult->fetch_assoc()) {
        $catName = $row['category'];
        if (!empty($catName)) {
            $categories[] = $catName;
        }
    }
    $catStmt->close();
    // Do not close $conn here if dynamic_front_menu.php still needs it
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Top Teacher Education - My Stories</title>
    <link rel="stylesheet" href="dynamic_front_menu.css">
    <link rel="stylesheet" href="styles.css"> 
    <link rel="stylesheet" href="menu.css"> 
    <link rel="stylesheet" href="save_text.css" />
    <link rel="icon" type="image/x-icon" href="favicon.ico">

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<style>
    /* ------------------------------------------------------------------- */
    /* 🟢 RESPONSIVE & MAIN LAYOUT STYLES 🟢 */
    /* ------------------------------------------------------------------- */
    body {
        font-family: Arial, sans-serif;
        background-color: #f4f7f6;
        margin: 0;
        padding: 0;
        display: flex;
        flex-direction: column;
        min-height: 100vh;
    }
    /* Main container adapts to full width on mobile, max 1400px on desktop */
    main {
        flex: 1;
        width: 100%;
        margin: 0 auto;
        padding: 20px;
        box-sizing: border-box;
    }
    h2, h3 { 
        color: #2c3e50; 
        text-align: center; 
        margin-top: 15px;
        border-bottom: 1px solid #ddd;
        padding-bottom: 8px;
    }
    
    /* Desktop-Specific Main Container Styling (Full Screen View: 1400px) */
    @media (min-width: 768px) {
        main {
            max-width: 1400px; /* Wide screen size */
            padding: 30px;
            background-color: transparent; /* Full screen look */
            box-shadow: none; /* Full screen look */
            margin-top: 20px;
        }
    }
    
    /* --- MENU CSS FIX: OVERRIDE GLOBAL STYLES & ENFORCE 100% WIDTH --- */
    .tt-header-main .tt-nav-list {
        background: transparent !important; 
        gap: 0 !important; 
    }
    .html {
        font-size: none !important; 
    }


    /* Search and Filter Controls (Using full width on mobile) */
    .search-filter-controls {
        padding: 10px 0;
        margin-bottom: 20px;
        display: flex;
        flex-wrap: wrap;
        justify-content: center;
        gap: 10px;
    }
    .search-filter-controls input[type="text"] {
        padding: 10px 15px;
        border: 1px solid #ccc;
        border-radius: 5px;
        width: 100%;
        max-width: 300px;
        box-sizing: border-box;
    }
    .search-filter-controls button {
        padding: 10px 20px;
        background-color: #3498db;
        color: white;
        border: none;
        border-radius: 5px;
        cursor: pointer;
        transition: background-color 0.2s;
        flex-grow: 1;
        max-width: 120px;
    }
    .category-filters {
        padding: 10px 0;
        margin-bottom: 20px;
        display: flex;
        flex-wrap: wrap;
        justify-content: center;
        gap: 8px;
    }
    .category-filters a {
        color: white; 
        padding: 8px 12px; 
        border-radius: 20px; 
        text-decoration: none; 
        font-size: 0.9rem;
        transition: background-color 0.2s;
    }
    .category-filters a:hover {
        opacity: 0.8;
    }
    
    /* Story Entry Card Styles */
    .story-entry {
        background: white;
        border: 1px solid #ddd;
        border-radius: 8px;
        padding: 15px;
        margin-bottom: 20px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
        border-left: 5px solid #007bff; /* Highlight bar */
    }

    /* Story Actions (Buttons) */
    .story-actions {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        margin-top: 15px;
        border-top: 1px solid #eee;
        padding-top: 10px;
    }
    .action-btn {
        padding: 8px 12px;
        border-radius: 4px;
        font-size: 0.85rem;
        text-decoration: none;
        text-align: center;
        flex: 1 1 auto; 
        min-width: 120px;
        transition: background-color 0.2s;
    }
    button.primary-btn {
        background-color: #2ecc71;
        color: white;
        border: none;
    }
    a.action-link { /* Used for Edit/Delete buttons */
        color: white;
        text-decoration: none;
        border: none;
    }
    a.edit-btn {
        background-color: #f39c12;
    }
    a.delete-btn {
        background-color: #e74c3c;
    }

    /* ------------------------------------------------------------------- */
    /* 📱 MOBILE SPECIFIC STYLES (Enforcing full width view) 📱 */
    /* ------------------------------------------------------------------- */
    @media (max-width: 600px) {
        /* 🎯 KEY: Remove horizontal padding on main content for full width */
        main {
            padding: 10px 0; /* Padding is vertical only, relying on children for side spacing */
        }
        
        /* Apply small horizontal padding to immediate children for spacing */
        .search-filter-controls, 
        .category-filters,
        #story-list-container,
        .loading-indicator,
        h2, h3, p, 
        .top-actions {
             padding-left: 10px;
             padding-right: 10px;
             box-sizing: border-box;
             width: 100%;
             max-width: 100%;
        }
        
        /* Story entry needs padding inside its container, but its container should be full width */
        .story-entry {
             margin-left: 10px;
             margin-right: 10px;
             padding: 10px; /* Reduced internal padding for more content */
             box-sizing: border-box;
             width: auto;
        }

        /* Full width stacking for forms and buttons */
        .search-filter-controls input[type="text"], 
        .search-filter-controls button,
        .story-actions,
        .action-btn, .action-link {
            max-width: 100%;
            flex-basis: 100%;
        }
        .story-actions {
            flex-direction: column;
            gap: 10px;
        }
    }


    /* ------------------------------------------------------------------- */
    /* GLOBAL & TOOLTIP STYLES (Your original styles) */
    /* ------------------------------------------------------------------- */
    .word { cursor: pointer; transition: background-color 0.1s; }
    .word:hover { background-color: #f0f0f0; }
    .tooltip {
        position: absolute; background-color: #333; color: white; padding: 8px 12px; border-radius: 6px; z-index: 1000; font-size: 0.9em; transform: translateX(-50%); white-space: nowrap; pointer-events: none;
    }
    .tooltip button { pointer-events: auto; }
    .toast-notification {
        visibility: hidden; min-width: 250px; background-color: #333; color: #fff; text-align: center; border-radius: 2px; padding: 16px; position: fixed; z-index: 2000; left: 50%; bottom: 30px; transform: translateX(-50%); font-size: 17px; opacity: 0; transition: visibility 0s, opacity 0.5s ease;
    }
    .toast-notification.show { visibility: visible; opacity: 1; }
    #story-list-container { min-height: 500px; } 
    .loading-indicator { text-align: center; padding: 10px; font-style: italic; color: #555; }
</style>

<script>
const TARGET_LANG_1 = 'en';
const TARGET_LANG_2 = 'bn';
const LOAD_LIMIT = <?php echo STORY_LOAD_LIMIT; ?>;
let currentOffset = 0; 
let isLoading = false;
let allLoaded = false;
let currentSpeakingStory = null;

// =================================================================
// Core Utility Functions (Including Toast and Translation)
// =================================================================

function showToast(message) {
    let toast = document.getElementById("toastNotification");
    
    if (!toast) {
        toast = document.createElement("div");
        toast.id = "toastNotification";
        toast.className = "toast-notification";
        document.body.appendChild(toast);
    }
    
    toast.textContent = message;
    toast.className = "toast-notification show";

    setTimeout(function(){ 
        toast.className = toast.className.replace("show", ""); 
    }, 3000);
}

function translateText(text, targetLang, callback) {
    const apiUrl = `https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=${targetLang}&dt=t&q=${encodeURIComponent(text)}`;
    $.get(apiUrl, function (data) {
        const translatedText = data[0].map(t => t[0]).join("");
        callback(translatedText);
    }).fail(function() {
        callback(`[Translation Error for ${targetLang}]`);
    });
}

function speakText(text) {
    if ('speechSynthesis' in window) {
        window.speechSynthesis.cancel(); 
        const utter = new SpeechSynthesisUtterance(text);
        utter.lang = 'en'; // Assuming the default story language is English
        window.speechSynthesis.speak(utter);
    } else {
        console.warn("Text-to-speech not supported in this browser.");
    }
}

function saveWordToMemorizationList(word, translationEn, translationBn, sourceLangCode) {
    $.ajax({
        url: 'save_word.php', // Assuming this file handles saving words to the user's list
        type: 'POST',
        dataType: 'json',
        data: {
            word: word,
            translation_en: translationEn,
            translation_bn: translationBn,
            source_lang_code: sourceLangCode
        },
        success: function(response) {
            showToast(response.message); 
        },
        error: function() {
            showToast('Error: Could not save the word.');
        }
    });
}

// =================================================================
// Story & Word Interaction Logic
// =================================================================

function translateFullStory(storyNum, callback) {
    const contentEl = document.querySelector(`#story-${storyNum} .story-content`);
    const text = contentEl.innerText;
    const box = document.querySelector(`#translations-${storyNum}`);
    
    let translationsCompleted = 0;
    const expectedTranslations = 2;

    const checkCompletion = () => {
        translationsCompleted++;
        if (translationsCompleted === expectedTranslations && callback) {
            callback();
        }
    };
    
    box.querySelector('.english').textContent = '[Translating to English...]';
    box.querySelector('.bangla').textContent = '[Translating to Bangla...]';

    translateText(text, TARGET_LANG_1, t => {
        box.querySelector('.english').textContent = t;
        checkCompletion();
    });
    
    translateText(text, TARGET_LANG_2, t => {
        box.querySelector('.bangla').textContent = t;
        checkCompletion();
    });
    
    box.style.display = 'block';
}

function speakFullStory(storyNum) {
    const synth = window.speechSynthesis;

    if (currentSpeakingStory === storyNum && synth.speaking) {
        synth.cancel();
        currentSpeakingStory = null;
        return;
    }

    const contentEl = document.querySelector(`#story-${storyNum} .story-content`);
    const text = contentEl.innerText;
    speakText(text);

    currentSpeakingStory = storyNum;

    window.speechSynthesis.onend = () => {
        currentSpeakingStory = null;
    };
}

// Applies word wrapping and event listeners to newly loaded content
function wrapWords(containerElement) {
    $(containerElement).find('.story-content').each(function() {
        const container = $(this)[0];
        if (container.dataset.wrapped) return;

        const treeWalker = document.createTreeWalker(container, NodeFilter.SHOW_TEXT, null, false);
        let node;
        const textNodes = [];

        while (node = treeWalker.nextNode()) {
            // Check if parent node is not already a wrapper (like an editor tag)
            if (node.nodeValue.trim() && node.parentNode.className !== 'word') {
                textNodes.push(node);
            }
        }

        textNodes.forEach(textNode => {
            const parent = textNode.parentNode;
            // Use regex to split words but keep spaces as separate elements
            const words = textNode.textContent.split(/(\s+)/); 
            const fragment = document.createDocumentFragment();

            words.forEach(word => {
                if (word.trim()) {
                    const span = document.createElement('span');
                    span.className = 'word';
                    span.textContent = word;
                    span.addEventListener('click', handleWordClick);
                    fragment.appendChild(span);
                } else {
                    fragment.appendChild(document.createTextNode(word));
                }
            });

            parent.replaceChild(fragment, textNode);
        });
        container.dataset.wrapped = 'true';
    });
}

function showTooltip(element, translation, word, sourceLangCode) {
    hideTooltip();

    const tooltip = document.createElement("div");
    tooltip.className = "tooltip";
    
    const translationText = translation.split('|').map(t => `<p style="margin: 3px 0; font-weight: 500;">${t.trim()}</p>`).join('');
    
    const saveButton = document.createElement('button');
    saveButton.textContent = '⭐ Save Word';
    saveButton.style.cssText = 'background: #f1c40f; color: #333; border: none; padding: 5px 10px; border-radius: 4px; cursor: pointer; margin-top: 8px; font-size: 0.9em; width: 100%;';
    
    saveButton.onclick = function() {
        const enMatch = translation.match(/EN: (.*?)\s*\|/);
        const bnMatch = translation.match(/BN: (.*)/);
        
        const en = enMatch ? enMatch[1].trim() : '';
        const bn = bnMatch ? bnMatch[1].trim() : '';
        
        saveWordToMemorizationList(word, en, bn, sourceLangCode);
        hideTooltip();
    };
    
    tooltip.innerHTML = translationText;
    tooltip.appendChild(saveButton);

    document.body.appendChild(tooltip);

    const rect = element.getBoundingClientRect();
    const leftPos = rect.left + rect.width / 2 + window.scrollX;
    const topPos = rect.top + window.scrollY - tooltip.offsetHeight - 8;

    tooltip.style.left = `${leftPos}px`;
    tooltip.style.top = `${topPos}px`;
    
    document.addEventListener('click', hideTooltip, { once: true });
}

function handleWordClick(event) {
    event.stopPropagation();
    const wordElement = event.currentTarget;
    const word = wordElement.textContent.trim();

    if (!word) return;

    speakText(word);
    hideTooltip(); 

    translateText(word, TARGET_LANG_1, (en) => {
        translateText(word, TARGET_LANG_2, (bn) => {
            const tooltipText = `EN: ${en} | BN: ${bn}`;
            
            // Re-use API call to detect source language
            $.get(`https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=${TARGET_LANG_1}&dt=bd&q=${encodeURIComponent(word)}`, function(data) {
                const detectedLangCode = data[2] || 'unknown'; 
                showTooltip(wordElement, tooltipText, word, detectedLangCode);
            }).fail(() => {
                showTooltip(wordElement, tooltipText, word, 'auto_fail');
            });
        });
    });
}

function hideTooltip() {
    document.querySelectorAll(".tooltip").forEach(tip => tip.remove());
}

function toggleTranslation(num, btn) {
    const box = document.getElementById('translations-' + num);
    
    if (box.style.display === 'none' || box.style.display === '') {
        btn.innerHTML = '⏳ Translating...';
        btn.disabled = true; 
        
        translateFullStory(num, () => {
            btn.innerHTML = '🔄 Hide Translation';
            btn.disabled = false;
        });
        
    } else {
        box.style.display = 'none';
        btn.innerHTML = '🔄 Show Translation';
        btn.disabled = false;
    }
}


// =================================================================
// Story Loading and Infinite Scroll Logic
// =================================================================

function renderStories(storiesHtml) {
    const container = $('#story-list-container');
    
    // Append HTML and then re-initialize word wrapping
    container.append(storiesHtml);
    wrapWords(container); 
}

function loadStories() {
    if (isLoading || allLoaded) {
        return;
    }
    
    isLoading = true;
    const indicator = $('#loading-indicator');
    indicator.html('Loading more stories...');

    const urlParams = new URLSearchParams(window.location.search);

    $.ajax({
        url: 'save_text.php',
        type: 'GET',
        data: { 
            ajax_load: true,
            offset: currentOffset,
            limit: LOAD_LIMIT,
            search: urlParams.get('search') || '',
            filter: urlParams.get('filter') || ''
        },
        success: function(response) {
            if (response.trim() === '') {
                allLoaded = true;
                indicator.html('End of saved stories.');
            } else {
                renderStories(response);
                currentOffset += LOAD_LIMIT;
                indicator.html('');
            }
        },
        error: function() {
            indicator.html('Error loading stories.');
        },
        complete: function() {
            isLoading = false;
        }
    });
}

function checkScroll() {
    const threshold = 300; 
    if ($(window).scrollTop() + $(window).height() >= $(document).height() - threshold) {
        loadStories();
    }
}

// Function used by the search form submission
function submitSearch(event) {
    event.preventDefault(); 

    // Update URL parameters (search only)
    const newUrl = new URL(window.location.href);
    const searchInput = newUrl.searchParams.get('search');

    if (searchInput) {
        newUrl.searchParams.set('search', searchInput);
    } else {
        newUrl.searchParams.delete('search');
    }
    
    window.history.pushState({}, '', newUrl);

    // Reset list and reload
    $('#story-list-container').empty();
    $('#loading-indicator').html('Loading stories...');
    currentOffset = 0;
    allLoaded = false;
    loadStories(); 
}

// Initial setup
$(document).ready(function() {
    // Attach event listener for the search form
    $('.search-filter-controls').on('submit', function(e) {
        e.preventDefault();
        
        // Use URLSearchParams to capture current values
        const url = new URL(window.location.href);
        const searchVal = $(this).find('input[name="search"]').val();
        
        // Update URL: Remove existing params first (except session/base context)
        url.searchParams.delete('search');
        url.searchParams.delete('filter');

        if (searchVal) {
             url.searchParams.set('search', searchVal);
        }
        
        // Note: Filters are handled by the category links' HREF values

        window.history.pushState({}, '', url.toString());

        $('#story-list-container').empty();
        $('#loading-indicator').html('Loading stories...');
        currentOffset = 0;
        allLoaded = false;
        loadStories();
    });
    
    // Initial load happens here
    loadStories(); 
    $(window).scroll(checkScroll);
});

</script>
</head>
<body>
    <?php
    // This includes the dynamic menu logic, its CSS, and outputs the <header> tag.
    include('dynamic_front_menu.php');
    ?>

    <main>
        <div style="text-align: center;">
            <h2>Saved Stories</h2>
            <?php if ($showError): ?>
                <p style='color:red; text-align:center;'>❌ An error occurred or required fields were missing. Please try again.</p>
            <?php endif; ?>
            <?php if ($showSuccess || $showUpdateSuccess): ?>
            <script>
                // Use DOMContentLoaded or jQuery's ready function for toast messages
                $(document).ready(function() {
                    let message = "✅ Story saved successfully!";
                    <?php if ($showUpdateSuccess): ?>
                    message = "✅ Story updated successfully!";
                    <?php endif; ?>
                    if (typeof showToast === 'function') {
                        showToast(message);
                    }
                });
            </script>
            <?php endif; ?>
            <p>Click on any word to see its meaning, hear the sound, and **save it to your memorization list.** 📝</p>
        </div>

        <div class="top-actions" style="text-align: center; margin-bottom: 20px;">
            <a href="memorized_list.php" class="action-btn action-link" style=" /* Using standardized classes for better CSS adherence */
                background-color: #f1c40f; 
                color: #333; 
                padding: 10px 20px;
                display: inline-block;
                min-width: 200px;
            ">
                📚 View Memorized Words
            </a>
            </div>
        
        <form method="GET" action="save_text.php" class="search-filter-controls">
            <input type="text" name="search" placeholder="Search your stories..." value="<?php echo htmlspecialchars($search); ?>">
            <button type="submit">Search</button>
        </form>

<?php
echo "<h3>Filter by Category</h3>";

// Show category filter buttons
echo "<div class='category-filters'>";
foreach ($categories as $cat) {
    $isActive = (empty($filter) && $cat === 'All') || ($filter === $cat);
    $activeStyle = $isActive ? 'background-color: #2ecc71;' : 'background-color: #3498db;';
    $url = ($cat === 'All') ? 'save_text.php' : 'save_text.php?filter=' . urlencode($cat);
    
    // Also retain the search query if active
    if (!empty($search) && $cat !== 'All') {
        $url .= '&search=' . urlencode($search);
    } elseif (!empty($search) && $cat === 'All') {
        // Retain search when clicking 'All'
        $url .= '?search=' . urlencode($search);
    }

    echo "<a href='$url' style='$activeStyle'>$cat</a>";
}
echo "</div>";
?>

<div id="story-list-container">
    </div>
<div id="loading-indicator" class="loading-indicator">
    </div>

</main>
<footer>
    <p>&copy; 2025 Top Teacher Education</p>
</footer>
<?php 
// Close the connection at the end of the script execution.
if (isset($conn)) mysqli_close($conn); 
ob_end_flush();
?>