<?php
// dashboard.php

// Include database connection file
include 'db.php';

/**
 * Formats bytes into a human-readable string (KB, MB, GB, etc.).
 * @param int $bytes The number of bytes to format.
 * @param int $precision The number of decimal places.
 * @return string The formatted file size string.
 */
function format_bytes($bytes, $precision = 2) {
    if ($bytes > 0) {
        $i = floor(log($bytes) / log(1024));
        $sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
        return sprintf('%.0' . $precision . 'F', $bytes / pow(1024, $i)) * 1 . ' ' . $sizes[$i];
    } else {
        return '0 B';
    }
}

/**
 * Formats a timestamp string to 'Y-m-d H:i:s'.
 * @param string|null $timestamp The timestamp string to format.
 * @return string The formatted timestamp or the original string if invalid.
 */
function format_timestamp($timestamp) {
    if (!$timestamp || $timestamp === 'No records') {
        return $timestamp;
    }
    try {
        return (new DateTime($timestamp))->format('Y-m-d H:i:s');
    } catch (Exception $e) {
        return $timestamp;
    }
}

// Initialize arrays for data
$stats = [
    'db_size' => 'N/A', 'db_name' => 'N/A',
    'tables' => [
        'REPOSITORY' => ['count' => 0, 'latest' => 'No records'],
        'PROJECT'    => ['count' => 0, 'latest' => 'No records'],
        'COMPONENT'  => ['count' => 0, 'latest' => 'No records'],
        'FILE'       => ['count' => 0, 'latest' => 'No records']
    ]
];
$recent_activity = [];
$search_results = [];
$error_message = null;

// FIX: Use a more robust check that allows searching for '0' and handles empty submission.
$search_query = isset($_GET['search_query']) ? trim($_GET['search_query']) : '';
$has_query = array_key_exists('search_query', $_GET) && $search_query !== '';


