/* Componentes de layout compartilhados. Expostos via window.* */

const { useState, useEffect } = React;


function AppHeader({ current_path }) {
    const user = window.C7_STORE.get().user;
    const is_corporate = user && user.account_type === 'corporate_payer';

    // Nav diferente por account_type
    const nav = is_corporate ? [
        { path: '/dashboard',    label: 'Dashboard' },
        { path: '/pagamentos',   label: 'Pagamentos' },
        { path: '/fornecedores', label: 'Fornecedores' },
        { path: '/ordens',       label: 'Histórico' },
        { path: '/perfil',       label: 'Perfil' },
    ] : [
        { path: '/dashboard',    label: 'Dashboard' },
        { path: '/ordens',       label: 'Ordens' },
        { path: '/perfil',       label: 'Perfil' },
    ];

    const on_logout = async () => {
        await window.C7_API.logout();
        window.C7_STORE.set({ user: null });
        window.C7_ROUTER.navigate('/login');
    };

    function is_active(item_path) {
        if (!current_path) return false;
        // Exact match na raiz, prefix nos demais — evita /ordens combinar com tudo
        if (item_path === '/dashboard') return current_path === '/dashboard';
        if (item_path === '/perfil')    return current_path === '/perfil';
        return current_path.startsWith(item_path);
    }

    return (
        <header className="app-header">
            <span className="brand">CORE <span className="seven">7</span> CAPITAL</span>
            <nav>
                {nav.map(item => (
                    <a key={item.path}
                       href={'#' + item.path}
                       className={is_active(item.path) ? 'active' : ''}>
                        {item.label}
                    </a>
                ))}
            </nav>
            <div className="user-chip">
                {user && <span>{user.nome || user.email}</span>}
                <button className="logout-btn" onClick={on_logout}>sair</button>
            </div>
        </header>
    );
}


