{% extends "base.html" %}

{% block title %}Edit Profile - AISBF{% endblock %}

{% block content %}
<div class="container">
    <h1 data-i18n="profile_page.title">Edit Profile</h1>
    <p data-i18n="profile_page.subtitle">Update your account information</p>

    {% if success %}
    <div class="alert alert-success">{{ success }}</div>
    {% endif %}

    {% if error %}
    <div class="alert alert-error">{{ error }}</div>
    {% endif %}

    <div class="card">
        <h2 data-i18n="profile_page.account_info">Account Information</h2>

        <form method="POST" action="{{ url_for(request, '/dashboard/profile') }}">
            <div class="form-group">
                <label for="username" data-i18n="profile_page.username">Username</label>
                <input type="text" id="username" name="username" value="{{ session.username }}" required>
            </div>

            <div class="form-group">
                <label for="display_name" data-i18n="profile_page.display_name">Display Name</label>
                <input type="text" id="display_name" name="display_name" value="{{ user.display_name or session.username }}" placeholder="Your display name">
                <small style="color: var(--color-muted); display: block; margin-top: 0.5rem;" data-i18n="profile_page.display_name_hint">
                    This is how your name will be displayed throughout the application
                </small>
            </div>

            <div class="form-group">
                <label for="email" data-i18n="profile_page.email">Email Address</label>
                <input type="email" id="email" name="email" value="{{ session.email or '' }}" readonly style="background: var(--bg-page); cursor: not-allowed;">
                {% if not session.email %}
                <small style="color: var(--color-muted); display: block; margin-top: 0.5rem;">
                    <span data-i18n="profile_page.no_email">No email address set.</span> <a href="{{ url_for(request, '/dashboard/change-email') }}" style="color: var(--color-link);" data-i18n="profile_page.add_email">Add Email</a> <span data-i18n="profile_page.email_requires_verify">(requires verification)</span>
                </small>
                {% else %}
                <small style="color: var(--color-muted); display: block; margin-top: 0.5rem;">
                    <a href="{{ url_for(request, '/dashboard/change-email') }}" style="color: var(--color-link);" data-i18n="profile_page.change_email">Change Email</a> <span data-i18n="profile_page.email_requires_verify">(requires verification)</span>
                </small>
                {% endif %}
            </div>

            <div class="form-group">
                <label data-i18n="profile_page.profile_picture">Profile Picture</label>
                <div style="display: flex; align-items: flex-start; gap: 1.5rem; flex-wrap: wrap;">
                    <div style="position: relative; cursor: pointer; flex-shrink: 0;" id="avatar-wrap">
                        <img id="avatar-preview"
                             src="{{ '/dashboard/profile-pic' if user.profile_pic else 'https://www.gravatar.com/avatar/' ~ (session.email|md5 if session.email else '') ~ '?s=96&d=identicon' }}"
                             alt="Profile picture"
                             style="width: 96px; height: 96px; border-radius: 8px; object-fit: cover; display: block;">
                        <div id="avatar-overlay" style="position: absolute; inset: 0; background: rgba(0,0,0,0.45); border-radius: 8px; display: flex; align-items: center; justify-content: center; opacity: 0; transition: opacity 0.2s; pointer-events: none;">
                            <span style="color: #fff; font-size: 0.8rem; text-align: center;">Change</span>
                        </div>
                    </div>
                    <div style="flex: 1; min-width: 0;">
                        <input type="file" id="profile_pic_file" accept="image/*" style="display: none;">
                        <button type="button" id="pic-upload-btn" class="btn btn-secondary" onclick="document.getElementById('profile_pic_file').click()" data-i18n="profile_page.upload_image">
                            Upload Image
                        </button>
                        <small style="color: var(--color-muted); display: block; margin-top: 0.5rem;" data-i18n="profile_page.upload_hint">Max 5 MB. JPG, PNG, GIF, WebP.</small>
                        <div id="pic-upload-status" style="margin-top: 0.5rem; font-size: 0.85rem; display: none;"></div>
                        <div id="pic-progress-bar" style="margin-top: 0.5rem; height: 6px; background: var(--bg-accent); border-radius: 3px; display: none;">
                            <div id="pic-progress-fill" style="height: 100%; background: var(--color-link); border-radius: 3px; width: 0%; transition: width 0.2s;"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div style="margin-top: 1.5rem;">
                <button type="submit" class="btn btn-primary" data-i18n="profile_page.save">Save Changes</button>
            </div>
        </form>
    </div>

    <div class="card" style="margin-top: 2rem; border: 1px solid var(--alert-error-border);">
        <h2 style="color: var(--alert-error-fg);" data-i18n="profile_page.danger_zone">Danger Zone</h2>
        <p style="color: var(--color-muted); margin-bottom: 1rem;" data-i18n="profile_page.danger_zone_desc">Permanently delete your account and all associated data.</p>
        <a href="{{ url_for(request, '/dashboard/delete-account') }}" class="btn btn-danger" data-i18n="profile_page.delete_account">Delete Account</a>
    </div>
