/**
 * TeamAdminSurface — root team admin surface
 *
 * Reads globals:
 *   __SECTION__          — active section name (string)
 *   __BASE__             — base path
 *   __CONFIG_SECTIONS__  — v0.38.3: extension config sections (array|null)
 *
 * Layout: topbar (back + team name) + sidebar nav + content area.
 * All 10+ sections are native Preact components loaded lazily.
 */
const { html } = window;
const { useState, useEffect, useCallback, useMemo } = hooks;
const { render } = preact;

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

// ── Section config ──────────────────────────
const SECTIONS = [
    { key: 'members',     label: 'Members' },
    { key: 'groups',      label: 'Groups' },
    { key: 'connections', label: 'Connections' },
    { key: 'workflows',   label: 'Workflows' },
    { key: 'settings',    label: 'Settings' },
    { key: 'activity',    label: 'Activity' },
];

// ── Lazy section imports ────────────────────
const sectionModules = {
    members:     () => import('./members.js'),
    groups:      () => import('./groups.js'),
    connections: () => import('./connections.js'),
    workflows:   () => import('./workflows.js'),
    settings:    () => import('./settings.js'),
    activity:    () => import('./activity.js'),
};

// ── v0.38.3: Extension config sections ──────
const _configSections = window.__CONFIG_SECTIONS__ || [];
const _base = window.__BASE__ || '';
for (const cs of _configSections) {
    const pkgId = cs.package_id;
    const component = cs.component || 'js/config.js';
    SECTIONS.push({ key: pkgId, label: cs.label });
    sectionModules[pkgId] = () => import(`${_base}/surfaces/${pkgId}/${component}`);
}

function TeamAdminSurface() {
    const BASE    = window.__BASE__ || '';
    const section = window.__SECTION__ || 'members';

    const [SectionComponent, setSectionComponent] = useState(null);
    const [selectedTeam, setSelectedTeam] = useState(null);

    // Determine teams this user can admin
    const adminTeams = useMemo(() => {
        const teams = sw.auth?.teams || [];
        if (sw.isAdmin) return teams;
        return teams.filter(t => t.my_role === 'admin');
    }, []);

    // Auto-select if only one team
    useEffect(() => {
        if (adminTeams.length === 1 && !selectedTeam) {
            setSelectedTeam(adminTeams[0]);
        }
    }, [adminTeams]);

    // Load section component
    useEffect(() => {
        setSectionComponent(null);
        const loader = sectionModules[section];
        if (loader) {
            loader().then(mod => {
                const Comp = mod.default || Object.values(mod)[0];
                setSectionComponent(() => Comp);
            }).catch(e => console.error('[team-admin] Failed to load section:', section, e));
        }
    }, [section]);

    // Back button with return URL stash
    useEffect(() => {
        const RETURN_KEY = 'sb_team_admin_return';
        if (!sessionStorage.getItem(RETURN_KEY)) {
            const ref = document.referrer;
            if (ref && ref.startsWith(location.origin) && !ref.includes('/team-admin')) {
                sessionStorage.setItem(RETURN_KEY, ref);
            } else {
                sessionStorage.setItem(RETURN_KEY, location.origin + BASE + '/');
            }
        }
    }, []);

    const backClick = useCallback((e) => {
        e.preventDefault();
        const RETURN_KEY = 'sb_team_admin_return';
        const returnURL = sessionStorage.getItem(RETURN_KEY);
        sessionStorage.removeItem(RETURN_KEY);
        location.href = returnURL || BASE + '/';
    }, []);

    const navClick = useCallback((e) => {
        e.preventDefault();
        const href = e.currentTarget.getAttribute('href');
        if (href) location.replace(href);
    }, []);

    const teamId = selectedTeam?.id || selectedTeam?.team_id || null;
    const teamName = selectedTeam?.name || selectedTeam?.team_name || 'Team';
    const sectionLabel = SECTIONS.find(s => s.key === section)?.label || 'Members';

    // Team picker if multiple teams
    if (!selectedTeam && adminTeams.length > 1) {
        return html`
            <div class="surface-settings" style="flex-direction:column;">
                <div class="settings-topbar">
                    <a href="${BASE}/" class="settings-topbar-back" onClick=${backClick}>
                        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                             stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <line x1="19" y1="12" x2="5" y2="12"/>
                            <polyline points="12 19 5 12 12 5"/>
                        </svg>
                        Back
                    </a>
                    <div class="settings-topbar-sep"></div>
                    <span class="settings-topbar-title">Team Administration</span>
                </div>
                <div style="padding:32px;max-width:480px;margin:0 auto;">
                    <h3 style="margin:0 0 16px;">Select a Team</h3>
                    <div class="admin-list">
                        ${adminTeams.map(t => html`
                            <div class="admin-surface-row" key=${t.id || t.team_id}
                                 style="cursor:pointer;" onClick=${() => setSelectedTeam(t)}>
                                <strong style="flex:1;">${t.name || t.team_name}</strong>
                                <span class="badge">${t.my_role || 'admin'}</span>
                            </div>
                        `)}
                    </div>
                </div>
            </div>
            <${ToastContainer} />
            <${DialogStack} />
        `;
    }

    // No teams
    if (!selectedTeam && adminTeams.length === 0) {
        return html`
            <div class="surface-settings" style="flex-direction:column;">
                <div class="settings-topbar">
                    <a href="${BASE}/" class="settings-topbar-back" onClick=${backClick}>
                        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                             stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <line x1="19" y1="12" x2="5" y2="12"/>
                            <polyline points="12 19 5 12 12 5"/>
                        </svg>
                        Back
                    </a>
                    <div class="settings-topbar-sep"></div>
                    <span class="settings-topbar-title">Team Administration</span>
                </div>
                <div style="padding:32px;text-align:center;">
                    <div class="empty-hint">You are not an admin of any team.</div>
                </div>
            </div>
            <${ToastContainer} />
            <${DialogStack} />
        `;
    }

    return html`
        <div class="surface-settings" style="flex-direction:column;">
            ${/* Top Bar */``}
            <div class="settings-topbar">
                <a href="${BASE}/" class="settings-topbar-back" onClick=${backClick}>
                    <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                         stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                        <line x1="19" y1="12" x2="5" y2="12"/>
                        <polyline points="12 19 5 12 12 5"/>
                    </svg>
                    Back
                </a>
                <div class="settings-topbar-sep"></div>
                <span class="settings-topbar-title">
                    ${teamName}
                    ${adminTeams.length > 1 && html`
                        <button class="btn-small btn-ghost" style="margin-left:8px;font-size:11px;"
                                onClick=${() => setSelectedTeam(null)}>Switch Team</button>
                    `}
                </span>
            </div>

            <div style="display:flex;flex:1;min-height:0;">
                ${/* Left Nav */``}
                <div class="settings-nav">
                    ${SECTIONS.map(s => html`
                        <a key=${s.key} href="${BASE}/team-admin/${s.key}"
                           class="settings-nav-link ${section === s.key ? 'active' : ''}"
                           onClick=${navClick}>
                            ${s.label}
                        </a>
                    `)}
                </div>

                ${/* Content */``}
                <div class="settings-content">
                    <h2>${sectionLabel}</h2>
                    ${SectionComponent && teamId
                        ? html`<${SectionComponent} teamId=${teamId} />`
                        : html`<div class="settings-placeholder">Loading\u2026</div>`
                    }
                </div>
            </div>
        </div>
        <${ToastContainer} />
        <${DialogStack} />
    `;
}

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

export { TeamAdminSurface };
