{% extends "base.html" %}

{% block title %}Decode Message - Stegasoo{% endblock %}

{% block content %}
<style>
/* Accordion styling */
.step-accordion .accordion-button {
    background: rgba(35, 45, 55, 0.8);
    color: #fff;
    padding: 0.75rem 1rem;
    border-left: 3px solid rgba(255, 230, 153, 0.3);
    border-bottom: 1px solid rgba(255, 255, 255, 0.08);
    transition: all 0.3s ease;
}
.step-accordion .accordion-button:hover {
    background: rgba(45, 55, 65, 0.9);
    border-left-color: rgba(255, 230, 153, 0.5);
}
.step-accordion .accordion-button:not(.collapsed) {
    background: linear-gradient(90deg, rgba(255, 230, 153, 0.12) 0%, rgba(40, 50, 60, 0.85) 40%, rgba(40, 50, 60, 0.85) 100%);
    color: #fff;
    box-shadow: inset 0 1px 0 rgba(255, 230, 153, 0.1);
    border-left: 3px solid #ffe699;
}
.step-accordion .accordion-button::after {
    filter: brightness(0) invert(1);
    opacity: 0.5;
}
.step-accordion .accordion-button:not(.collapsed)::after {
    opacity: 0.9;
}
.step-accordion .accordion-body {
    background: rgba(30, 40, 50, 0.4);
    padding: 1rem;
}
.step-accordion .accordion-item {
    border-color: rgba(255,255,255,0.1);
    background: transparent;
}
.step-accordion .accordion-item:first-child .accordion-button {
    border-radius: 0;
}
.step-accordion .accordion-item:last-child .accordion-button.collapsed {
    border-radius: 0;
}
.step-summary {
    font-size: 0.8rem;
    color: rgba(255,255,255,0.5);
    margin-left: auto;
    padding-right: 1rem;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 50%;
}
.step-summary.has-content {
    color: rgba(99, 179, 237, 0.8);
}
.step-title {
    display: flex;
    align-items: center;
    gap: 0.5rem;
}
.step-number {
    background: rgba(246, 173, 85, 0.2);
    color: #f6ad55;
    width: 1.5rem;
    height: 1.5rem;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 0.75rem;
    font-weight: bold;
    border: 1px solid rgba(246, 173, 85, 0.3);
}
.step-number.complete {
    background: rgba(72, 187, 120, 0.2);
    color: #48bb78;
    border-color: rgba(72, 187, 120, 0.3);
}

/* Glowing passphrase input */
.passphrase-input {
    background: rgba(30, 40, 50, 0.8) !important;
    border: 2px solid rgba(99, 179, 237, 0.3) !important;
    color: #63b3ed !important;
    font-family: 'Courier New', monospace;
    font-size: 1.1rem;
    letter-spacing: 0.5px;
    padding: 12px 16px;
    transition: border-color 0.3s ease, box-shadow 0.3s ease;
}
.passphrase-input:focus {
    border-color: rgba(99, 179, 237, 0.8) !important;
    box-shadow: 0 0 20px rgba(99, 179, 237, 0.4) !important;
}
.passphrase-input::placeholder {
    color: rgba(99, 179, 237, 0.4);
}

/* PIN input */
.pin-input-container .form-control {
    background: rgba(30, 40, 50, 0.8) !important;
    border: 2px solid rgba(246, 173, 85, 0.3) !important;
    color: #f6ad55 !important;
    font-family: 'Courier New', monospace;
    font-size: 1.2rem;
    letter-spacing: 3px;
    text-align: center;
}
.pin-input-container .form-control:focus {
    border-color: rgba(246, 173, 85, 0.8) !important;
    box-shadow: 0 0 20px rgba(246, 173, 85, 0.4) !important;
}

/* QR Crop Animation - uses .qr-scan-container from style.css */
</style>