try {
    if ($has_query) {
        // FIX: Escape special LIKE characters for a literal search
        $needle = str_replace(['\\', '%', '_'], ['\\\\', '\\%', '\\_'], $search_query);

        // FIX: Use ILIKE for case-insensitivity and encode() for safe BYTEA handling in SQL
        $stmt = $conn->prepare('
            SELECT
                f."FILE_ID",
                f."FILE_NAME",
                encode(f."CODE", \'escape\') AS "CODE",  -- Let BYTEA return as readable text
                f."CREATED_AT",
                c."COMPONENT_NAME", c."COMPONENT_ID",
                p."PROJECT_NAME",   p."PROJECT_ID",
                r."REPOSITORY_NAME", r."REPOSITORY_ID"
            FROM "FILE" f
            LEFT JOIN "COMPONENT"  c ON f."COMPONENT_ID"  = c."COMPONENT_ID"
            LEFT JOIN "PROJECT"    p ON c."PROJECT_ID"    = p."PROJECT_ID"
            LEFT JOIN "REPOSITORY" r ON p."REPOSITORY_ID" = r."REPOSITORY_ID"
            WHERE f."FILE_NAME" ILIKE :q ESCAPE \'\\\'
            ORDER BY f."CREATED_AT" DESC
            LIMIT 100
        ');
        $stmt->bindValue(':q', "%{$needle}%", PDO::PARAM_STR);
        $stmt->execute();
        $search_results = $stmt->fetchAll(PDO::FETCH_ASSOC);

    } else {
        // --- If no search, fetch dashboard data ---
        // 1. Fetch Summary Statistics
        $db_name_stmt = $conn->query('SELECT current_database()');
        $stats['db_name'] = $db_name_stmt->fetchColumn();

        if ($stats['db_name']) {
            $size_stmt = $conn->prepare('SELECT pg_database_size(?)');
            $size_stmt->bindParam(1, $stats['db_name'], PDO::PARAM_STR);
            $size_stmt->execute();
            $stats['db_size'] = format_bytes($size_stmt->fetchColumn());
        }

        foreach ($stats['tables'] as $table_name => &$table_data) {
            $table_data['count'] = $conn->query("SELECT COUNT(*) FROM \"{$table_name}\"")->fetchColumn();
            $latest = $conn->query("SELECT MAX(\"CREATED_AT\") FROM \"{$table_name}\"")->fetchColumn();
            if ($latest) $table_data['latest'] = $latest;
        }
        unset($table_data);

        // 2. Fetch Recent Activity
        $activity_tables = [
            'REPOSITORY' => 'REPOSITORY_NAME', 'PROJECT' => 'PROJECT_NAME',
            'COMPONENT' => 'COMPONENT_NAME', 'FILE' => 'FILE_NAME'
        ];
        foreach ($activity_tables as $table_name => $name_col) {
            $stmt = $conn->query("SELECT \"{$name_col}\" AS name, \"CREATED_AT\" FROM \"{$table_name}\" ORDER BY \"CREATED_AT\" DESC LIMIT 30");
            $recent_activity[$table_name]['records'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
        }
    }

} catch (PDOException $e) {
    $error_message = "Database query failed: " . htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8');
}

// SVG icons for dashboard cards and activity lists
$icons = [
    'db_size'    => '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><ellipse cx="12" cy="5" rx="9" ry="3"></ellipse><path d="M21 12c0 1.66-4 3-9 3s-9-1.34-9-3"></path><path d="M3 5v14c0 1.66 4 3 9 3s9-1.34 9-3V5"></path></svg>',
    'REPOSITORY' => '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="2" width="20" height="8" rx="2" ry="2"></rect><rect x="2" y="14" width="20" height="8" rx="2" ry="2"></rect><line x1="6" y1="6" x2="6.01" y2="6"></line><line x1="6" y1="18" x2="6.01" y2="18"></line></svg>',
    'PROJECT'    => '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"></path></svg>',
    'COMPONENT'  => '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"></path><polyline points="3.27 6.96 12 12.01 20.73 6.96"></polyline><line x1="12" y1="22.08" x2="12" y2="12"></line></svg>',
    'FILE'       => '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polyline points="14 2 14 8 20 8"></polyline></svg>'
];
//$icon_colors = ['#00aaff', '#66d9ff', '#66ffc2', '#ffc966', '#ffb366'];
$icon_colors = ['#00aaff', '#66d9ff', '#66ffc2', '#dd6b20', '#805ad5'];

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Database Dashboard & File Search</title>
    <style>
        :root {
            --bg-color: #090a0f; --panel-bg-color: rgba(26, 26, 26, 0.6); --border-color: rgba(255, 255, 255, 0.1);
            --text-primary: #f0f0f0; --text-secondary: #a0a0a0; --accent-color: #00aaff;
            --font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
            --border-radius: 16px;
        }
        *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
        body {
            background-color: transparent; color: var(--text-primary); font-family: var(--font-family);
            padding: 1.5rem; animation: fadeIn 0.5s ease-out forwards;
        }
        @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }

        /* --- Generic & Dashboard Styles --- */
        .section-title {
            font-size: 1.5em; font-weight: 600; letter-spacing: -0.5px; margin: 2.5rem 0 1.5rem 0;
            padding-bottom: 0.75rem; border-bottom: 1px solid var(--border-color); color: var(--text-primary);
        }
        .dashboard-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 1.5rem; }
        .stat-card {
            background-color: var(--panel-bg-color); border: 1px solid var(--border-color); border-radius: var(--border-radius);
            padding: 1.5rem; backdrop-filter: blur(10px); display: flex; flex-direction: column; gap: 0.5rem;
            transition: transform 0.3s ease, box-shadow 0.3s ease; position: relative; overflow: hidden;
        }
        .stat-card:hover { transform: translateY(-5px); box-shadow: 0 10px 25px rgba(0, 0, 0, 0.5); }
        .stat-card::before {
            content: ''; position: absolute; top: 0; left: 0; width: 100%; height: 3px;
            background: var(--card-color, var(--accent-color)); box-shadow: 0 0 12px var(--card-color, var(--accent-color));
        }
        .card-header { display: flex; align-items: center; gap: 0.75rem; color: var(--text-secondary); font-size: 0.95em; }
        .card-header svg { width: 20px; height: 20px; color: var(--card-color, var(--accent-color)); }
        .card-value { font-size: 2.25em; font-weight: 600; letter-spacing: -1px; margin-top: 0.5rem; }
        .card-footer { font-size: 0.85em; color: var(--text-secondary); margin-top: auto; padding-top: 0.5rem; }
        .large-card { grid-column: 1 / -1; }
        .large-card .card-value { font-size: 2.4em; }
        .db-name-label { font-size: 0.9em; color: var(--text-secondary); margin-top: 8px; }

        .activity-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(350px, 1fr)); gap: 1.5rem; }
        .activity-panel { background-color: rgba(16, 18, 27, 0.5); border: 1px solid var(--border-color); border-radius: var(--border-radius); overflow: hidden; }
        .panel-header { display: flex; align-items: center; gap: 0.75rem; padding: 1rem 1.25rem; background-color: rgba(255, 255, 255, 0.05); border-bottom: 1px solid var(--border-color); font-weight: 600; }
        .panel-header svg { color: var(--card-color); width: 20px; height: 20px; }
        .activity-list { list-style: none; padding: 0; margin: 0; }
        .activity-item { display: flex; justify-content: space-between; align-items: center; padding: 0.85rem 1.25rem; font-size: 0.9em; border-bottom: 1px solid rgba(255, 255, 255, 0.05); }
        .activity-item:last-child { border-bottom: none; }
        .activity-item:hover { background-color: rgba(0, 170, 255, 0.1); }
        .item-name { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; padding-right: 1rem; }
        .item-time { font-size: 0.9em; color: var(--text-secondary); flex-shrink: 0; }
        .no-activity, .no-results { padding: 2rem; text-align: center; color: var(--text-secondary); }

        /* --- Search Section Styles --- */
        .search-container { margin-bottom: 1.5rem; }
        .search-form { display: flex; gap: 0.75rem; }
        .search-form input {
            flex-grow: 1; padding: 0.75rem 1rem; font-size: 1em; background-color: rgba(0, 0, 0, 0.3);
            color: var(--text-primary); border: 1px solid var(--border-color); border-radius: 12px;
            transition: border-color 0.3s, box-shadow 0.3s;
        }
        .search-form input:focus { outline: none; border-color: var(--accent-color); box-shadow: 0 0 10px rgba(0, 170, 255, 0.5); }
        .search-form button {
            padding: 0.75rem 1.5rem; font-size: 1em; font-weight: 600; cursor: pointer;
            background-color: #2a2a2a; /* Dark Grey Background */
            color: white;
            border: 1px solid var(--border-color); /* Subtle border */
            border-radius: 12px;
            transition: background-color 0.3s, border-color 0.3s;
        }
        .search-form button:hover {
            background-color: #3a3a3a; /* Lighter Grey on Hover */
            border-color: var(--accent-color); /* Accent Border on Hover */
        }

        .file-list-container {
            background-color: var(--panel-bg-color); border: 1px solid var(--border-color); border-radius: var(--border-radius);
            padding: 1rem; backdrop-filter: blur(10px); position: relative;
        }
        .file-list-header, .file-item {
            display: grid; grid-template-columns: 1fr 2fr 120px; gap: 1rem; align-items: center;
            padding: 0.75rem 1rem; border-bottom: 1px solid var(--border-color);
        }
        .file-list-header { font-weight: 600; color: var(--text-secondary); font-size: 0.85em; }
        .file-item:last-child { border-bottom: none; }
        .file-item:hover { background-color: rgba(0, 170, 255, 0.08); }
        .file-path { font-size: 0.9em; word-break: break-all; }
        .file-path a { text-decoration: none; }
        .file-path a:hover { text-decoration: underline; }
        .file-path .repo { color: #ff8282; } .file-path .proj { color: #ffc966; } .file-path .comp { color: #66d9ff; }
        .file-path .name { color: var(--text-primary); font-weight: 500; } .file-path .sep { color: var(--text-secondary); margin: 0 2px; }
        .code-content {
            white-space: pre-wrap; word-break: break-all; cursor: pointer; max-height: 150px; overflow-y: auto;
            padding: 0.5rem; border-radius: 8px; font-family: 'SF Mono', 'Fira Code', 'monospace'; font-size: 0.9em;
        }
        .code-content.highlighted { background-color: rgba(0, 170, 255, 0.2); }
        .code-content::-webkit-scrollbar { width: 6px; }
        .code-content::-webkit-scrollbar-thumb { background: rgba(255, 255, 255, 0.2); border-radius: 3px; }
        .file-timestamp { font-size: 0.9em; color: var(--text-secondary); }

        /* --- Password Modal Styles --- */
        .pw-modal-backdrop {
            position: fixed;
            inset: 0;
            display: none;
            align-items: flex-start; /* MODIFIED: Align to top */
            justify-content: center;
            padding-top: 150px; /* MODIFIED: Add top offset */
            z-index: 2000;
            background: rgba(0,0,0,0.65);
            backdrop-filter: blur(6px);
        }
        .pw-modal {
            width: 90%; max-width: 420px; background: #111; color: #eaeaea; border: 1px solid rgba(255,255,255,0.08);
            border-radius: 18px; padding: 20px; box-shadow: 0 12px 40px rgba(0,0,0,0.6);
        }
        .pw-title { font-size: 1.1rem; font-weight: 700; margin-bottom: 8px; }
        .pw-desc { font-size: 0.9rem; color: #aaa; margin-bottom: 14px; }
        .pw-input { width: 100%; padding: 10px 12px; border-radius: 10px; border: 1px solid #333; background: #0c0c0c; color: #eaeaea; outline: none; }
        .pw-actions { display: flex; gap: 10px; margin-top: 14px; }
        .pw-btn { flex: 1; padding: 10px; border: none; border-radius: 10px; cursor: pointer; background: #00aaff; color: white; font-weight: 700; }
        .pw-btn.secondary { background: #2a2a2a; color: #ddd; }
        .pw-error { color: #ff7b7b; font-size: 0.85rem; margin-top: 8px; display: none; }
        
        .error-message { background-color: rgba(255, 0, 0, 0.1); border: 1px solid rgba(255, 0, 0, 0.3); color: #ffcccc; padding: 1.5rem; border-radius: var(--border-radius); text-align: center; }
    </style>
</head>
<body>
    <?php if ($error_message): ?>
        <div class="error-message"><?php echo $error_message; ?></div>
    <?php else: ?>
        
        <!-- File Search Area -->
        <h2 class="section-title" style="margin-top: 0;">Search</h2>
        <div class="search-container">
            <form class="search-form" method="get" action="dashboard.php">
                <input type="text" name="search_query" placeholder="Search by File Name..." value="<?php echo htmlspecialchars($search_query, ENT_QUOTES, 'UTF-8'); ?>" required>
                <button type="submit">Search</button>
            </form>
        </div>

        <?php if ($has_query): ?>
            <!-- Display ONLY search results -->
            <div class="file-list-container" id="file-search-results">
                <div class="file-list-header">
                    <div>File Path</div>
                    <div>Content (Click to Copy)</div>
                    <div>Timestamp</div>
                </div>
                <?php if (!empty($search_results)): ?>
                    <?php foreach ($search_results as $row): ?>
                        <?php 
                            // FIX: The SQL query now returns CODE as text, so no unescaping is needed.
                            $code_data   = $row['CODE'];
                            $enc_payload = str_replace(["\r", "\n"], '', $code_data);
                        ?>
                        <div class="file-item">
                            <div class="file-path">
                                <span class="repo"><?php echo htmlspecialchars($row['REPOSITORY_NAME'], ENT_QUOTES, 'UTF-8'); ?></span><span class="sep">/</span>
                                <span class="proj"><?php echo htmlspecialchars($row['PROJECT_NAME'], ENT_QUOTES, 'UTF-8'); ?></span><span class="sep">/</span>
                                <span class="comp"><?php echo htmlspecialchars($row['COMPONENT_NAME'], ENT_QUOTES, 'UTF-8'); ?></span><span class="sep">/</span>
                                <span class="name"><?php echo htmlspecialchars($row['FILE_NAME'], ENT_QUOTES, 'UTF-8'); ?></span>
                            </div>
                            <div class="code-content"
                                 data-enc="<?php echo htmlspecialchars($enc_payload, ENT_QUOTES, 'UTF-8'); ?>"
                                 onclick="copyToClipboard(this)">Decrypting…</div>
                            <div class="file-timestamp"><?php echo format_timestamp($row['CREATED_AT']); ?></div>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <div class="no-results">No files found matching your search criteria.</div>
                <?php endif; ?>
            </div>
        <?php else: ?>
            <!-- Display dashboard panels if NO search is active -->
            <!-- Summary Statistics Area -->
            <h2 class="section-title">Database Summary</h2>
            <div class="dashboard-grid">
                <div class="stat-card large-card" style="--card-color: <?php echo $icon_colors[0]; ?>;">
                    <div>
                        <div class="card-header"><?php echo $icons['db_size']; ?><span>Total Database Size</span></div>
                        <div class="card-value"><?php echo htmlspecialchars($stats['db_size'], ENT_QUOTES, 'UTF-8'); ?></div>
                        <div class="db-name-label">Database: <?php echo htmlspecialchars($stats['db_name'], ENT_QUOTES, 'UTF-8'); ?></div>
                    </div>
                </div>
                <?php $i = 1; foreach ($stats['tables'] as $table_name => $data): ?>
                <div class="stat-card" style="--card-color: <?php echo $icon_colors[$i % count($icon_colors)]; ?>;">
                    <div class="card-header"><?php echo $icons[$table_name]; ?><span><?php echo htmlspecialchars($table_name, ENT_QUOTES, 'UTF-8'); ?></span></div>
                    <div class="card-value"><?php echo htmlspecialchars($data['count'], ENT_QUOTES, 'UTF-8'); ?></div>
                    <div class="card-footer">Last entry: <?php echo htmlspecialchars(format_timestamp($data['latest']), ENT_QUOTES, 'UTF-8'); ?></div>
                </div>
                <?php $i++; endforeach; ?>
            </div>

            <!-- Recent Activity Area -->
            <h2 class="section-title">Recent Activity</h2>
            <div class="activity-grid">
                <?php $i = 1; foreach ($recent_activity as $table_name => $data): ?>
                <div class="activity-panel">
                    <div class="panel-header" style="--card-color: <?php echo $icon_colors[$i % count($icon_colors)]; ?>;">
                        <?php echo $icons[$table_name]; ?>
                        <span><?php echo htmlspecialchars($table_name, ENT_QUOTES, 'UTF-8'); ?></span>
                    </div>
                    <ul class="activity-list">
                        <?php if (empty($data['records'])): ?>
                            <li class="no-activity">No activity records found.</li>
                        <?php else: ?>
                            <?php foreach ($data['records'] as $record): ?>
                            <li class="activity-item">
                                <span class="item-name" title="<?php echo htmlspecialchars($record['name'], ENT_QUOTES, 'UTF-8'); ?>">
                                    <?php echo htmlspecialchars($record['name'], ENT_QUOTES, 'UTF-8'); ?>
                                </span>
                                <span class="item-time"><?php echo htmlspecialchars(format_timestamp($record['CREATED_AT']), ENT_QUOTES, 'UTF-8'); ?></span>
                            </li>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </ul>
                </div>
                <?php $i++; endforeach; ?>
            </div>
        <?php endif; ?>
    <?php endif; ?>

    <!-- Password Modal (global for the page) -->
    <div id="pwBackdrop" class="pw-modal-backdrop" aria-hidden="true">
        <div class="pw-modal" role="dialog" aria-modal="true" aria-labelledby="pwTitle">
            <div id="pwTitle" class="pw-title">Enter Decryption Password</div>
            <div class="pw-desc">A password is required to decrypt content for this session.</div>
            <input id="pwInput" class="pw-input" type="password" placeholder="Password" autocomplete="current-password" />
            <div class="pw-actions">
                <button id="pwConfirm" class="pw-btn">Continue</button>
                <button id="pwCancel"  class="pw-btn secondary" type="button">Cancel</button>
            </div>
            <div id="pwError" class="pw-error">Password is required.</div>
        </div>
    </div>

<script>
    // --- Clipboard Function ---
    function copyToClipboard(element) {
        document.querySelectorAll('.code-content').forEach(el => el.classList.remove('highlighted'));
        element.classList.add('highlighted');
        const range = document.createRange();
        range.selectNodeContents(element);
        const selection = window.getSelection();
        selection.removeAllRanges();
        selection.addRange(range);
        try {
            document.execCommand('copy');
        } catch (err) {
            console.error('Failed to copy text: ', err);
        }
        selection.removeAllRanges();
        setTimeout(() => { element.classList.remove('highlighted'); }, 500);
    }

    // --- WebCrypto Helpers ---
    const enc = new TextEncoder();
    const dec = new TextDecoder();
    function b64encode(bytes) {
        let bin = ''; const arr = new Uint8Array(bytes);
        for (let i = 0; i < arr.length; i++) bin += String.fromCharCode(arr[i]);
        return btoa(bin);
    }
    function b64decode(str) {
        const clean = (str || '').replace(/[\r\n\s]/g, ''); const bin = atob(clean);
        const out = new Uint8Array(bin.length);
        for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
        return out.buffer;
    }
    async function deriveKey(password, salt) {
        const keyMaterial = await crypto.subtle.importKey('raw', enc.encode(password), 'PBKDF2', false, ['deriveKey']);
        return crypto.subtle.deriveKey(
            { name: 'PBKDF2', salt, iterations: 100000, hash: 'SHA-256' },
            keyMaterial, { name: 'AES-GCM', length: 256 }, false, ['encrypt','decrypt']
        );
    }
    async function aesDecrypt(packet, password) {
        if (typeof packet !== 'string' || !packet.startsWith('v1$')) return packet;
        const parts = packet.trim().split('$');
        if (parts.length !== 4) throw new Error('Invalid packet');
        const salt = new Uint8Array(b64decode(parts[1]));
        const iv   = new Uint8Array(b64decode(parts[2]));
        const ct   = b64decode(parts[3]);
        const key = await deriveKey(password, salt);
        const pt = await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, key, ct);
        return dec.decode(pt);
    }

    // --- Session-level Password Modal Logic ---
    const PW_KEY = 'code_pw_session';
    const pwBackdrop = document.getElementById('pwBackdrop');
    const pwInput = document.getElementById('pwInput');
    const pwConfirm = document.getElementById('pwConfirm');
    const pwCancel = document.getElementById('pwCancel');
    const pwError = document.getElementById('pwError');

    function havePassword() { return !!sessionStorage.getItem(PW_KEY); }
    function getPassword() { return sessionStorage.getItem(PW_KEY) || ''; }
    function openPwModal() {
        pwBackdrop.style.display = 'flex';
        pwBackdrop.setAttribute('aria-hidden', 'false');
        pwInput.value = '';
        pwInput.focus();
    }
    function closePwModal() {
        pwBackdrop.style.display = 'none';
        pwBackdrop.setAttribute('aria-hidden', 'true');
    }

    pwConfirm.addEventListener('click', () => {
        const v = pwInput.value;
        if (!v) { pwError.style.display = 'block'; return; }
        pwError.style.display = 'none';
        sessionStorage.setItem(PW_KEY, v);
        closePwModal();
        decryptAll();
    });
    pwCancel.addEventListener('click', () => { closePwModal(); });
    pwInput.addEventListener('keydown', (e) => { if (e.key === 'Enter') pwConfirm.click(); });


    async function decryptAll() {
        const blocks = document.querySelectorAll('.code-content');
        if (blocks.length === 0) return;

        if (!havePassword()) {
            openPwModal();
            return;
        }

        const pw = getPassword();
        for (const el of blocks) {
            const packet = el.getAttribute('data-enc') || '';
            try {
                if (!packet) continue;
                const text = await aesDecrypt(packet, pw);
                el.textContent = text;
            } catch (e) {
                console.error("Decryption failed for an item:", e);
                el.textContent = '•••• Decryption Failed ••••';
            }
        }
    }
    
    // Decrypt on page load if there are search results
    window.addEventListener('load', decryptAll);

</script>
</body>
</html>
