{% extends "base.html" %}

{% block title %}Generate Credentials - Stegasoo{% endblock %}

{% block content %}
<div class="row justify-content-center">
    <div class="col-lg-8">
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0"><i class="bi bi-key-fill me-2"></i>Generate Credentials</h5>
            </div>
            <div class="card-body">
                {% if not generated %}
                <!-- Generation Form -->
                <form method="POST">
                    <div class="mb-4">
                        <label class="form-label">Words per Passphrase</label>
                        <input type="range" class="form-range" name="words_per_passphrase" 
                               min="{{ min_passphrase_words }}" max="12" value="{{ default_passphrase_words }}" id="wordsRange">
                        <div class="d-flex justify-content-between small text-muted">
                            <span>{{ min_passphrase_words }} (~33 bits)</span>
                            <span id="wordsValue" class="text-primary fw-bold">{{ default_passphrase_words }} words (~44 bits)</span>
                            <span>12 (132 bits)</span>
                        </div>
                        <div class="form-text">
                            <i class="bi bi-shield-check me-1"></i>
                            Recommended: <strong>{{ recommended_passphrase_words }}+ words</strong> for good security
                        </div>
                    </div>
                    
                    <hr>
                    
                    <h6 class="text-muted mb-3">SECURITY FACTORS <span class="text-warning small">(select at least one)</span></h6>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" name="use_pin" 
                                       id="usePinCheck" checked>
                                <label class="form-check-label" for="usePinCheck">
                                    <i class="bi bi-123 me-1"></i> Generate PIN
                                </label>
                            </div>
                            <div class="mt-2" id="pinOptions">
                                <label class="form-label small">PIN Length</label>
                                <select name="pin_length" class="form-select form-select-sm">
                                    <option value="6" selected>6 digits (~20 bits)</option>
                                    <option value="7">7 digits (~23 bits)</option>
                                    <option value="8">8 digits (~26 bits)</option>
                                    <option value="9">9 digits (~30 bits)</option>
                                </select>
                            </div>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" name="use_rsa" 
                                       id="useRsaCheck">
                                <label class="form-check-label" for="useRsaCheck">
                                    <i class="bi bi-file-earmark-lock me-1"></i> Generate RSA Key
                                </label>
                            </div>
                            <div class="mt-2 d-none" id="rsaOptions">
                                <label class="form-label small">Key Size</label>
                                <select name="rsa_bits" class="form-select form-select-sm" id="rsaBitsSelect">
                                    <option value="2048" selected>2048 bits (~128 bits entropy)</option>
                                    <option value="3072">3072 bits (~128 bits entropy)</option>
                                    <option value="4096">4096 bits (~128 bits entropy)</option>
                                </select>
                                <div class="form-text text-warning d-none" id="rsaQrWarning">
                                    <i class="bi bi-exclamation-triangle me-1"></i>QR code unavailable for keys &gt;3072 bits
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <button type="submit" class="btn btn-primary btn-lg w-100 mt-3">
                        <i class="bi bi-shuffle me-2"></i>Generate Credentials
                    </button>
                </form>
                
                {% else %}
                <!-- Generated Credentials Display -->
                <div class="alert alert-warning">
                    <i class="bi bi-exclamation-triangle me-2"></i>
                    <strong>Memorize these credentials!</strong> They will not be shown again.
                    <br><small>Do not screenshot or save to an unencrypted file.</small>
                </div>
                
                {% if pin %}
                <div class="mb-4">
                    <h6 class="text-muted"><i class="bi bi-123 me-2"></i>STATIC PIN</h6>
                    <div class="text-center">
                        <div class="pin-container d-inline-block">
                            <div class="pin-digits-row" id="pinDigits">
                                {% for digit in pin %}
                                <span class="pin-digit-box">{{ digit }}</span>
                                {% endfor %}
                            </div>
                            <div class="pin-buttons mt-3">
                                <button type="button" class="btn btn-sm btn-outline-secondary me-2" onclick="togglePinVisibility()">
                                    <i class="bi bi-eye-slash" id="pinToggleIcon"></i>
                                    <span id="pinToggleText">Hide</span>
                                </button>
                                <button type="button" class="btn btn-sm btn-outline-secondary" onclick="copyPin()">
                                    <i class="bi bi-clipboard" id="pinCopyIcon"></i>
                                    <span id="pinCopyText">Copy</span>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                {% endif %}
                
                <div class="mb-4">
                    <h6 class="text-muted">
                        <i class="bi bi-chat-quote me-2"></i>PASSPHRASE
                    </h6>
                    
                    <div class="passphrase-container">
                        <div class="passphrase-display" id="passphraseDisplay">
                            <code class="passphrase-text">{{ passphrase }}</code>
                        </div>
                        
                        <div class="passphrase-buttons mt-3">
                            <button type="button" class="btn btn-sm btn-outline-secondary me-2" onclick="togglePassphraseVisibility()">
                                <i class="bi bi-eye-slash" id="passphraseToggleIcon"></i>
                                <span id="passphraseToggleText">Hide</span>
                            </button>
                            <button type="button" class="btn btn-sm btn-outline-secondary me-2" onclick="copyPassphrase()">
                                <i class="bi bi-clipboard" id="passphraseCopyIcon"></i>
                                <span id="passphraseCopyText">Copy</span>
                            </button>
                            <button type="button" class="btn btn-sm btn-outline-primary" onclick="toggleMemoryAid()">
                                <i class="bi bi-lightbulb" id="memoryAidIcon"></i>
                                <span id="memoryAidText">Memory Aid</span>
                            </button>
                        </div>
                    </div>
                    
                    <!-- Memory Aid Story -->
                    <div class="memory-aid-container mt-3 d-none" id="memoryAidContainer">
                        <div class="card bg-dark border-primary">
                            <div class="card-header bg-primary text-white">
                                <i class="bi bi-book me-2"></i>Memory Story
                            </div>
                            <div class="card-body">
                                <p class="memory-story mb-3" id="memoryStory">
                                    <!-- Story will be generated by JavaScript -->
                                </p>
                                <div class="form-text">
                                    <i class="bi bi-info-circle me-1"></i>
                                    This story is generated from your passphrase to help you remember it.
                                    The words appear in order within the narrative.
                                </div>
                                <button type="button" class="btn btn-sm btn-outline-light mt-2" onclick="regenerateStory()">
                                    <i class="bi bi-arrow-repeat me-1"></i>Generate Different Story
                                </button>
                            </div>
                        </div>
                    </div>
                    
                    <div class="alert alert-info mt-3 mb-0">
                        <small class="text-muted">
                            ({{ words_per_passphrase }} words = ~{{ passphrase_entropy }} bits entropy)
                        </small>
                    </div>
                </div>
                
                {% if rsa_key_pem %}
                <div class="mb-4">
                    <h6 class="text-muted"><i class="bi bi-file-earmark-lock me-2"></i>RSA PRIVATE KEY ({{ rsa_bits }} bits)</h6>
                    
                    <ul class="nav nav-tabs" role="tablist">
                        <li class="nav-item" role="presentation">
                            <button class="nav-link active" data-bs-toggle="tab" data-bs-target="#keyTextTab" type="button">
                                <i class="bi bi-file-text me-1"></i>PEM Text
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" data-bs-toggle="tab" data-bs-target="#keyDownloadTab" type="button">
                                <i class="bi bi-download me-1"></i>Download
                            </button>
                        </li>
                        {% if has_qrcode and qr_token %}
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" data-bs-toggle="tab" data-bs-target="#keyQrTab" type="button">
                                <i class="bi bi-qr-code me-1"></i>QR Code
                            </button>
                        </li>
                        {% endif %}
                    </ul>
                    
                    <div class="tab-content border border-top-0 rounded-bottom p-3 bg-dark">
                        <!-- PEM Text Tab -->
                        <div class="tab-pane fade show active" id="keyTextTab" role="tabpanel">
                            <pre class="bg-black p-2 rounded small mb-2" style="max-height: 200px; overflow-y: auto;"><code id="rsaKeyDisplay">{{ rsa_key_pem }}</code></pre>
                            <button class="btn btn-sm btn-outline-light" 
                                    onclick="navigator.clipboard.writeText(document.getElementById('rsaKeyDisplay').textContent)">
                                <i class="bi bi-clipboard me-1"></i>Copy to Clipboard
                            </button>
                        </div>
                        
                        <!-- Download Tab -->
                        <div class="tab-pane fade" id="keyDownloadTab" role="tabpanel">
                            <form action="{{ url_for('download_key') }}" method="POST" class="row g-2 align-items-end">
                                <input type="hidden" name="key_pem" value="{{ rsa_key_pem }}">
                                <div class="col-md-8">
                                    <label class="form-label small">Password to encrypt the key file</label>
                                    <input type="password" name="key_password" class="form-control" 
                                           placeholder="Min 8 characters" minlength="8" required>
                                </div>
                                <div class="col-md-4">
                                    <button type="submit" class="btn btn-primary w-100">
                                        <i class="bi bi-download me-1"></i>Download .pem
                                    </button>
                                </div>
                            </form>
                            <div class="form-text mt-2">
                                The downloaded file will be password-protected (AES-256 encrypted).
                            </div>
                        </div>
                        
                        {% if has_qrcode and qr_token %}
                        <!-- QR Code Tab -->
                        <div class="tab-pane fade" id="keyQrTab" role="tabpanel">
                            <div class="text-center">
                                <p class="small text-muted mb-3">
                                    Scan this QR code to transfer the RSA key to another device.
                                    <br><strong>Warning:</strong> This is the unencrypted private key!
                                </p>
                                <div class="qr-container d-inline-block p-3 bg-white rounded mb-3">
                                    <img src="{{ url_for('generate_qr', token=qr_token) }}" 
                                         alt="RSA Key QR Code" 
                                         class="img-fluid"
                                         style="max-width: 300px;"
                                         id="qrCodeImage">
                                </div>
                                <div>
                                    <a href="{{ url_for('generate_qr_download', token=qr_token) }}" 
                                       class="btn btn-outline-primary">
                                        <i class="bi bi-download me-1"></i>Download QR Code
                                    </a>
                                    <button class="btn btn-outline-secondary ms-2" onclick="printQrCode()">
                                        <i class="bi bi-printer me-1"></i>Print
                                    </button>
                                </div>
                                <div class="alert alert-warning small mt-3 mb-0 text-start">
                                    <i class="bi bi-shield-exclamation me-1"></i>
                                    <strong>Security note:</strong> The QR code contains your unencrypted private key.
                                    Only scan in a secure environment. Consider using the password-protected download instead.
                                    {% if rsa_bits >= 4096 %}
                                    <br><br>
                                    <i class="bi bi-exclamation-triangle me-1"></i>
                                    <strong>4096-bit keys</strong> produce very dense QR codes. If scanning fails, 
                                    use the PEM text or download options instead.
                                    {% endif %}
                                </div>
                            </div>
                        </div>
                        {% endif %}
                    </div>
                </div>
                {% endif %}
                
                <div class="mb-4">
                    <h6 class="text-muted"><i class="bi bi-shield-check me-2"></i>SECURITY SUMMARY</h6>
                    <div class="row text-center">
                        <div class="col">
                            <div class="p-2 bg-dark rounded">
                                <div class="small text-muted">Passphrase</div>
                                <div class="fs-5 text-info">{{ passphrase_entropy }} bits</div>
                                <div class="small text-muted">{{ words_per_passphrase }} words</div>
                            </div>
                        </div>
                        {% if pin_entropy %}
                        <div class="col">
                            <div class="p-2 bg-dark rounded">
                                <div class="small text-muted">PIN</div>
                                <div class="fs-5 text-warning">{{ pin_entropy }} bits</div>
                            </div>
                        </div>
                        {% endif %}
                        {% if rsa_entropy %}
                        <div class="col">
                            <div class="p-2 bg-dark rounded">
                                <div class="small text-muted">RSA</div>
                                <div class="fs-5 text-primary">{{ rsa_entropy }} bits</div>
                            </div>
                        </div>
                        {% endif %}
                        <div class="col">
                            <div class="p-2 bg-dark rounded">
                                <div class="small text-muted">Total</div>
                                <div class="fs-5 text-success">{{ total_entropy }} bits</div>
                            </div>
                        </div>
                    </div>
                    <div class="form-text text-center mt-2">
                        + reference photo entropy (~80-256 bits)
                    </div>
                </div>
                
                <div class="d-grid gap-2">
                    <a href="{{ url_for('generate') }}" class="btn btn-outline-primary">
                        <i class="bi bi-arrow-repeat me-2"></i>Generate New Credentials
                    </a>
                    <a href="{{ url_for('encode_page') }}" class="btn btn-success">
                        <i class="bi bi-lock me-2"></i>Start Encoding
                    </a>
                </div>
                {% endif %}
            </div>
        </div>
        
        {% if not generated %}
        <div class="card mt-4">
            <div class="card-body">
                <h6 class="text-muted mb-3"><i class="bi bi-info-circle me-2"></i>About Credentials</h6>
                <ul class="small text-muted mb-0">
                    <li class="mb-2">
                        <strong>Passphrase</strong> is a single phrase you use each time
                    </li>
                    <li class="mb-2">
                        <strong>PIN</strong> is static and adds another factor both parties must know
                    </li>
                    <li class="mb-2">
                        <strong>RSA key</strong> adds asymmetric cryptography for additional security
                    </li>
                    <li class="mb-0">
                        You need <strong>at least one</strong> of PIN or RSA key (or both)
                    </li>
                </ul>
            </div>
        </div>
        {% endif %}
    </div>