<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-unlock-fill me-2"></i>Decode Secret Message or File</h5>
            </div>
            <div class="card-body {% if not decoded_message and not decoded_file %}p-0{% endif %}">
                {% if decoded_message %}
                <!-- Text Message Result -->
                <div class="alert alert-success">
                    <h6><i class="bi bi-check-circle me-2"></i>Message Decrypted Successfully!</h6>
                </div>

                <label class="form-label text-muted">Decoded Message: <small class="text-secondary">(click to copy)</small></label>
                <div class="alert-message p-3 rounded bg-dark border border-secondary mb-3" id="decodedContent" style="white-space: pre-wrap; cursor: pointer; transition: border-color 0.2s;"
                     onclick="navigator.clipboard.writeText(this.innerText).then(() => { this.style.borderColor = '#198754'; this.dataset.origText = this.innerHTML; this.innerHTML = '<i class=\'bi bi-check-circle text-success\'></i> Copied to clipboard!'; setTimeout(() => { this.innerHTML = this.dataset.origText; this.style.borderColor = ''; }, 1500); }).catch(() => alert('Failed to copy'))"
                     onmouseover="this.style.borderColor = '#6c757d'"
                     onmouseout="this.style.borderColor = ''">{{ decoded_message }}</div>

                <a href="/decode" class="btn btn-outline-light w-100">
                    <i class="bi bi-arrow-repeat me-2"></i>Decode Another
                </a>

                {% elif decoded_file %}
                <!-- File Result -->
                <div class="alert alert-success">
                    <h6><i class="bi bi-check-circle me-2"></i>File Decrypted Successfully!</h6>
                </div>

                <div class="text-center mb-4">
                    <i class="bi bi-file-earmark-check text-success" style="font-size: 4rem;"></i>
                    <h5 class="mt-3">{{ filename }}</h5>
                    <p class="text-muted mb-1">{{ file_size }}</p>
                    {% if mime_type %}
                    <small class="text-muted">Type: {{ mime_type }}</small>
                    {% endif %}
                </div>

                <a href="{{ url_for('decode_download', file_id=file_id) }}" class="btn btn-primary btn-lg w-100 mb-3">
                    <i class="bi bi-download me-2"></i>Download File
                </a>

                <div class="alert alert-warning small">
                    <i class="bi bi-clock me-1"></i>
                    <strong>File expires in 10 minutes.</strong> Download now.
                </div>

                <a href="/decode" class="btn btn-outline-light w-100">
                    <i class="bi bi-arrow-repeat me-2"></i>Decode Another
                </a>

                {% else %}
                <!-- Decode Form -->
                <form method="POST" enctype="multipart/form-data" id="decodeForm">
              <input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>

                    <div class="accordion step-accordion" id="decodeAccordion">

                        <!-- ================================================================
                             STEP 1: CARRIER TYPE (v4.3.0)
                             ================================================================ -->
                        <div class="accordion-item" id="carrierTypeStep">
                            <h2 class="accordion-header">
                                <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#stepCarrierType">
                                    <span class="step-title">
                                        <span class="step-number" id="stepCarrierTypeNumber">1</span>
                                        <i class="bi bi-collection me-1"></i> Carrier Type
                                    </span>
                                    <span class="step-summary" id="stepCarrierTypeSummary"></span>
                                </button>
                            </h2>
                            <div id="stepCarrierType" class="accordion-collapse collapse show" data-bs-parent="#decodeAccordion">
                                <div class="accordion-body">
                                    <input type="hidden" name="carrier_type" id="carrierTypeInput" value="image">
                                    <div class="btn-group w-100" role="group">
                                        <input type="radio" class="btn-check" name="carrier_type_select" id="typeImage" value="image" checked>
                                        <label class="btn btn-outline-secondary" for="typeImage">
                                            <i class="bi bi-image me-1"></i> Image
                                        </label>
                                        <input type="radio" class="btn-check" name="carrier_type_select" id="typeAudio" value="audio"
                                               {% if not has_audio %}disabled{% endif %}>
                                        <label class="btn btn-outline-secondary {% if not has_audio %}disabled text-muted{% endif %}" for="typeAudio">
                                            <i class="bi bi-music-note-beamed me-1"></i> Audio
                                            {% if not has_audio %}<small class="d-block" style="font-size: 0.65rem;">(not available)</small>{% endif %}
                                        </label>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- ================================================================
                             STEP 2: IMAGES & MODE
                             ================================================================ -->
                        <div class="accordion-item">
                            <h2 class="accordion-header">
                                <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#stepImages">
                                    <span class="step-title">
                                        <span class="step-number" id="stepImagesNumber">2</span>
                                        <i class="bi bi-images me-1"></i> Reference, Carrier, Mode
                                    </span>
                                    <span class="step-summary" id="stepImagesSummary">Select reference & stego</span>
                                </button>
                            </h2>
                            <div id="stepImages" class="accordion-collapse collapse" data-bs-parent="#decodeAccordion">
                                <div class="accordion-body">

                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">
                                                <i class="bi bi-image me-1"></i> Reference Photo
                                            </label>
                                            <div class="drop-zone scan-container" id="refDropZone">
                                                <input type="file" name="reference_photo" accept="image/*" required id="refPhotoInput">
                                                <div class="drop-zone-label">
                                                    <i class="bi bi-cloud-arrow-up fs-3 d-block mb-2 text-muted"></i>
                                                    <span class="text-muted">Drop image or click</span>
                                                </div>
                                                <img class="drop-zone-preview d-none" id="refPreview">
                                                <div class="scan-overlay"><div class="scan-grid"></div><div class="scan-line"></div></div>
                                                <div class="scan-corners">
                                                    <div class="scan-corner tl"></div><div class="scan-corner tr"></div>
                                                    <div class="scan-corner bl"></div><div class="scan-corner br"></div>
                                                </div>
                                                <div class="scan-data-panel">
                                                    <div class="scan-data-filename"><i class="bi bi-check-circle-fill"></i><span id="refFileName">image.jpg</span></div>
                                                    <div class="scan-data-row"><span class="scan-status-badge">Hash Acquired</span><span class="scan-data-value" id="refFileSize">--</span></div>
                                                </div>
                                            </div>
                                            <div class="form-text">Same reference photo used for encoding</div>
                                        </div>

                                        <div class="col-md-6 mb-3">
                                            <div id="imageStegoSection">
                                                <label class="form-label">
                                                    <i class="bi bi-file-earmark-image me-1"></i> Stego Image
                                                </label>
                                                <div class="drop-zone pixel-container" id="stegoDropZone">
                                                    <input type="file" name="stego_image" accept="image/*" required id="stegoInput">
                                                    <div class="drop-zone-label">
                                                        <i class="bi bi-cloud-arrow-up fs-3 d-block mb-2 text-muted"></i>
                                                        <span class="text-muted">Drop image or click</span>
                                                    </div>
                                                    <img class="drop-zone-preview d-none" id="stegoPreview">
                                                    <div class="pixel-blocks"></div>
                                                    <div class="pixel-scan-line"></div>
                                                    <div class="pixel-corners">
                                                        <div class="pixel-corner tl"></div><div class="pixel-corner tr"></div>
                                                        <div class="pixel-corner bl"></div><div class="pixel-corner br"></div>
                                                    </div>
                                                    <div class="pixel-data-panel">
                                                        <div class="pixel-data-filename"><i class="bi bi-check-circle-fill"></i><span id="stegoFileName">image.png</span></div>
                                                        <div class="pixel-data-row"><span class="pixel-status-badge">Stego Loaded</span><span class="pixel-data-value" id="stegoFileSize">--</span></div>
                                                        <div class="pixel-dimensions" id="stegoDims">-- x -- px</div>
                                                    </div>
                                                </div>
                                                <div class="form-text">Image containing the hidden message</div>
                                            </div>
                                            <!-- Audio Stego (hidden by default) -->
                                            <div class="d-none" id="audioStegoSection">
                                                <label class="form-label">
                                                    <i class="bi bi-file-earmark-music me-1"></i> Stego Audio
                                                </label>
                                                <div class="drop-zone pixel-container" id="audioStegoDropZone">
                                                    <input type="file" name="stego_image" accept="audio/*" id="audioStegoInput">
                                                    <div class="drop-zone-label">
                                                        <i class="bi bi-music-note-beamed fs-3 d-block mb-2 text-muted"></i>
                                                        <span class="text-muted">Drop audio or click</span>
                                                    </div>
                                                    <div class="pixel-data-panel">
                                                        <div class="pixel-data-filename"><i class="bi bi-check-circle-fill"></i><span id="audioStegoFileName">audio.wav</span></div>
                                                        <div class="pixel-data-row"><span class="pixel-status-badge">Audio Loaded</span><span class="pixel-data-value" id="audioStegoFileSize">--</span></div>
                                                    </div>
                                                </div>
                                                <div class="form-text">Audio file containing the hidden message</div>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- Extraction Mode -->
                                    <div class="d-flex gap-2 align-items-center flex-wrap mb-2">
                                        <div id="imageModeGroup">
                                            <div class="btn-group" role="group">
                                                <input type="radio" class="btn-check" name="embed_mode" id="modeAuto" value="auto" checked>
                                                <label class="btn btn-outline-secondary text-nowrap" for="modeAuto"><i class="bi bi-magic me-1"></i>Auto</label>
                                                <input type="radio" class="btn-check" name="embed_mode" id="modeLsb" value="lsb">
                                                <label class="btn btn-outline-secondary text-nowrap" for="modeLsb"><i class="bi bi-grid-3x3-gap me-1"></i>LSB</label>
                                                <input type="radio" class="btn-check" name="embed_mode" id="modeDct" value="dct" {% if not has_dct %}disabled{% endif %}>
                                                <label class="btn btn-outline-secondary text-nowrap" for="modeDct" id="dctModeLabel"><i class="bi bi-soundwave me-1"></i>DCT</label>
                                            </div>
                                        </div>
                                        <!-- Audio Extraction Modes (hidden by default) -->
                                        <div class="d-none" id="audioModeGroup">
                                            <div class="btn-group" role="group">
                                                <input type="radio" class="btn-check" name="embed_mode" id="modeAudioAuto" value="audio_auto">
                                                <label class="btn btn-outline-secondary text-nowrap" for="modeAudioAuto"><i class="bi bi-magic me-1"></i>Auto</label>
                                                <input type="radio" class="btn-check" name="embed_mode" id="modeAudioLsb" value="audio_lsb">
                                                <label class="btn btn-outline-secondary text-nowrap" for="modeAudioLsb"><i class="bi bi-grid-3x3-gap me-1"></i>LSB</label>
                                                <input type="radio" class="btn-check" name="embed_mode" id="modeAudioSpread" value="audio_spread">
                                                <label class="btn btn-outline-secondary text-nowrap" for="modeAudioSpread"><i class="bi bi-broadcast me-1"></i>Spread</label>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="form-text" id="modeHint">
                                        <i class="bi bi-lightning me-1"></i>Tries LSB first, then DCT
                                    </div>

                                </div>
                            </div>
                        </div>

                        <!-- ================================================================
                             STEP 3: SECURITY
                             ================================================================ -->
                        <div class="accordion-item">
                            <h2 class="accordion-header">
                                <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#stepSecurity">
                                    <span class="step-title">
                                        <span class="step-number" id="stepSecurityNumber">3</span>
                                        <i class="bi bi-shield-lock me-1"></i> Security
                                    </span>
                                    <span class="step-summary" id="stepSecuritySummary">Passphrase & keys</span>
                                </button>
                            </h2>
                            <div id="stepSecurity" class="accordion-collapse collapse" data-bs-parent="#decodeAccordion">
                                <div class="accordion-body">

                                    <!-- Passphrase -->
                                    <div class="mb-3">
                                        <label class="form-label"><i class="bi bi-chat-quote me-1"></i> Passphrase</label>
                                        <input type="text" name="passphrase" class="form-control passphrase-input"
                                               placeholder="e.g., apple forest thunder mountain" required id="passphraseInput">
                                        <div class="form-text">The passphrase used during encoding</div>
                                    </div>

                                    <hr class="my-3 opacity-25">
                                    <div class="small text-muted mb-2">Provide same factors used during encoding</div>

                                    <div class="row">
                                        <!-- PIN -->
                                        <div class="col-md-6 mb-2">
                                            <div class="security-box h-100">
                                                <label class="form-label"><i class="bi bi-123 me-1"></i> PIN</label>
                                                <div class="input-group pin-input-container">
                                                    <input type="password" name="pin" class="form-control" id="pinInput" placeholder="••••••" maxlength="9">
                                                    <button class="btn btn-outline-secondary" type="button" data-toggle-password="pinInput">
                                                        <i class="bi bi-eye"></i>
                                                    </button>
                                                </div>
                                                </div>
                                        </div>

                                        <!-- Channel -->
                                        <div class="col-md-6 mb-2">
                                            <div class="security-box h-100">
                                                <label class="form-label"><i class="bi bi-broadcast me-1"></i> Channel</label>
                                                <select class="form-select form-select-sm" name="channel_key" id="channelSelectDec">
                                                    <option value="auto" selected>Auto{% if channel_configured %} (Server){% endif %}</option>
                                                    <option value="none">Public</option>
                                                    {% if saved_channel_keys %}
                                                    <optgroup label="Saved Keys">
                                                        {% for key in saved_channel_keys %}
                                                        <option value="{{ key.channel_key }}">{{ key.name }}</option>
                                                        {% endfor %}
                                                    </optgroup>
                                                    {% endif %}
                                                    <option value="custom">Custom...</option>
                                                </select>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- Custom Channel Key -->
                                    <div class="mb-3 d-none" id="channelCustomInputDec">
                                        <div class="security-box">
                                            <label class="form-label"><i class="bi bi-key me-1"></i> Custom Channel Key</label>
                                            <div class="input-group">
                                                <input type="text" name="channel_key_custom" class="form-control form-control-sm font-monospace"
                                                       placeholder="XXXX-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX" id="channelKeyInputDec">
                                                <button class="btn btn-outline-secondary btn-sm" type="button" id="channelKeyScanDec" title="Scan QR"><i class="bi bi-camera"></i></button>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- RSA Key -->
                                    <div class="mb-3">
                                        <div class="security-box">
                                            <label class="form-label"><i class="bi bi-file-earmark-lock me-1"></i> RSA Key <span class="text-muted">(if used)</span></label>
                                            <div class="btn-group w-100 mb-2" role="group">
                                                <input type="radio" class="btn-check" name="rsa_input_method" id="rsaMethodFile" value="file" checked>
                                                <label class="btn btn-outline-secondary btn-sm" for="rsaMethodFile"><i class="bi bi-file-earmark me-1"></i>.pem</label>
                                                <input type="radio" class="btn-check" name="rsa_input_method" id="rsaMethodQr" value="qr">
                                                <label class="btn btn-outline-secondary btn-sm" for="rsaMethodQr"><i class="bi bi-qr-code me-1"></i>QR</label>
                                            </div>
                                            <div id="rsaFileSection">
                                                <input type="file" name="rsa_key" class="form-control form-control-sm" accept=".pem">
                                            </div>
                                            <div id="rsaQrSection" class="d-none d-flex flex-column">
                                                <input type="hidden" name="rsa_key_pem" id="rsaKeyPem">
                                                <div class="drop-zone p-2 w-100" id="qrDropZone">
                                                    <input type="file" name="rsa_key_qr" accept="image/*" id="rsaQrInput">
                                                    <div class="drop-zone-label text-center">
                                                        <i class="bi bi-qr-code-scan fs-5 d-block text-muted mb-1"></i>
                                                        <span class="text-muted small">Drop QR image</span>
                                                    </div>
                                                    <div class="qr-scan-container d-none" id="qrCropContainer">
                                                        <img class="qr-original" id="qrOriginal" alt="Original">
                                                        <img class="qr-cropped" id="qrCropped" alt="Cropped">
                                                    </div>
                                                </div>
                                                <button type="button" class="btn btn-outline-secondary btn-sm w-100 mt-2" id="rsaQrWebcam">
                                                    <i class="bi bi-camera me-1"></i>Scan with Camera
                                                </button>
                                            </div>
                                            <div class="input-group input-group-sm mt-2">
                                                <input type="password" name="rsa_password" class="form-control" id="rsaPasswordInput" placeholder="Key password (if encrypted)">
                                                <button class="btn btn-outline-secondary" type="button" data-toggle-password="rsaPasswordInput"><i class="bi bi-eye"></i></button>
                                            </div>
                                        </div>
                                    </div>

                                </div>
                            </div>
                        </div>

                    </div>

                    <!-- Submit Button -->
                    <div class="p-3">
                        <button type="submit" class="btn btn-primary btn-lg w-100" id="decodeBtn">
                            <i class="bi bi-unlock me-2"></i>Decode
                        </button>
                    </div>

                </form>
                {% endif %}
            </div>
        </div>

        {% if not decoded_message and not decoded_file %}
        <!-- Troubleshooting Card -->
        <div class="card mt-4">
            <div class="card-body">
                <h6 class="text-muted mb-3"><i class="bi bi-question-circle me-2"></i>Troubleshooting</h6>
                <ul class="list-unstyled text-muted small mb-0">
                    <li class="mb-2">
                        <i class="bi bi-check-circle-fill text-success me-1"></i>
                        Use the <strong>exact same reference photo</strong> (byte-for-byte identical)
                    </li>
                    <li class="mb-2">
                        <i class="bi bi-check-circle-fill text-success me-1"></i>
                        Enter the <strong>exact passphrase</strong> used during encoding
                    </li>
                    <li class="mb-2">
                        <i class="bi bi-exclamation-triangle-fill text-warning me-1"></i>
                        Ensure the stego image hasn't been <strong>resized or recompressed</strong>
                    </li>
                    <li class="mb-0">
                        <i class="bi bi-info-circle-fill text-info me-1"></i>
                        If auto-detection fails, try specifying <strong>LSB or DCT mode</strong>
                    </li>
                </ul>
            </div>
        </div>
        {% endif %}
    </div>