</div>

<style>
.card {
    background: var(--bg-panel);
    padding: 2rem;
    border-radius: 8px;
    margin-top: 1.5rem;
}
.card h2 { margin-bottom: 1.5rem; color: var(--color-text); }
.form-group { margin-bottom: 1.25rem; }
.form-group label { display: block; margin-bottom: 0.5rem; font-weight: 500; color: var(--color-text); }
.form-group input {
    width: 100%; padding: 0.75rem; border: 1px solid var(--color-border); border-radius: 4px;
    background: var(--bg-input); color: var(--color-text); font-size: 1rem;
}
.form-group input:focus { outline: none; border-color: var(--color-link); }
</style>

<script>
const CHUNK_SIZE = 512 * 1024; // 512 KB — same as providers

const avatarWrap = document.getElementById('avatar-wrap');
const overlay    = document.getElementById('avatar-overlay');
avatarWrap.addEventListener('mouseenter', () => overlay.style.opacity = '1');
avatarWrap.addEventListener('mouseleave', () => overlay.style.opacity = '0');
avatarWrap.addEventListener('click',      () => document.getElementById('profile_pic_file').click());

document.getElementById('profile_pic_file').addEventListener('change', async function () {
    const file = this.files && this.files[0];
    if (!file) return;

    const MAX_BYTES = 5 * 1024 * 1024;
    const statusEl  = document.getElementById('pic-upload-status');
    const barWrap   = document.getElementById('pic-progress-bar');
    const barFill   = document.getElementById('pic-progress-fill');
    const btn       = document.getElementById('pic-upload-btn');

    function setStatus(msg, color) {
        statusEl.style.color = color || 'var(--color-text)';
        statusEl.textContent = msg;
        statusEl.style.display = 'block';
    }
    function setProgress(pct) {
        barWrap.style.display = 'block';
        barFill.style.width = pct + '%';
    }

    // Client-side size check
    if (file.size > MAX_BYTES) {
        setStatus(window.i18n.t('profile_page.upload_too_large'), '#f87171');
        this.value = '';
        return;
    }

    // Client-side type check
    if (!file.type.startsWith('image/')) {
        setStatus(window.i18n.t('profile_page.upload_invalid_type'), '#f87171');
        this.value = '';
        return;
    }

    // Preview immediately
    const reader = new FileReader();
    reader.onload = e => { document.getElementById('avatar-preview').src = e.target.result; };
    reader.readAsDataURL(file);

    btn.disabled = true;
    setProgress(0);
    setStatus(window.i18n.t('profile_page.uploading'), 'var(--color-link)');

    try {
        const totalChunks = Math.ceil(file.size / CHUNK_SIZE);

        for (let i = 1; i <= totalChunks; i++) {
            const start  = (i - 1) * CHUNK_SIZE;
            const end    = Math.min(start + CHUNK_SIZE, file.size);
            const chunk  = file.slice(start, end);
            const pct    = Math.round((i / totalChunks) * 100);

            setProgress(pct);
            setStatus(window.i18n.interpolate(window.i18n.t('profile_page.upload_pct'), {pct}), 'var(--color-link)');

            const fd = new FormData();
            fd.append('file_name',     file.name);
            fd.append('chunk_number',  i);
            fd.append('total_chunks',  totalChunks);
            fd.append('total_size',    file.size);
            fd.append('file',          chunk, file.name);

            const resp = await fetch('/dashboard/profile/upload-pic/chunk', {
                method: 'POST',
                body: fd
            });

            if (!resp.ok) {
                let msg = 'Upload failed (server error).';
                try { msg = (await resp.json()).error || msg; } catch (_) {}
                throw new Error(msg);
            }

            const result = await resp.json();
            if (!result.success) throw new Error(result.error || 'Upload failed.');

            if (result.complete) {
                setProgress(100);
                setStatus(window.i18n.t('profile_page.upload_success'), '#4ade80');
                btn.disabled = false;
                return;
            }
        }

        // Fallback — shouldn't reach here
        setStatus('Upload complete.', '#4ade80');
    } catch (err) {
        setStatus(window.i18n.interpolate(window.i18n.t('profile_page.upload_failed'), {error: err.message}), '#f87171');
        barWrap.style.display = 'none';
    } finally {
        btn.disabled = false;
        this.value = '';
    }
});
</script>
{% endblock %}