</div>

<style>
.pin-container {
    background: linear-gradient(145deg, #1e1e2e 0%, #2d2d44 100%);
    border: 1px solid #ffc107;
    border-radius: 16px;
    padding: 1.5rem 2rem;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3), 0 0 40px rgba(255, 193, 7, 0.1);
}

.pin-digits-row {
    display: flex;
    justify-content: center;
    gap: 0.5rem;
}

.pin-digit-box {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 3rem;
    height: 3.5rem;
    background: rgba(0, 0, 0, 0.4);
    border: 1px solid rgba(255, 193, 7, 0.3);
    border-radius: 8px;
    font-family: 'Consolas', 'Monaco', monospace;
    font-size: 1.75rem;
    font-weight: bold;
    color: #ffc107;
    text-shadow: 0 0 10px rgba(255, 193, 7, 0.5);
    transition: filter 0.3s ease, transform 0.2s ease;
}

.pin-digit-box:hover {
    transform: translateY(-2px);
    border-color: rgba(255, 193, 7, 0.6);
}

.pin-digits-row.blurred .pin-digit-box {
    filter: blur(8px);
    user-select: none;
}

.pin-buttons .btn {
    min-width: 80px;
}

/* Passphrase Container */
.passphrase-container {
    background: linear-gradient(145deg, #1e1e2e 0%, #2d2d44 100%);
    border: 1px solid #0dcaf0;
    border-radius: 16px;
    padding: 1.5rem 2rem;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3), 0 0 40px rgba(13, 202, 240, 0.1);
}

