/**
 * ProjectsList — card grid view for all projects.
 *
 * Props:
 *   projects  — array of project objects
 *   loading   — boolean
 *   onSelect  — (id: string) => void
 *   onCreate  — (name: string) => void
 */
const html = window.html;
const { useState, useMemo } = window.hooks;

import { UserMenu } from '../../shell/user-menu.js';

// ── Relative time helper ────────────────────
const DIVISIONS = [
    [60, 'second'], [60, 'minute'], [24, 'hour'],
    [30, 'day'], [12, 'month'], [Infinity, 'year'],
];
function relativeTime(dateStr) {
    if (!dateStr) return '';
    let val = Math.floor((Date.now() - new Date(dateStr).getTime()) / 1000);
    if (val < 10) return 'just now';
    for (const [div, unit] of DIVISIONS) {
        if (val < div) {
            const n = Math.floor(val);
            return `Updated ${n} ${unit}${n !== 1 ? 's' : ''} ago`;
        }
        val /= div;
    }
    return '';
}

export function ProjectsList({ projects, loading, onSelect, onCreate }) {
    const [search, setSearch] = useState('');
    const [sort, setSort] = useState('activity');

    const filtered = useMemo(() => {
        const q = search.toLowerCase().trim();
        let list = projects;
        if (q) {
            list = list.filter(p =>
                (p.name || '').toLowerCase().includes(q) ||
                (p.description || '').toLowerCase().includes(q)
            );
        }
        if (sort === 'activity') {
            list = [...list].sort((a, b) =>
                new Date(b.updated_at || 0) - new Date(a.updated_at || 0)
            );
        } else {
            list = [...list].sort((a, b) =>
                (a.name || '').localeCompare(b.name || '')
            );
        }
        return list;
    }, [projects, search, sort]);

    async function handleCreate() {
        const name = await sw.prompt('Project name:');
        if (name && name.trim()) onCreate(name.trim());
    }

    if (loading) {
        return html`<div class="sw-projects__list">
            <div class="sw-projects__empty">Loading projects\u2026</div>
        </div>`;
    }

    return html`
        <div class="sw-projects__list">
            <div class="sw-projects__list-header">
                <${UserMenu} placement="down-right" />
                <h1 class="sw-projects__list-title">Projects</h1>
                <button class="sw-projects__new-btn" onClick=${handleCreate}>+ New project</button>
            </div>

            <div class="sw-projects__search-wrap">
                <span class="sw-projects__search-icon">\u{1F50D}</span>
                <input class="sw-projects__search"
                       type="text"
                       placeholder="Search projects\u2026"
                       value=${search}
                       onInput=${e => setSearch(e.target.value)} />
            </div>

            <div class="sw-projects__sort">
                <span>Sort by</span>
                <select value=${sort} onChange=${e => setSort(e.target.value)}>
                    <option value="activity">Activity</option>
                    <option value="name">Name</option>
                </select>
            </div>

            ${filtered.length === 0 && !loading && html`
                <div class="sw-projects__empty">
                    ${search ? 'No projects match your search.' : 'No projects yet.'}
                    ${!search && html`<div style="margin-top:12px;">
                        <button class="sw-projects__new-btn" onClick=${handleCreate}>+ Create your first project</button>
                    </div>`}
                </div>
            `}

            <div class="sw-projects__grid">
                ${filtered.map(p => html`
                    <div key=${p.id}
                         class="sw-projects__card"
                         style=${p.color ? `border-left: 3px solid ${p.color}` : ''}
                         onClick=${() => onSelect(p.id)}>
                        <div class="sw-projects__card-name">
                            ${p.icon ? html`<span>${p.icon}</span>` : ''}
                            <span>${p.name}</span>
                            ${p.is_archived && html`<span class="sw-projects__card-badge">archived</span>`}
                        </div>
                        ${p.description && html`
                            <div class="sw-projects__card-desc">${p.description}</div>
                        `}
                        <div class="sw-projects__card-meta">${relativeTime(p.updated_at)}</div>
                    </div>
                `)}
            </div>
        </div>
    `;
}
