---
import { i18n } from "@i18n/translation";
import I18nKey from "@i18n/i18nKey";
import CryptoJS from 'crypto-js';


interface Props {
    isEncrypted?: boolean;
    password?: string;
}

const { isEncrypted = false, password = "" } = Astro.props;

let encryptedContent = "";
if (isEncrypted) {
    const html = await Astro.slots.render('default');
    encryptedContent = CryptoJS.AES.encrypt(html, password).toString();
}
---

{!isEncrypted ? (
    <slot />
) : (
    <div id="password-protection" class="password-protection">
        <div class="password-container">
            <div class="lock-icon">
                <svg width="48" height="48" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2zM9 6c0-1.66 1.34-3 3-3s3 1.34 3 3v2H9V6z" fill="currentColor"/>
                </svg>
            </div>
            <h2 class="text-90">{i18n(I18nKey.passwordProtectedTitle)}</h2>
            <p class="text-75">{i18n(I18nKey.passwordProtectedDescription)}</p>
            <div class="password-input-group">
                <div class="password-input-wrapper">
                    <input
                        type="password"
                        id="password-input"
                        placeholder={i18n(I18nKey.passwordPlaceholder)}
                        class="password-input text-90"
                        autocomplete="current-password"
                    />
                    <button id="toggle-password" class="toggle-password-btn text-50" type="button" aria-label="Toggle password visibility">
                        <svg id="eye-icon" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path>
                            <circle cx="12" cy="12" r="3"></circle>
                        </svg>
                        <svg id="eye-off-icon" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display: none;">
                            <path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"></path>
                            <line x1="1" y1="1" x2="23" y2="23"></line>
                        </svg>
                    </button>
                </div>
                <button id="unlock-btn" class="unlock-button">{i18n(I18nKey.passwordUnlock)}</button>
            </div>
            <div id="error-message" class="error-message" style="display: none;">{i18n(I18nKey.passwordIncorrect)}</div>
        </div>
    </div>

    <div id="decrypted-content" class="decrypted-content" style="display: none;" data-encrypted={encryptedContent}></div>

    <script>
        import CryptoJS from 'crypto-js';

        function initPasswordProtection() {
            const passwordInput = document.getElementById('password-input') as HTMLInputElement;
            const unlockBtn = document.getElementById('unlock-btn');
            const togglePasswordBtn = document.getElementById('toggle-password');
            const eyeIcon = document.getElementById('eye-icon');
            const eyeOffIcon = document.getElementById('eye-off-icon');
            const errorMessage = document.getElementById('error-message');
            const passwordProtection = document.getElementById('password-protection');
            const decryptedContent = document.getElementById('decrypted-content');

            if (!passwordInput || !unlockBtn || !decryptedContent || !passwordProtection) return;

            // 切换密码可见性
            if (togglePasswordBtn && eyeIcon && eyeOffIcon) {
                togglePasswordBtn.addEventListener('click', () => {
                    const isPassword = passwordInput.type === 'password';
                    passwordInput.type = isPassword ? 'text' : 'password';
                    eyeIcon.style.display = isPassword ? 'none' : 'block';
                    eyeOffIcon.style.display = isPassword ? 'block' : 'none';
                });
            }

            const handleUnlock = () => {
                const password = passwordInput.value;
                const encrypted = decryptedContent.getAttribute('data-encrypted');

                if (!password || !encrypted) return;

                try {
                    const bytes = CryptoJS.AES.decrypt(encrypted, password);
                    const decryptedHtml = bytes.toString(CryptoJS.enc.Utf8);

                    if (decryptedHtml) {
                        decryptedContent.innerHTML = decryptedHtml;
                        decryptedContent.style.display = 'block';
                        passwordProtection.style.display = 'none';

                        // 执行解密内容中的脚本
                        decryptedContent.querySelectorAll('script').forEach(oldScript => {
                            const newScript = document.createElement('script');
                            Array.from(oldScript.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value));
                            newScript.appendChild(document.createTextNode(oldScript.innerHTML));
                            oldScript.parentNode?.replaceChild(newScript, oldScript);
                        });

                        // 触发可能需要的重新渲染或初始化
                        window.dispatchEvent(new Event('resize'));
                        window.dispatchEvent(new CustomEvent('content-decrypted'));
                    } else {
                        if (errorMessage) errorMessage.style.display = 'block';
                    }
                } catch (e) {
                    if (errorMessage) errorMessage.style.display = 'block';
                }
            };

            unlockBtn.addEventListener('click', handleUnlock);
            passwordInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') handleUnlock();
                if (errorMessage) errorMessage.style.display = 'none';
            });
        }

        // 页面加载时初始化
        initPasswordProtection();

        // 支持 View Transitions
        document.addEventListener('astro:after-swap', initPasswordProtection);
    </script>
)}