</div>
{% endblock %}

{% block scripts %}
<script src="{{ url_for('static', filename='js/soosef.js') }}"></script>
<script>
// ============================================================================
// MODE HINT - Dynamic text based on selected extraction mode
// ============================================================================
const modeHints = {
    auto: { icon: 'lightning', text: 'Tries LSB first, then DCT' },
    lsb: { icon: 'hdd', text: 'For email and direct transfers' },
    dct: { icon: 'phone', text: 'For social media images' },
    audio_auto: { icon: 'lightning', text: 'Tries LSB first, then Spread Spectrum' },
    audio_lsb: { icon: 'grid-3x3-gap', text: 'Direct bit embedding in audio samples' },
    audio_spread: { icon: 'broadcast', text: 'Noise-resistant spread spectrum encoding' }
};

document.querySelectorAll('input[name="embed_mode"]').forEach(radio => {
    radio.addEventListener('change', function() {
        const hint = document.getElementById('modeHint');
        const data = modeHints[this.value];
        if (hint && data) {
            hint.innerHTML = `<i class="bi bi-${data.icon} me-1"></i>${data.text}`;
        }
    });
});

// ============================================================================
// ACCORDION SUMMARY UPDATES
// ============================================================================

const carrierTypeInput = document.getElementById('carrierTypeInput');