.passphrase-display {
    background: rgba(0, 0, 0, 0.4);
    border: 1px solid rgba(13, 202, 240, 0.3);
    border-radius: 12px;
    padding: 1.5rem;
    text-align: center;
    transition: filter 0.3s ease;
}

.passphrase-display.blurred {
    filter: blur(8px);
    user-select: none;
}

.passphrase-text {
    font-family: 'Consolas', 'Monaco', monospace;
    font-size: 1.5rem;
    font-weight: bold;
    color: #0dcaf0;
    text-shadow: 0 0 10px rgba(13, 202, 240, 0.5);
    word-wrap: break-word;
    display: block;
    line-height: 1.6;
}

.passphrase-buttons {
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
    gap: 0.5rem;
}

.passphrase-buttons .btn {
    min-width: 100px;
}

/* Memory Aid */
.memory-story {
    font-size: 1.1rem;
    line-height: 1.8;
    color: #e9ecef;
}

.memory-story .passphrase-word {
    font-weight: bold;
    color: #0dcaf0;
    text-decoration: underline;
    text-decoration-style: wavy;
    text-decoration-color: rgba(13, 202, 240, 0.5);
}

/* Responsive */
@media (max-width: 576px) {
    .pin-container, .passphrase-container {
        padding: 1rem 1.25rem;
    }
    
    .pin-digit-box {
        width: 2.25rem;
        height: 2.75rem;
        font-size: 1.25rem;
    }
    
    .pin-digits-row {
        gap: 0.35rem;
    }
    
    .passphrase-text {
        font-size: 1.2rem;
    }
    
    .memory-story {
        font-size: 1rem;
    }
}
</style>
{% endblock %}

