/**
 * LoginSurface — root login surface component
 *
 * Reads globals from Go template:
 *   __BASE__               — base path
 *   __AUTH_MODE__           — 'builtin' | 'oidc' | 'mtls'
 *   __REGISTRATION_OPEN__  — boolean
 *   __BANNER__             — { visible, text, background, color } or null
 *   __VERSION__            — app version string
 *   __ENVIRONMENT__        — environment label or null
 *
 * Handles OIDC callback (#oidc_result=<base64>).
 */
const { html } = window;
const { useState, useEffect, useCallback } = hooks;
const { render } = preact;

import { Hero } from './hero.js';
import { LoginForm } from './login-form.js';
import { RegisterForm } from './register-form.js';
import { SSOPanel } from './sso-panel.js';

function LoginSurface() {
    const BASE     = window.__BASE__ || '';
    const authMode = window.__AUTH_MODE__ || 'builtin';
    const regOpen  = window.__REGISTRATION_OPEN__ || false;
    const banner   = window.__BANNER__ || null;
    const version  = window.__VERSION__ || '';
    const env      = window.__ENVIRONMENT__ || null;

    const [tab, setTab] = useState('login'); // 'login' | 'register'

    // ── OIDC callback handler (runs once on mount) ──
    useEffect(() => {
        const hash = window.location.hash;
        if (!hash.startsWith('#oidc_result=')) return;
        try {
            const encoded = hash.slice('#oidc_result='.length);
            const json = atob(encoded);
            const data = JSON.parse(json);
            sw.auth._setAuth(data);
            window.location.replace(BASE + '/');
        } catch (e) {
            console.error('[login] Failed to process OIDC callback:', e);
        }
    }, []);

    const switchToLogin = useCallback(() => setTab('login'), []);

    const heading = tab === 'login'
        ? { title: 'Welcome back', sub: 'Sign in to your Switchboard instance' }
        : { title: 'Create account', sub: 'Join your team on Switchboard' };

    return html`
        <div class="login-shell">
            ${banner?.visible && html`
                <div class="login-banner"
                     style="background:${banner.background};color:${banner.color};">
                    ${banner.text}
                </div>
            `}

            <div class="login-main">
                <${Hero} base=${BASE} version=${version} env=${env} />

                <div class="login-auth-panel">
                    <div class="login-auth-inner">
                        <div class="login-auth-heading login-anim login-anim-a1">
                            <h2>${heading.title}</h2>
                            <p>${heading.sub}</p>
                        </div>

                        ${authMode === 'oidc' || authMode === 'mtls'
                            ? html`<${SSOPanel} mode=${authMode} base=${BASE} />`
                            : html`
                                ${regOpen && html`
                                    <div class="login-auth-tabs login-anim login-anim-a2">
                                        <button class="login-auth-tab ${tab === 'login' ? 'active' : ''}"
                                                onClick=${() => setTab('login')}>Log In</button>
                                        <button class="login-auth-tab ${tab === 'register' ? 'active' : ''}"
                                                onClick=${() => setTab('register')}>Register</button>
                                    </div>
                                `}

                                ${tab === 'login'
                                    ? html`<${LoginForm} />`
                                    : html`<${RegisterForm} onPending=${switchToLogin} />`
                                }
                            `
                        }

                        <div class="login-auth-footer">
                            <p>Self-hosted instance \u00B7 Your data stays on your infrastructure</p>
                        </div>
                    </div>
                </div>
            </div>

            ${banner?.visible && html`
                <div class="login-banner"
                     style="background:${banner.background};color:${banner.color};">
                    ${banner.text}
                </div>
            `}
        </div>
    `;
}

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

export { LoginSurface };
