/**
 * Avatar primitive — circle avatar with letter fallback
 * Sizes: sm (24px), md (32px), lg (48px)
 */
const { html } = window;
const { useState } = hooks;

function initials(name) {
    if (!name) return '?';
    const parts = name.trim().split(/\s+/);
    if (parts.length > 1) {
        // Multi-word: first + last initials ("John Doe" → "JD")
        return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
    }
    // Single word: first letter only ("admin" → "A")
    return name[0].toUpperCase();
}

export function Avatar({ src, name = '', size = 'md' }) {
    const [failed, setFailed] = useState(false);

    if (src && !failed) {
        return html`
            <img
                class="sw-avatar sw-avatar--${size}"
                src=${src}
                alt=${name}
                onError=${() => setFailed(true)}
            />
        `;
    }
    return html`
        <span class="sw-avatar sw-avatar--${size} sw-avatar--fallback"
              aria-label=${name || 'Avatar'}>
            ${initials(name)}
        </span>
    `;
}
