/**
 * ProjectsSurface — root view-switching component.
 *
 * No selectedId → card grid list (ProjectsList)
 * With selectedId → detail view (ProjectDetail)
 *
 * Globals: __PROJECT_ID__ (deep-link), __BASE__ (base path)
 */
const html = window.html;
const { useState, useEffect, useCallback } = window.hooks;
const { render } = window.preact;

import { ToastContainer } from '../../primitives/toast.js';
import { DialogStack } from '../../shell/dialog-stack.js';
import { ProjectsList } from './list.js';
import { ProjectDetail } from './detail.js';

function ProjectsSurface() {
    const BASE = window.__BASE__ || '';
    const deepLinkId = window.__PROJECT_ID__ || '';

    const [projects, setProjects] = useState([]);
    const [selectedId, setSelectedId] = useState(deepLinkId || '');
    const [loading, setLoading] = useState(true);

    const load = useCallback(async () => {
        try {
            const resp = await sw.api.projects.list();
            const list = resp?.data || resp || [];
            setProjects(list);
            if (deepLinkId && !list.find(p => p.id === deepLinkId)) {
                setSelectedId('');
            }
        } catch (e) { sw.toast(e.message, 'error'); }
        finally { setLoading(false); }
    }, [deepLinkId]);

    useEffect(() => { load(); }, [load]);

    const selected = projects.find(p => p.id === selectedId) || null;

    function selectProject(id) {
        setSelectedId(id);
        history.replaceState(null, '', BASE + '/projects/' + id);
    }

    function goBack() {
        setSelectedId('');
        history.replaceState(null, '', BASE + '/projects');
    }

    async function createProject(name) {
        try {
            const proj = await sw.api.projects.create({ name });
            sw.toast('Project created', 'success');
            await load();
            if (proj?.id) selectProject(proj.id);
        } catch (e) { sw.toast(e.message, 'error'); }
    }

    const handleUpdate = useCallback((deleted) => {
        if (deleted) { setSelectedId(''); history.replaceState(null, '', BASE + '/projects'); }
        load();
    }, [load, BASE]);

    return html`
        <div class="sw-projects">
            ${selected
                ? html`<${ProjectDetail}
                    key=${selectedId}
                    project=${selected}
                    onBack=${goBack}
                    onUpdate=${handleUpdate} />`
                : html`<${ProjectsList}
                    projects=${projects}
                    loading=${loading}
                    onSelect=${selectProject}
                    onCreate=${createProject} />`
            }
        </div>
        <${ToastContainer} />
        <${DialogStack} />
    `;
}

// ── Mount ────────────────────────────────
const mount = document.getElementById('projects-mount');
if (mount) {
    render(html`<${ProjectsSurface} />`, mount);
    console.log('[projects] Surface mounted');
}

export { ProjectsSurface };