function updateImagesSummary() {
    const ref = document.getElementById('refPhotoInput')?.files[0];
    const isAudio = carrierTypeInput?.value === 'audio';
    const stego = isAudio
        ? document.getElementById('audioStegoInput')?.files[0]
        : document.getElementById('stegoInput')?.files[0];
    const mode = document.querySelector('input[name="embed_mode"]:checked')?.value?.toUpperCase() || 'AUTO';
    const summary = document.getElementById('stepImagesSummary');
    const stepNum = document.getElementById('stepImagesNumber');

    if (ref && stego) {
        const refName = ref.name.length > 12 ? ref.name.slice(0, 10) + '..' : ref.name;
        const stegoName = stego.name.length > 12 ? stego.name.slice(0, 10) + '..' : stego.name;
        summary.textContent = `${refName} + ${stegoName}, ${mode}`;
        summary.classList.add('has-content');
        stepNum.classList.add('complete');
        stepNum.innerHTML = '<i class="bi bi-check"></i>';
    } else if (ref || stego) {
        summary.textContent = ref ? ref.name.slice(0, 15) : stego.name.slice(0, 15);
        summary.classList.remove('has-content');
        stepNum.classList.remove('complete');
        stepNum.textContent = '2';
    } else {
        summary.textContent = isAudio ? 'Select reference & audio' : 'Select reference & stego';
        summary.classList.remove('has-content');
        stepNum.classList.remove('complete');
        stepNum.textContent = '2';
    }
}

