"use client";

import { useEffect, useRef, useState } from "react";
import { usePathname } from "next/navigation";
import { LicenseBanner } from "@/components/LicenseBanner";
import { Logo } from "@/components/Logo";
import { Sidebar, SidebarDrawer } from "@/components/Sidebar";
import { useAuth } from "@/components/AuthProvider";

function MenuIcon() {
    return (
        <svg className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
            <path strokeLinecap="round" strokeLinejoin="round" d="M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5" />
        </svg>
    );
}

/**
 * Owns the responsive chrome so app/(app)/layout.tsx can stay a server
 * component. Above lg this is the layout it always was; below lg the sidebar
 * becomes an offcanvas behind the top bar's hamburger.
 */
export function AppShell({ children }: { children: React.ReactNode }) {
    const [open, setOpen] = useState(false);
    const pathname = usePathname();
    const buttonRef = useRef<HTMLButtonElement>(null);
    const { instance } = useAuth();

    // A drawer that survives navigation would cover the page you just asked for.
    useEffect(() => {
        setOpen(false);
    }, [pathname]);

    function close() {
        setOpen(false);
        buttonRef.current?.focus();
    }

    return (
        <div className="flex h-screen overflow-hidden">
            <Sidebar />
            <SidebarDrawer open={open} onClose={close} />

            <div className="flex min-w-0 flex-1 flex-col overflow-y-auto">
                <header className="sticky top-0 z-40 flex h-14 shrink-0 items-center gap-3 border-b border-border bg-surface px-3 lg:hidden">
                    <button
                        ref={buttonRef}
                        type="button"
                        onClick={() => setOpen(true)}
                        aria-label="Open navigation"
                        aria-expanded={open}
                        aria-controls="app-sidebar-drawer"
                        className="-ml-1 rounded p-2 text-text-secondary transition-colors hover:bg-surface-2 hover:text-text-primary"
                    >
                        <MenuIcon />
                    </button>
                    <Logo className="h-7 w-7 shrink-0 text-logo" />
                    <div className="min-w-0">
                        <span className="block text-sm font-extrabold leading-tight tracking-[-0.035em] text-text-primary">Vantage</span>
                        {instance && (
                            <span className="block truncate font-mono text-[0.62rem] uppercase tracking-[0.1em] text-text-secondary">{instance.name}</span>
                        )}
                    </div>
                </header>

                <main className="flex min-w-0 flex-1 flex-col">
                    <LicenseBanner />
                    {children}
                </main>
            </div>
        </div>
    );
}