{% block scripts %}
<script>
// Words range slider
const wordsRange = document.getElementById('wordsRange');
const wordsValue = document.getElementById('wordsValue');

if (wordsRange) {
    wordsRange.addEventListener('input', function() {
        const bits = this.value * 11;
        wordsValue.textContent = `${this.value} words (~${bits} bits)`;
    });
}

// Toggle PIN/RSA options
const usePinCheck = document.getElementById('usePinCheck');
const useRsaCheck = document.getElementById('useRsaCheck');
const pinOptions = document.getElementById('pinOptions');
const rsaOptions = document.getElementById('rsaOptions');

if (usePinCheck) {
    usePinCheck.addEventListener('change', function() {
        pinOptions.classList.toggle('d-none', !this.checked);
    });
}

if (useRsaCheck) {
    useRsaCheck.addEventListener('change', function() {
        rsaOptions.classList.toggle('d-none', !this.checked);
    });
}

// RSA key size QR warning
const rsaBitsSelect = document.getElementById('rsaBitsSelect');
const rsaQrWarning = document.getElementById('rsaQrWarning');

if (rsaBitsSelect && rsaQrWarning) {
    rsaBitsSelect.addEventListener('change', function() {
        rsaQrWarning.classList.toggle('d-none', parseInt(this.value) <= 3072);
    });
}