function updateSecuritySummary() {
    const passphrase = document.getElementById('passphraseInput')?.value || '';
    const pin = document.getElementById('pinInput')?.value || '';
    const rsaFile = document.querySelector('input[name="rsa_key"]')?.files[0];
    const rsaPem = document.getElementById('rsaKeyPem')?.value || '';
    const summary = document.getElementById('stepSecuritySummary');
    const stepNum = document.getElementById('stepSecurityNumber');

    const parts = [];
    if (passphrase.trim()) parts.push('passphrase');
    if (pin) parts.push('PIN');
    if (rsaFile || rsaPem) parts.push('RSA');

    if (parts.length > 0) {
        summary.textContent = parts.join(' + ');
        summary.classList.add('has-content');
        if (passphrase.trim()) {
            stepNum.classList.add('complete');
            stepNum.innerHTML = '<i class="bi bi-check"></i>';
        }
    } else {
        summary.textContent = 'Passphrase & keys';
        summary.classList.remove('has-content');
        stepNum.classList.remove('complete');
        stepNum.textContent = '3';
    }
}

// Attach listeners
document.getElementById('refPhotoInput')?.addEventListener('change', updateImagesSummary);
document.getElementById('stegoInput')?.addEventListener('change', updateImagesSummary);
document.getElementById('audioStegoInput')?.addEventListener('change', updateImagesSummary);
document.querySelectorAll('input[name="embed_mode"]').forEach(r => r.addEventListener('change', updateImagesSummary));
document.querySelectorAll('#audioModeGroup input[name="embed_mode"]').forEach(r => r.addEventListener('change', updateImagesSummary));