<style>
    .password-protection {
        display: flex;
        justify-content: center;
        align-items: center;
        min-height: 40vh;
        padding: 2rem;
    }

    .password-container {
        text-align: center;
        max-width: 400px;
        width: 100%;
        padding: 2.5rem;
        border-radius: 1rem;
        background: var(--card-bg);
        border: 1px solid var(--line-divider);
        box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 8px 10px -6px rgba(0, 0, 0, 0.1);
    }

    .lock-icon {
        margin-bottom: 1.5rem;
        color: var(--primary);
        display: flex;
        justify-content: center;
    }

    .password-container h2 {
        margin-bottom: 0.75rem;
        font-size: 1.5rem;
        font-weight: 700;
    }

    .password-container p {
        margin-bottom: 2rem;
        font-size: 0.95rem;
        line-height: 1.5;
    }

    .password-input-group {
        display: flex;
        flex-direction: column;
        gap: 0.75rem;
        margin-bottom: 1rem;
    }

    .password-input-wrapper {
        position: relative;
        width: 100%;
    }

    .password-input {
        width: 100%;
        padding: 0.75rem 3rem 0.75rem 1rem;
        border: 1px solid var(--line-divider);
        border-radius: 0.5rem;
        background: var(--card-bg);
        font-size: 1rem;
        transition: all 0.2s ease;
    }

    .password-input::-ms-reveal,
    .password-input::-ms-clear {
        display: none;
    }

    .toggle-password-btn {
        position: absolute;
        right: 0.75rem;
        top: 50%;
        translate: 0 -50%;
        background: none;
        border: none;
        padding: 0.25rem;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        transition: color 0.2s ease;
    }

    .toggle-password-btn:hover {
        color: var(--primary);
    }

    .password-input::placeholder {
        color: var(--content-meta);
        opacity: 0.7;
    }

    .password-input:focus {
        outline: none;
        border-color: var(--primary);
        box-shadow: 0 0 0 3px var(--primary-light);
    }

    .unlock-button {
        width: 100%;
        padding: 0.75rem 1.5rem;
        background: var(--primary);
        color: white;
        border: none;
        border-radius: 0.5rem;
        font-size: 1rem;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.2s ease;
    }

    .unlock-button:hover {
        background: var(--primary-hover);
        translate: 0 -1px;
    }

    .unlock-button:active {
        translate: 0 0;
    }

    .error-message {
        color: #ef4444;
        font-size: 0.875rem;
        margin-top: 0.75rem;
        font-weight: 500;
    }

    .decrypted-content {
        animation: fadeIn 0.5s ease-out;
    }

    @keyframes fadeIn {
        from {
            opacity: 0;
            translate: 0 10px;
        }
        to {
            opacity: 1;
            translate: 0 0;
        }
    }

    /* 响应式适配 */
    @media (max-width: 768px) {
        .password-protection {
            padding: 1rem;
            min-height: 30vh;
        }
        .password-container {
            padding: 1.5rem;
        }
    }
</style>