/**
 * ProfileSection — display name, email, avatar, password change
 */
const { html } = window;
const { useState, useEffect, useCallback, useRef } = hooks;

export function ProfileSection() {
    const [displayName, setDisplayName] = useState('');
    const [email, setEmail] = useState('');
    const [avatarUrl, setAvatarUrl] = useState(null);
    const [savingProfile, setSavingProfile] = useState(false);

    // Password state
    const [curPw, setCurPw] = useState('');
    const [newPw, setNewPw] = useState('');
    const [confirmPw, setConfirmPw] = useState('');
    const [savingPw, setSavingPw] = useState(false);

    const fileRef = useRef(null);

    // Load profile
    useEffect(() => {
        (async () => {
            try {
                const p = await sw.api.profile.get();
                setDisplayName(p.display_name || p.username || '');
                setEmail(p.email || '');
                setAvatarUrl(p.avatar || p.avatar_url || null);
            } catch (e) {
                // Fall back to auth user
                const u = sw.auth.user;
                if (u) {
                    setDisplayName(u.display_name || u.username || '');
                    setEmail(u.email || '');
                    setAvatarUrl(u.avatar || null);
                }
            }
        })();
    }, []);

    const saveProfile = useCallback(async () => {
        if (!displayName.trim()) {
            sw.emit('toast', { message: 'Display name is required', variant: 'error' });
            return;
        }
        setSavingProfile(true);
        try {
            await sw.api.profile.update({ display_name: displayName.trim() });
            sw.emit('toast', { message: 'Profile saved', variant: 'success' });
        } catch (e) {
            sw.emit('toast', { message: e.message, variant: 'error' });
        } finally {
            setSavingProfile(false);
        }
    }, [displayName]);

    const changePassword = useCallback(async () => {
        if (!curPw || !newPw) {
            sw.emit('toast', { message: 'All password fields are required', variant: 'error' });
            return;
        }
        if (newPw !== confirmPw) {
            sw.emit('toast', { message: 'Passwords do not match', variant: 'error' });
            return;
        }
        if (newPw.length < 8) {
            sw.emit('toast', { message: 'Password must be at least 8 characters', variant: 'error' });
            return;
        }
        setSavingPw(true);
        try {
            await sw.api.profile.password(curPw, newPw);
            sw.emit('toast', { message: 'Password changed', variant: 'success' });
            setCurPw(''); setNewPw(''); setConfirmPw('');
        } catch (e) {
            sw.emit('toast', { message: e.message, variant: 'error' });
        } finally {
            setSavingPw(false);
        }
    }, [curPw, newPw, confirmPw]);

    // Avatar upload
    const onAvatarFile = useCallback(async (e) => {
        const file = e.target.files?.[0];
        if (!file) return;
        const reader = new FileReader();
        reader.onload = async () => {
            try {
                await sw.api.profile.avatar(reader.result);
                setAvatarUrl(reader.result);
                sw.emit('toast', { message: 'Avatar updated', variant: 'success' });
            } catch (err) {
                sw.emit('toast', { message: err.message, variant: 'error' });
            }
        };
        reader.readAsDataURL(file);
    }, []);

    const removeAvatar = useCallback(async () => {
        try {
            await sw.api.profile.deleteAvatar();
            setAvatarUrl(null);
            sw.emit('toast', { message: 'Avatar removed', variant: 'success' });
        } catch (e) {
            sw.emit('toast', { message: e.message, variant: 'error' });
        }
    }, []);

    const initial = (displayName || '?')[0].toUpperCase();

    return html`
        <div class="settings-section">
            <h3>Profile</h3>

            ${/* Avatar */''}
            <div style="display:flex;align-items:center;gap:16px;margin-bottom:16px;">
                <div class="avatar-preview" style="width:56px;height:56px;border-radius:50%;overflow:hidden;
                     background:var(--bg-raised);display:flex;align-items:center;justify-content:center;
                     font-size:24px;font-weight:600;color:var(--text-2);flex-shrink:0;">
                    ${avatarUrl
                        ? html`<img src=${avatarUrl} alt="Avatar"
                                    style="width:100%;height:100%;object-fit:cover;" />`
                        : initial
                    }
                </div>
                <div style="display:flex;gap:8px;">
                    <button class="btn-sm btn-secondary"
                            onClick=${() => fileRef.current?.click()}>
                        Upload
                    </button>
                    ${avatarUrl && html`
                        <button class="btn-sm btn-secondary" onClick=${removeAvatar}>
                            Remove
                        </button>
                    `}
                    <input type="file" ref=${fileRef} accept="image/*"
                           style="display:none;" onChange=${onAvatarFile} />
                </div>
            </div>

            <div class="form-group">
                <label>Display Name</label>
                <input type="text" placeholder="Your display name"
                       value=${displayName}
                       onInput=${e => setDisplayName(e.target.value)} />
            </div>
            <div class="form-group">
                <label>Email</label>
                <input type="email" disabled value=${email} />
            </div>
            <button class="btn-md btn-primary" disabled=${savingProfile}
                    onClick=${saveProfile}>
                ${savingProfile ? 'Saving\u2026' : 'Save Profile'}
            </button>
        </div>

        <div class="settings-section" style="margin-top:20px;">
            <h3>Change Password</h3>
            <div class="form-group">
                <label>Current Password</label>
                <input type="password" autocomplete="current-password"
                       value=${curPw} onInput=${e => setCurPw(e.target.value)} />
            </div>
            <div class="form-group">
                <label>New Password</label>
                <input type="password" autocomplete="new-password"
                       value=${newPw} onInput=${e => setNewPw(e.target.value)} />
            </div>
            <div class="form-group">
                <label>Confirm New Password</label>
                <input type="password" autocomplete="new-password"
                       value=${confirmPw} onInput=${e => setConfirmPw(e.target.value)} />
            </div>
            <button class="btn-md btn-primary" disabled=${savingPw}
                    onClick=${changePassword}>
                ${savingPw ? 'Updating\u2026' : 'Update Password'}
            </button>
        </div>
    `;
}