document.getElementById('passphraseInput')?.addEventListener('input', updateSecuritySummary);
document.getElementById('pinInput')?.addEventListener('input', updateSecuritySummary);
document.querySelector('input[name="rsa_key"]')?.addEventListener('change', updateSecuritySummary);

// ============================================================================
// CARRIER TYPE TOGGLE (v4.3.0)
// ============================================================================

const carrierTypeRadios = document.querySelectorAll('input[name="carrier_type_select"]');
const imageStegoSection = document.getElementById('imageStegoSection');
const audioStegoSection = document.getElementById('audioStegoSection');
const imageModeGroup = document.getElementById('imageModeGroup');
const audioModeGroup = document.getElementById('audioModeGroup');
const stepCarrierTypeSummary = document.getElementById('stepCarrierTypeSummary');

carrierTypeRadios.forEach(radio => {
    radio.addEventListener('change', function() {
        const isAudio = this.value === 'audio';
        carrierTypeInput.value = this.value;

        // Toggle stego sections
        if (imageStegoSection) imageStegoSection.classList.toggle('d-none', isAudio);
        if (audioStegoSection) audioStegoSection.classList.toggle('d-none', !isAudio);

        // Toggle required attribute so hidden inputs don't block form submission
        const imgStego = document.getElementById('stegoInput');
        const audStego = document.getElementById('audioStegoInput');
        if (imgStego) { if (isAudio) imgStego.removeAttribute('required'); else imgStego.setAttribute('required', ''); }
        if (audStego) { if (isAudio) audStego.setAttribute('required', ''); else audStego.removeAttribute('required'); }

        // Toggle mode groups
        if (imageModeGroup) imageModeGroup.classList.toggle('d-none', isAudio);
        if (audioModeGroup) audioModeGroup.classList.toggle('d-none', !isAudio);

        // Update summary
        if (stepCarrierTypeSummary) {
            stepCarrierTypeSummary.textContent = isAudio ? 'Audio' : 'Image';
        }

        // Select default mode
        if (isAudio) {
            const audioAuto = document.getElementById('modeAudioAuto');
            if (audioAuto) audioAuto.checked = true;
        } else {
            const autoMode = document.getElementById('modeAuto');
            if (autoMode) autoMode.checked = true;
        }

        // Clear stego file selections
        const stegoInput = document.getElementById('stegoInput');
        const audioStegoInput = document.getElementById('audioStegoInput');
        if (stegoInput) stegoInput.value = '';
        if (audioStegoInput) audioStegoInput.value = '';

        // Reset previews
        document.getElementById('stegoPreview')?.classList.add('d-none');

        // Update mode hint
        const hint = document.getElementById('modeHint');
        if (hint) {
            if (isAudio) {
                hint.innerHTML = '<i class="bi bi-lightning me-1"></i>Tries LSB first, then Spread Spectrum';
            } else {
                hint.innerHTML = '<i class="bi bi-lightning me-1"></i>Tries LSB first, then DCT';
            }
        }

        updateImagesSummary();
    });
});

// Audio stego file info display
const audioStegoInput = document.getElementById('audioStegoInput');
audioStegoInput?.addEventListener('change', function() {
    if (this.files && this.files[0]) {
        const file = this.files[0];
        document.getElementById('audioStegoFileName').textContent = file.name;
        document.getElementById('audioStegoFileSize').textContent = (file.size / 1024).toFixed(1) + ' KB';
        updateImagesSummary();
    }
});

// ============================================================================
// MODE SWITCHING
// ============================================================================

// Apply disabled styling to DCT if not available
if (document.getElementById('modeDct')?.disabled) {
    document.getElementById('dctModeLabel')?.classList.add('disabled', 'text-muted');
}

// ============================================================================
// LOADING STATE
// ============================================================================

Stegasoo.initFormLoading('decodeForm', 'decodeBtn', 'Decoding...');
</script>
{% endblock %}