// PIN visibility toggle
let pinHidden = false;
function togglePinVisibility() {
    const pinDigits = document.getElementById('pinDigits');
    const icon = document.getElementById('pinToggleIcon');
    const text = document.getElementById('pinToggleText');
    
    pinHidden = !pinHidden;
    
    if (pinHidden) {
        pinDigits.classList.add('blurred');
        icon.className = 'bi bi-eye';
        text.textContent = 'Show';
    } else {
        pinDigits.classList.remove('blurred');
        icon.className = 'bi bi-eye-slash';
        text.textContent = 'Hide';
    }
}

// Copy PIN
function copyPin() {
    const pin = '{{ pin|default("", true) }}';
    const icon = document.getElementById('pinCopyIcon');
    const text = document.getElementById('pinCopyText');
    
    navigator.clipboard.writeText(pin).then(() => {
        icon.className = 'bi bi-check';
        text.textContent = 'Copied!';
        setTimeout(() => {
            icon.className = 'bi bi-clipboard';
            text.textContent = 'Copy';
        }, 2000);
    });
}

// Passphrase visibility toggle
let passphraseHidden = false;
function togglePassphraseVisibility() {
    const display = document.getElementById('passphraseDisplay');
    const icon = document.getElementById('passphraseToggleIcon');
    const text = document.getElementById('passphraseToggleText');
    
    passphraseHidden = !passphraseHidden;
    
    if (passphraseHidden) {
        display.classList.add('blurred');
        icon.className = 'bi bi-eye';
        text.textContent = 'Show';
    } else {
        display.classList.remove('blurred');
        icon.className = 'bi bi-eye-slash';
        text.textContent = 'Hide';
    }
}