// Tela de login (/login e /login/2fa) — ja com a marca EBRO.
// O resto do app continua Core 7 por enquanto.
// O CSS vai junto do componente (e nao no app.css) porque o Cloudflare manda o
// navegador guardar os arquivos por 4 h: com CSS e JSX em arquivos separados,
// quem tinha o app.css antigo em cache via a tela nova sem estilo.
const AUTH_CSS = `
.center-screen {
    position: relative; overflow: hidden;
    min-height: 100vh; min-height: 100svh;
    display: flex; align-items: center; justify-content: center;
    padding: 28px 20px;
    font-family: "Archivo", var(--c7-font-text);
    background:
        radial-gradient(ellipse 70% 50% at 50% 0%, rgba(120, 140, 190, 0.16), transparent 70%),
        linear-gradient(180deg, #0b101c 0%, #070b14 100%);
}
.center-screen .auth-waves {
    position: absolute; left: 0; right: 0; bottom: 0;
    width: 100%; height: 42vh; pointer-events: none;
}
.center-screen .auth-wrap { position: relative; z-index: 1; width: 100%; max-width: 420px; }
.center-screen .auth-brand {
    display: flex; align-items: center; justify-content: center; gap: 12px;
    color: #f2f0ea; text-decoration: none;
}
.center-screen .auth-brand svg { width: 34px; height: 24px; }
.center-screen .auth-brand path { fill: none; stroke: currentColor; stroke-width: 4.6; stroke-linecap: round; }
.center-screen .auth-brand span {
    font-size: 26px; font-weight: 800; font-stretch: 125%; letter-spacing: 0.04em; line-height: 1;
}
.center-screen .auth-tag {
    margin: 12px 0 28px; text-align: center;
    font-size: 10px; font-weight: 600; font-stretch: 125%;
    letter-spacing: 0.32em; text-transform: uppercase; color: #7c8597;
}
.center-screen .c-card {
    width: 100%; padding: 32px; margin: 0;
    border-radius: 14px;
    background:
        radial-gradient(120% 80% at 100% 0%, rgba(120, 140, 190, 0.16), transparent 60%),
        linear-gradient(160deg, #101b38 0%, #0c1530 100%);
    border: 1px solid rgba(160, 175, 210, 0.16);
    box-shadow: 0 40px 80px -40px rgba(0, 0, 0, 0.8), 0 1px 0 rgba(255, 255, 255, 0.05) inset;
}
.center-screen .c-card h2 {
    font-family: "Archivo", sans-serif; font-size: 24px; font-weight: 300; font-stretch: 112%;
    letter-spacing: -0.01em; color: #f2f0ea; margin-bottom: 22px;
}
.center-screen .c-field label {
    font-family: "Archivo", sans-serif; font-size: 10px; font-weight: 600; font-stretch: 115%;
    letter-spacing: 0.22em; color: #7c8597;
}
.center-screen .c-field input {
    padding: 13px 14px; font-size: 15px;
    background: rgba(4, 8, 18, 0.5);
    border: 1px solid rgba(205, 214, 230, 0.10); color: #f2f0ea;
}
.center-screen .c-field input:focus { border-color: rgba(205, 214, 230, 0.4); background: rgba(4, 8, 18, 0.6); }
.center-screen .c-btn {
    padding: 14px 18px; border-radius: 3px;
    font-family: "Archivo", sans-serif; font-size: 12px; font-weight: 600; font-stretch: 118%; letter-spacing: 0.2em;
    color: #11151d; border-color: #d4d8de;
    background:
        repeating-linear-gradient(90deg, rgba(255, 255, 255, 0.05) 0 1px, transparent 1px 3px),
        linear-gradient(160deg, #f1f2f4 0%, #c9ced6 45%, #e6e9ed 60%, #b7bdc7 100%);
    box-shadow: 0 1px 0 rgba(255, 255, 255, 0.6) inset, 0 10px 30px -12px rgba(0, 0, 0, 0.6);
}
.center-screen .auth-back {
    display: block; margin-top: 22px; text-align: center;
    font-size: 12px; letter-spacing: 0.04em; color: #7c8597; text-decoration: none;
}
.center-screen .auth-back:hover { color: #f2f0ea; }
@media (max-width: 480px) {
    .center-screen .c-card { padding: 24px 20px; }
}
`;

function CenterScreen({ children }) {
    return (
        <div className="center-screen">
            <style>{AUTH_CSS}</style>
            <svg className="auth-waves" viewBox="0 0 1440 320" preserveAspectRatio="none" aria-hidden="true">
                {Array.from({ length: 14 }).map((_, i) => {
                    const y = 40 + i * i * 1.45;
                    const a = 14 + i * 2.2;
                    return <path key={i} fill="none" stroke="rgba(214,222,238,1)"
                                 strokeOpacity={0.05 + i * 0.012} strokeWidth={0.6 + i * 0.06}
                                 d={`M0 ${y} C 360 ${y - a}, 720 ${y + a}, 1080 ${y - a * 0.4} S 1440 ${y + a * 0.3}, 1440 ${y}`} />;
                })}
            </svg>
            <div className="auth-wrap">
                <a className="auth-brand" href="/" aria-label="EBRO">
                    <svg viewBox="0 0 40 28" aria-hidden="true">
                        <path d="M3.5 12.5C11 6.5 20 12.5 36.5 5.5" />
                        <path d="M3.5 23C11 17 20 23 36.5 16" />
                    </svg>
                    <span>EBRO</span>
                </a>
                <div className="auth-tag">Câmbio &amp; Pagamentos</div>
                <div className="c-card">{children}</div>
                <a className="auth-back" href="/">← Voltar ao site</a>
            </div>
        </div>
    );
}


function AppFooter() {
    const year = new Date().getFullYear();
    return (
        <footer className="app-footer">
            <div className="app-footer-inner">
                <div className="app-footer-links">
                    <a href="#/termos">Termos de uso</a>
                    <span className="app-footer-sep">·</span>
                    <a href="#/privacidade">Política de privacidade</a>
                    <span className="app-footer-sep">·</span>
                    <a href="mailto:suporte@core7cap.com">Suporte</a>
                </div>
                <div className="app-footer-copy">
                    © {year} Core 7 Capital Intermediações em Negócios Ltda — CNPJ 57.517.361/0001-27
                </div>
            </div>
        </footer>
    );
}


