<!-- VAULT ZERO-KNOWLEDGE THEME -->
<style>
    body { background-color: #0a0a0a !important; color: #f8f9fa !important; font-family: 'Inter', sans-serif; }
    .vault-card { background-color: #121212; border: 1px solid #222; transition: all 0.3s ease; }
    .vault-card:hover { border-color: #00ff66; box-shadow: 0 0 20px rgba(0, 255, 102, 0.15); transform: translateY(-3px); }
    .pw-field { font-family: 'Courier New', monospace; letter-spacing: 2px; }
    .navbar { display: none !important; }
    .sidebar { border-right: 1px solid #222 !important; }
    .glass-modal { background: rgba(18, 18, 18, 0.95); backdrop-filter: blur(10px); border: 1px solid #333; }
    .neon-text { text-shadow: 0 0 10px rgba(0, 255, 102, 0.5); }
    #itemsGrid { min-height: 50vh; }
    .matrix-loader { color: #00ff66; font-family: monospace; letter-spacing: 5px; }
</style>

<div class="container-fluid py-4" id="vaultContainer">
    <!-- Header -->
    <div class="d-flex justify-content-between align-items-center border-bottom border-dark pb-3 mb-4">
        <div>
            <h2 class="fw-bold mb-0 text-success neon-text"><i class="fa-solid fa-server me-2"></i> Vault Command</h2>
            <p class="text-secondary small mb-0"><i class="fa-solid fa-lock text-success"></i> Zero-Knowledge E2E Encryption Active.</p>
        </div>
        <div class="d-flex gap-2">
            <button class="btn btn-success fw-bold px-4" data-bs-toggle="modal" data-bs-target="#addItemModal">
                <i class="fa-solid fa-plus me-1"></i> Add Secret
            </button>
            
            <button class="btn btn-outline-warning" onclick="lockVault()">
                <i class="fa-solid fa-lock"></i> Lock
            </button>
            <button class="btn btn-outline-danger" data-bs-toggle="modal" data-bs-target="#hardResetModal" title="Wipe Vault">
                <i class="fa-solid fa-skull"></i>
            </button>
        </div>
    </div>

    <!-- Items Grid (Rendered via JS) -->
    <div id="loadingSec" class="text-center py-5">
        <h3 class="matrix-loader">DECRYPTING...</h3>
    </div>
    
    <div id="emptySec" class="text-center py-5 d-none">
        <i class="fa-solid fa-vault fa-3x text-secondary opacity-25 mb-3"></i>
        <h5 class="text-secondary">Vault is empty.</h5>
        <p class="text-muted small">Store your critical credentials securely.</p>
    </div>

    <div class="row g-3" id="itemsGrid"></div>
</div>

<!-- Add Modal -->
<div class="modal fade" id="addItemModal" tabindex="-1" data-bs-backdrop="static">
    <div class="modal-dialog">
        <div class="modal-content glass-modal text-light shadow-lg">
            <div class="modal-header border-bottom border-secondary">
                <h5 class="modal-title fw-bold"><i class="fa-solid fa-plus text-success me-2"></i> Vault Entry</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form id="vaultAddForm" data-no-pjax="true">
                <div class="modal-body p-4">
                    <div class="mb-3">
                        <label class="small text-secondary fw-bold text-uppercase mb-1">Title / Website</label>
                        <input type="text" name="title" class="form-control bg-black text-white border-secondary" required placeholder="eg. Google Account">
                    </div>
                    <div class="mb-3">
                        <label class="small text-secondary fw-bold text-uppercase mb-1">Username / Email (Optional)</label>
                        <input type="text" name="username" class="form-control bg-black text-white border-secondary">
                    </div>
                    <div class="row mb-3">
                        <div class="col-6">
                            <label class="small text-secondary fw-bold text-uppercase mb-1">Category</label>
                            <select name="category" class="form-select bg-black text-white border-secondary">
                                <option value="personal">Personal</option>
                                <option value="work">Work</option>
                                <option value="finance">Finance</option>
                                <option value="server">Server</option>
                                <option value="others">Others</option>
                            </select>
                        </div>
                        <div class="col-6">
                            <label class="small text-secondary fw-bold text-uppercase mb-1">Icon</label>
                            <select name="icon" class="form-select bg-black text-white border-secondary" style="font-family: 'Font Awesome 6 Free', sans-serif; font-weight: 900;">
                                <option value="fa-solid fa-key">&#xf084; Key</option>
                                <option value="fa-solid fa-lock">&#xf023; Lock</option>
                                <option value="fa-solid fa-credit-card">&#xf09d; Credit Card</option>
                                <option value="fa-solid fa-server">&#xf233; Server</option>
                                <option value="fa-solid fa-envelope">&#xf0e0; Envelope</option>
                                <option value="fa-solid fa-wallet">&#xf555; Wallet</option>
                            </select>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="small text-secondary fw-bold text-uppercase mb-1">Password</label>
                        <div class="input-group">
                            <input type="password" name="password" id="addPwField" class="form-control bg-black text-success border-secondary" required>
                            <button class="btn btn-outline-secondary" type="button" onclick="toggleVis('addPwField')"><i class="fa-solid fa-eye"></i></button>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="small text-secondary fw-bold text-uppercase mb-1">Secure Notes (Optional)</label>
                        <textarea name="notes" class="form-control bg-black text-white border-secondary" rows="3"></textarea>
                    </div>
                </div>
                <div class="modal-footer border-top border-secondary bg-black">
                    <button type="submit" id="addSubmitBtn" class="btn btn-success fw-bold px-4">Encrypt & Save</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Modal -->
<div class="modal fade" id="editItemModal" tabindex="-1" data-bs-backdrop="static">
    <div class="modal-dialog">
        <div class="modal-content glass-modal text-light shadow-lg">
            <div class="modal-header border-bottom border-secondary">
                <h5 class="modal-title fw-bold"><i class="fa-solid fa-pen text-warning me-2"></i> Edit Entry</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form id="vaultEditForm" data-no-pjax="true">
                <input type="hidden" name="id" id="editId">
                <div class="modal-body p-4">
                    <div class="mb-3">
                        <label class="small text-secondary fw-bold text-uppercase mb-1">Title</label>
                        <input type="text" name="title" id="editTitle" class="form-control bg-black text-white border-secondary" required>
                    </div>
                    <div class="mb-3">
                        <label class="small text-secondary fw-bold text-uppercase mb-1">Username</label>
                        <input type="text" name="username" id="editUsername" class="form-control bg-black text-white border-secondary">
                    </div>
                    <div class="row mb-3">
                        <div class="col-6">
                            <label class="small text-secondary fw-bold text-uppercase mb-1">Category</label>
                            <select name="category" id="editCategory" class="form-select bg-black text-white border-secondary">
                                <option value="personal">Personal</option>
                                <option value="work">Work</option>
                                <option value="finance">Finance</option>
                                <option value="server">Server</option>
                                <option value="others">Others</option>
                            </select>
                        </div>
                        <div class="col-6">
                            <label class="small text-secondary fw-bold text-uppercase mb-1">Icon</label>
                            <select name="icon" id="editIcon" class="form-select bg-black text-white border-secondary" style="font-family: 'Font Awesome 6 Free', sans-serif; font-weight: 900;">
                                <option value="fa-solid fa-key">&#xf084; Key</option>
                                <option value="fa-solid fa-lock">&#xf023; Lock</option>
                                <option value="fa-solid fa-credit-card">&#xf09d; Credit Card</option>
                                <option value="fa-solid fa-server">&#xf233; Server</option>
                                <option value="fa-solid fa-envelope">&#xf0e0; Envelope</option>
                                <option value="fa-solid fa-wallet">&#xf555; Wallet</option>
                            </select>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="small text-secondary fw-bold text-uppercase mb-1">Password</label>
                        <div class="input-group">
                            <input type="password" name="password" id="editPwField" class="form-control bg-black text-warning border-secondary" required>
                            <button class="btn btn-outline-secondary" type="button" onclick="toggleVis('editPwField')"><i class="fa-solid fa-eye"></i></button>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="small text-secondary fw-bold text-uppercase mb-1">Secure Notes</label>
                        <textarea name="notes" id="editNotes" class="form-control bg-black text-white border-secondary" rows="3"></textarea>
                    </div>
                </div>
                <div class="modal-footer border-top border-secondary bg-black">
                    <button type="submit" id="editSubmitBtn" class="btn btn-warning text-dark fw-bold px-4">Encrypt & Update</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Hard Reset Modal -->
<div class="modal fade" id="hardResetModal" tabindex="-1" data-bs-backdrop="static">
    <div class="modal-dialog">
        <div class="modal-content glass-modal text-light border-danger shadow-lg">
            <div class="modal-header border-bottom border-danger">
                <h5 class="modal-title fw-bold text-danger"><i class="fa-solid fa-skull me-2"></i> VAULT DESTRUCTION</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form id="vaultResetForm" data-no-pjax="true">
                <div class="modal-body p-4 text-center">
                    <p class="text-white fw-bold">This will permanently destroy the vault cryptography and all data.</p>
                    <div class="mb-3 text-start">
                        <label class="small text-secondary fw-bold text-uppercase mb-1">Type 'RESET VAULT' to confirm</label>
                        <input type="text" name="reset_text" class="form-control bg-black text-danger border-danger fw-bold text-center" placeholder="RESET VAULT" required>
                    </div>
                    <div class="mb-3 text-start">
                        <label class="small text-secondary fw-bold text-uppercase mb-1">Master Password</label>
                        <input type="password" id="resetMp" class="form-control bg-black text-warning border-danger text-center" required>
                    </div>
                </div>
                <div class="modal-footer border-top border-danger bg-black justify-content-center">
                    <button type="submit" class="btn btn-danger fw-bold px-4 w-100">DESTROY VAULT DATA</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// --- Embedded Data from Server ---
const encryptedItemsDb = <?= json_encode($items) ?>;

// --- Security Context ---
const masterPassword = sessionStorage.getItem('vault_mp');
const encSaltHex = sessionStorage.getItem('vault_enc_salt');
let aesKey = null;
let decryptedItems = [];

// If JS lost context but server session is alive -> enforce lock
if (!masterPassword || !encSaltHex) {
    lockVault();
}

// --- Crypto Engine ---
async function hashSHA256(str) {
    const buf = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(str));
    return Array.from(new Uint8Array(buf)).map(b => b.toString(16).padStart(2, '0')).join('');
}

async function getEncryptionKey(mp, saltHex) {
    const enc = new TextEncoder();
    const keyMaterial = await crypto.subtle.importKey(
        "raw", enc.encode(mp), { name: "PBKDF2" }, false, ["deriveBits", "deriveKey"]
    );
    const saltBuffer = new Uint8Array(saltHex.match(/.{1,2}/g).map(byte => parseInt(byte, 16)));
    return await crypto.subtle.deriveKey(
        { name: "PBKDF2", salt: saltBuffer, iterations: 100000, hash: "SHA-256" },
        keyMaterial, { name: "AES-GCM", length: 256 }, false, ["encrypt", "decrypt"]
    );
}

async function encryptData(jsonObject, key) {
    const iv = crypto.getRandomValues(new Uint8Array(12));
    const enc = new TextEncoder();
    const encoded = enc.encode(JSON.stringify(jsonObject));
    const cipherBuffer = await crypto.subtle.encrypt({ name: "AES-GCM", iv: iv }, key, encoded);
    
    const cipherHex = Array.from(new Uint8Array(cipherBuffer)).map(b => b.toString(16).padStart(2, '0')).join('');
    const ivHex = Array.from(iv).map(b => b.toString(16).padStart(2, '0')).join('');
    return { cipher_data: cipherHex, iv: ivHex };
}

async function decryptData(cipherHex, ivHex, key) {
    try {
        const iv = new Uint8Array(ivHex.match(/.{1,2}/g).map(byte => parseInt(byte, 16)));
        const cipherBuffer = new Uint8Array(cipherHex.match(/.{1,2}/g).map(byte => parseInt(byte, 16)));
        const decryptedBuffer = await crypto.subtle.decrypt({ name: "AES-GCM", iv: iv }, key, cipherBuffer);
        return JSON.parse(new TextDecoder().decode(decryptedBuffer));
    } catch (e) {
        return null; // Corrupted or wrong key
    }
}

// --- Initialization ---
async function initVault() {
    try {
        aesKey = await getEncryptionKey(masterPassword, encSaltHex);
        
        for (let row of encryptedItemsDb) {
            const data = await decryptData(row.cipher_data, row.iv, aesKey);
            if (data) {
                decryptedItems.push({ id: row.id, ...data });
            }
        }
        
        document.getElementById('loadingSec').classList.add('d-none');
        renderGrid();
        
    } catch(e) {
        console.error("Init failed", e);
        lockVault();
    }
}

// Ensure execution flow once DOM is ready
if(masterPassword) {
    initVault();
}

// --- UI Rendering ---
function renderGrid() {
    const grid = document.getElementById('itemsGrid');
    grid.innerHTML = '';
    
    if (decryptedItems.length === 0) {
        document.getElementById('emptySec').classList.remove('d-none');
        return;
    }
    
    // Sort alphabetically by title
    decryptedItems.sort((a,b) => a.title.localeCompare(b.title));

    decryptedItems.forEach(i => {
        const titleSafe = escapeHtml(i.title);
        const userSafe = escapeHtml(i.username || '');
        const catSafe = escapeHtml(i.category || 'personal');
        const iconSafe = escapeHtml(i.icon || 'fa-solid fa-key');
        const notesSafe = escapeHtml(i.notes || '');
        // We will store index to fetch the item when editing instead of embedding data in HTML
        const itemIdx = decryptedItems.indexOf(i);

        let userHtml = '';
        if(i.username) {
            userHtml = `
            <div class="mb-2">
                <small class="text-secondary d-block text-uppercase" style="font-size:10px;">Username</small>
                <div class="d-flex justify-content-between bg-dark px-2 py-1 rounded">
                    <span class="text-light" style="font-family: monospace;">${userSafe}</span>
                    <button class="btn btn-sm text-success p-0" onclick="copyToClipboard('${userSafe}')"><i class="fa-regular fa-copy"></i></button>
                </div>
            </div>`;
        }

        let notesHtml = '';
        if(i.notes) {
            notesHtml = `
            <div class="mt-3 pt-3 border-top border-dark">
                <small class="text-secondary d-block text-uppercase mb-1" style="font-size:10px;">Secure Notes</small>
                <p class="text-muted small mb-0 p-2 bg-dark rounded" style="font-family: monospace; font-size: 11px; white-space: pre-wrap;">${notesSafe}</p>
            </div>`;
        }

        const html = `
        <div class="col-md-6 col-lg-4">
            <div class="card vault-card h-100 shadow-sm rounded-3">
                <div class="card-body p-4">
                    <div class="d-flex justify-content-between align-items-start mb-3">
                        <div>
                            <h5 class="fw-bold text-white mb-1"><i class="${iconSafe} text-success me-2"></i> ${titleSafe}</h5>
                            <span class="badge bg-dark border border-secondary text-secondary" style="font-size: 0.65rem; text-transform: uppercase;">${catSafe}</span>
                        </div>
                        <div class="dropdown">
                            <button class="btn btn-sm btn-link text-secondary p-0 shadow-none border-0" data-bs-toggle="dropdown"><i class="fa-solid fa-ellipsis-vertical"></i></button>
                            <ul class="dropdown-menu dropdown-menu-dark shadow-sm">
                                <li><button class="dropdown-item" onclick="openEdit(${itemIdx})"><i class="fa-solid fa-pen text-warning me-2"></i> Edit</button></li>
                                <li><button class="dropdown-item text-danger" onclick="deleteItem(${i.id})"><i class="fa-solid fa-trash me-2"></i> Delete</button></li>
                            </ul>
                        </div>
                    </div>
                    ${userHtml}
                    <div class="mb-2">
                        <small class="text-secondary d-block text-uppercase" style="font-size:10px;">Password</small>
                        <div class="d-flex justify-content-between bg-dark px-2 py-1 rounded">
                            <span class="text-muted fw-bold pw-field" id="pwMask_${i.id}">••••••••</span>
                            <div class="d-flex gap-2">
                                <button class="btn btn-sm text-info p-0" onclick="revealPassword(${i.id}, ${itemIdx})"><i class="fa-solid fa-eye"></i></button>
                                <button class="btn btn-sm text-success p-0" onclick="copyPassword(${itemIdx})"><i class="fa-regular fa-copy"></i></button>
                            </div>
                        </div>
                    </div>
                    ${notesHtml}
                </div>
            </div>
        </div>`;
        grid.insertAdjacentHTML('beforeend', html);
    });
}

// --- Utilities ---
function escapeHtml(unsafe) {
    return unsafe.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
}

function toggleVis(fieldId) {
    const f = document.getElementById(fieldId);
    f.type = f.type === 'password' ? 'text' : 'password';
}

let revealTimers = {};
function revealPassword(id, idx) {
    const el = document.getElementById('pwMask_' + id);
    if(revealTimers[id]) clearTimeout(revealTimers[id]);
    
    el.innerText = decryptedItems[idx].password;
    el.classList.replace('text-muted', 'text-success');
    
    revealTimers[id] = setTimeout(() => {
        el.innerText = '••••••••';
        el.classList.replace('text-success', 'text-muted');
    }, 5000);
}

function copyPassword(idx) {
    copyToClipboard(decryptedItems[idx].password);
}

function copyToClipboard(txt) {
    navigator.clipboard.writeText(txt).then(() => {
        if(window.OTIS) window.OTIS.toast('Copied', 'Copied to clipboard', 'info');
        else alert('Copied!');
    });
}

function lockVault() {
    sessionStorage.removeItem('vault_mp');
    sessionStorage.removeItem('vault_enc_salt');
    fetch('<?= BASE_URL ?>/vault/lock').then(() => window.location.reload());
}

// Anti-Idle Auto-Lock
let idleTime = 0;
setInterval(() => {
    idleTime++;
    if(idleTime > 300) lockVault(); // 5 minutes
}, 1000);
['mousemove','keypress','scroll','click'].forEach(evt => document.addEventListener(evt, () => idleTime = 0));


// --- CRUD Actions ---

document.getElementById('vaultAddForm').addEventListener('submit', async function(e) {
    e.preventDefault();
    document.getElementById('addSubmitBtn').disabled = true;
    
    const obj = Object.fromEntries(new FormData(this));
    
    // Encrypt payload
    const encResult = await encryptData(obj, aesKey);

    fetch('<?= BASE_URL ?>/vault/addItem', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(encResult)
    }).then(r => r.json()).then(r => {
        if(r.success) window.location.reload();
    });
});

function openEdit(idx) {
    const item = decryptedItems[idx];
    document.getElementById('editId').value = item.id;
    document.getElementById('editTitle').value = item.title;
    document.getElementById('editUsername').value = item.username || '';
    document.getElementById('editPwField').value = item.password;
    document.getElementById('editNotes').value = item.notes || '';
    document.getElementById('editCategory').value = item.category || 'personal';
    document.getElementById('editIcon').value = item.icon || 'fa-solid fa-key';
    new bootstrap.Modal(document.getElementById('editItemModal')).show();
}

document.getElementById('vaultEditForm').addEventListener('submit', async function(e) {
    e.preventDefault();
    document.getElementById('editSubmitBtn').disabled = true;
    
    const fd = new FormData(this);
    const id = fd.get('id');
    fd.delete('id'); // Remove from encrypted payload
    const obj = Object.fromEntries(fd);
    
    const encResult = await encryptData(obj, aesKey);
    encResult.id = id;

    fetch('<?= BASE_URL ?>/vault/editItem', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(encResult)
    }).then(r => r.json()).then(r => {
        if(r.success) window.location.reload();
    });
});

function deleteItem(id) {
    if(!confirm('DANGER: Irreversible deletion! Proceed?')) return;
    fetch('<?= BASE_URL ?>/vault/deleteItem', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({id: id})
    }).then(r => r.json()).then(r => {
        if(r.success) window.location.reload();
    });
}

document.getElementById('vaultResetForm')?.addEventListener('submit', async function(e) {
    e.preventDefault();
    const mp = document.getElementById('resetMp').value;
    const txt = document.querySelector('input[name="reset_text"]').value;
    const auth_password = await hashSHA256("auth" + mp);

    fetch('<?= BASE_URL ?>/vault/hardReset', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({ auth_password, reset_text: txt })
    }).then(res => res.json()).then(res => {
        if(res.success) {
            sessionStorage.removeItem('vault_mp');
            sessionStorage.removeItem('vault_enc_salt');
            window.location.href = res.redirect;
        } else alert(res.message);
    });
});
</script>