// Copy passphrase
function copyPassphrase() {
    const passphrase = '{{ passphrase|default("", true) }}';
    const icon = document.getElementById('passphraseCopyIcon');
    const text = document.getElementById('passphraseCopyText');
    
    navigator.clipboard.writeText(passphrase).then(() => {
        icon.className = 'bi bi-check';
        text.textContent = 'Copied!';
        setTimeout(() => {
            icon.className = 'bi bi-clipboard';
            text.textContent = 'Copy';
        }, 2000);
    });
}

// Memory Aid Story Generation
const passphrase = '{{ passphrase|default("", true) }}';
const passphraseWords = passphrase.split(' ').filter(w => w.length > 0);
let currentStoryTemplate = 0;

// Story templates - words are inserted in order
const storyTemplates = [
    // Adventure template
    words => `Once upon a time, a brave explorer named ${highlight(words[0])} set out on a quest. Along the way, they discovered a mysterious ${highlight(words[1])} hidden in an ancient ${highlight(words[2])}${words[3] ? `. With the help of a magical ${highlight(words[3])}` : ''}${words[4] ? `, they unlocked the secrets of the ${highlight(words[4])}` : ''}${words[5] ? ` and found the legendary ${highlight(words[5])}` : ''}. And they all lived happily ever after.`,
    
    // Detective template
    words => `Detective ${highlight(words[0])} was investigating a curious case involving a stolen ${highlight(words[1])}. The only clue was a ${highlight(words[2])} found at the scene${words[3] ? `. Suddenly, a witness mentioned seeing a suspicious ${highlight(words[3])}` : ''}${words[4] ? ` near the old ${highlight(words[4])}` : ''}${words[5] ? `. The case was solved when they discovered the ${highlight(words[5])} contained the answer` : ''}.`,
    
    // Science fiction template
    words => `In the year 2150, Captain ${highlight(words[0])} commanded the starship ${highlight(words[1])}. Their mission: to explore the ${highlight(words[2])} sector of space${words[3] ? ` where ancient ${highlight(words[3])} technology was rumored to exist` : ''}${words[4] ? `. The crew discovered a portal to the ${highlight(words[4])} dimension` : ''}${words[5] ? `, containing the mythical ${highlight(words[5])}` : ''}.`,
    
    // Restaurant template
    words => `Chef ${highlight(words[0])} opened a new restaurant called "The ${highlight(words[1])}." The signature dish featured ${highlight(words[2])} as the main ingredient${words[3] ? `, garnished with fresh ${highlight(words[3])}` : ''}${words[4] ? `. Customers loved the special ${highlight(words[4])} sauce` : ''}${words[5] ? ` served in a ${highlight(words[5])}-shaped bowl` : ''}.`,
    
    // Journey template
    words => `The journey began at ${highlight(words[0])} Mountain, where travelers would gather their ${highlight(words[1])} supplies. The path led through the ${highlight(words[2])} valley${words[3] ? `, past the ancient ${highlight(words[3])} ruins` : ''}${words[4] ? `, until reaching the sacred ${highlight(words[4])} temple` : ''}${words[5] ? ` where the golden ${highlight(words[5])} awaited` : ''}.`,
    
    // Music template  
    words => `${highlight(words[0])} was a talented musician who played the ${highlight(words[1])} in the city square. Their music sounded like ${highlight(words[2])}${words[3] ? ` mixed with ${highlight(words[3])}` : ''}${words[4] ? `. People said it reminded them of ${highlight(words[4])}` : ''}${words[5] ? ` during a beautiful ${highlight(words[5])} sunset` : ''}.`,
    
    // Inventor template
    words => `Professor ${highlight(words[0])} invented a revolutionary device powered by ${highlight(words[1])} energy. It could transform ordinary ${highlight(words[2])}${words[3] ? ` into magnificent ${highlight(words[3])}` : ''}${words[4] ? `. The invention won the prestigious ${highlight(words[4])} Prize` : ''}${words[5] ? ` and was displayed at the ${highlight(words[5])} Museum` : ''}.`,
    
    // Garden template
    words => `In the enchanted garden, ${highlight(words[0])} flowers bloomed beside a ${highlight(words[1])} fountain. The garden keeper planted ${highlight(words[2])} seeds${words[3] ? ` near the ${highlight(words[3])} hedge` : ''}${words[4] ? `, creating a path to the ${highlight(words[4])} arbor` : ''}${words[5] ? ` where butterflies gathered on ${highlight(words[5])} petals` : ''}.`
];