function BackBar() {
    // Pega o path REAL da URL (nao o current_path do AppShell, que e usado
    // so pra highlight do menu — paginas filhas passam o pai pra mostrar
    // o link do menu ativo).
    const [path, setPath] = useState(window.C7_ROUTER.current().path);
    useEffect(() => window.C7_ROUTER.subscribe(r => setPath(r.path)), []);

    if (!path) return null;
    // Esconde nas paginas do menu — so aparece em paginas alcancadas
    // por botoes (ex: /ordens/nova, /ordens/<id>, /change-password).
    const HEADER_PATHS = new Set([
        '/dashboard', '/ordens', '/perfil',
        '/fornecedores', '/pagamentos',
    ]);
    if (HEADER_PATHS.has(path)) return null;

    function on_back() {
        if (window.history.length > 1) {
            window.history.back();
        } else {
            window.C7_ROUTER.navigate('/dashboard');
        }
    }

    return (
        <div className="app-back-bar">
            <button onClick={on_back} className="app-back-btn">
                ← Voltar
            </button>
        </div>
    );
}


function EmailVerifyBanner() {
    const [user, setUser] = useState(window.C7_STORE.get().user);
    const [sending, setSending] = useState(false);
    const [sent, setSent] = useState(false);

    useEffect(() => window.C7_STORE.subscribe(s => setUser(s.user)), []);

    if (!user || user.email_verified_at) return null;

    async function on_resend() {
        if (sending) return;
        setSending(true);
        try {
            await window.C7_API.post('/auth/resend-verification');
            setSent(true);
        } catch (e) {}
        finally { setSending(false); }
    }

    return (
        <div className="email-verify-banner">
            <span>
                Confirme seu email <strong>{user.email}</strong> pra liberar
                criação de ordens, cadastro de carteira e troca de senha.
            </span>
            <button onClick={on_resend} disabled={sending || sent}>
                {sent ? '✓ enviado' : (sending ? 'enviando…' : 'reenviar email')}
            </button>
            <style>{`
                .email-verify-banner {
                    display: flex; align-items: center; gap: 14px;
                    padding: 10px 18px;
                    background: rgba(255,200,87,0.08);
                    border-bottom: 1px solid rgba(255,200,87,0.3);
                    color: #ffc857;
                    font-family: var(--c7-font-mono, monospace);
                    font-size: 12px; line-height: 1.4;
                }
                .email-verify-banner span { flex: 1; }
                .email-verify-banner strong { color: var(--c7-platinum); }
                .email-verify-banner button {
                    flex: 0 0 auto;
                    background: transparent;
                    border: 1px solid rgba(255,200,87,0.5);
                    color: #ffc857;
                    padding: 6px 14px;
                    font-family: var(--c7-font-mono, monospace);
                    font-size: 11px; letter-spacing: 0.12em;
                    text-transform: uppercase; cursor: pointer;
                    border-radius: 2px;
                }
                .email-verify-banner button:hover:not(:disabled) {
                    background: rgba(255,200,87,0.12);
                }
                .email-verify-banner button:disabled {
                    opacity: 0.5; cursor: default;
                }
                @media (max-width: 640px) {
                    .email-verify-banner { flex-direction: column; align-items: stretch; }
                }
            `}</style>
        </div>
    );
}


function AppShell({ current_path, children }) {
    return (
        <div className="app-shell">
            <AppHeader current_path={current_path} />
            <EmailVerifyBanner />
            <main className="app-main">
                <BackBar />
                {children}
            </main>
            <AppFooter />
        </div>
    );
}


window.C7_Layout = { AppHeader, CenterScreen, AppShell, AppFooter, BackBar };