function highlight(word) {
    return `<span class="passphrase-word">${word}</span>`;
}

function generateStory(templateIndex = null) {
    if (passphraseWords.length === 0) return '';
    
    if (templateIndex === null) {
        templateIndex = currentStoryTemplate;
    }
    
    const template = storyTemplates[templateIndex % storyTemplates.length];
    return template(passphraseWords);
}

function toggleMemoryAid() {
    const container = document.getElementById('memoryAidContainer');
    const icon = document.getElementById('memoryAidIcon');
    const text = document.getElementById('memoryAidText');
    
    if (container.classList.contains('d-none')) {
        // Show memory aid
        container.classList.remove('d-none');
        icon.className = 'bi bi-lightbulb-fill';
        text.textContent = 'Hide Aid';
        
        // Generate initial story
        document.getElementById('memoryStory').innerHTML = generateStory();
    } else {
        // Hide memory aid
        container.classList.add('d-none');
        icon.className = 'bi bi-lightbulb';
        text.textContent = 'Memory Aid';
    }
}

function regenerateStory() {
    currentStoryTemplate = (currentStoryTemplate + 1) % storyTemplates.length;
    document.getElementById('memoryStory').innerHTML = generateStory(currentStoryTemplate);
}

// Print QR code
function printQrCode() {
    const qrImg = document.getElementById('qrCodeImage');
    if (!qrImg) return;
    
    const printWindow = window.open('', '_blank');
    printWindow.document.write(`
        <!DOCTYPE html>
        <html>
        <head>
            <title>Stegasoo RSA Key QR Code</title>
            <style>
                body { 
                    display: flex; 
                    flex-direction: column;
                    align-items: center; 
                    justify-content: center; 
                    min-height: 100vh;
                    margin: 0;
                    font-family: sans-serif;
                }
                img { max-width: 400px; }
                .warning {
                    margin-top: 20px;
                    padding: 10px;
                    border: 2px solid #ff9800;
                    background: #fff3e0;
                    max-width: 400px;
                    text-align: center;
                    font-size: 12px;
                }
            </style>
        </head>
        <body>
            <h2>Stegasoo RSA Private Key</h2>
            <img src="${qrImg.src}" alt="RSA Key QR Code">
            <div class="warning">
                <strong>⚠️ SECURITY WARNING</strong><br>
                This QR code contains your unencrypted RSA private key.<br>
                Store securely and destroy after use.
            </div>
            <script>window.onload = function() { window.print(); }<\/script>
        </body>
        </html>
    `);
    printWindow.document.close();
}
</script>
{% endblock %}
