"use client";
import { useContext, useState, useEffect, useRef } from "react";
import { NavigationStoreContext } from "./context.js";
/**
 * SSR module-level state.
 * Populated by initSegmentsSync before React renders.
 * Used by useState initializer during SSR.
 */
let ssrSegmentOrder = [];
let ssrPathname = "/";
/**
 * Filter segment IDs to only include routes and layouts.
 * Excludes parallels (contain .@) and loaders (contain D followed by digit).
 */
function filterSegmentOrder(matched) {
    return matched.filter((id) => {
        if (id.includes(".@"))
            return false;
        if (/D\d+\./.test(id))
            return false;
        return true;
    });
}
/**
 * Initialize segments data synchronously for SSR.
 * Called before rendering to populate state for useState initializer.
 *
 * @param matched - Segment order from RSC metadata
 * @param pathname - Current pathname
 */
export function initSegmentsSync(matched, pathname) {
    ssrSegmentOrder = filterSegmentOrder(matched ?? []);
    ssrPathname = pathname ?? "/";
}
/**
 * Shallow equality check for selector results
 */
function shallowEqual(a, b) {
    if (Object.is(a, b))
        return true;
    if (typeof a !== "object" ||
        a === null ||
        typeof b !== "object" ||
        b === null) {
        return false;
    }
    const keysA = Object.keys(a);
    const keysB = Object.keys(b);
    if (keysA.length !== keysB.length)
        return false;
    for (const key of keysA) {
        if (!Object.hasOwn(b, key) ||
            !Object.is(a[key], b[key])) {
            return false;
        }
    }
    return true;
}
/**
 * Parse pathname into path segments
 * /shop/products/123 → ["shop", "products", "123"]
 */
function parsePathname(pathname) {
    return pathname.split("/").filter(Boolean);
}
/**
 * Build segments state from event controller
 */
function buildSegmentsState(location, segmentOrder) {
    return {
        path: parsePathname(location.pathname),
        segmentIds: segmentOrder,
        location,
    };
}
/**
 * Build SSR state from module-level variables
 */
function buildSsrState() {
    const location = new URL(ssrPathname, "http://localhost");
    return {
        path: parsePathname(ssrPathname),
        segmentIds: ssrSegmentOrder,
        location,
    };
}
export function useSegments(selector) {
    const ctx = useContext(NavigationStoreContext);
    // Build initial state from SSR module state or event controller
    const [state, setState] = useState(() => {
        // During SSR or when no context, use module-level SSR state
        if (typeof document === "undefined" || !ctx) {
            const ssrState = buildSsrState();
            return selector ? selector(ssrState) : ssrState;
        }
        // On client with context, use event controller state
        const navState = ctx.eventController.getState();
        const handleState = ctx.eventController.getHandleState();
        const segmentsState = buildSegmentsState(navState.location, handleState.segmentOrder);
        return selector ? selector(segmentsState) : segmentsState;
    });
    const prevState = useRef(state);
    // Subscribe to both navigation state and handle state changes
    useEffect(() => {
        if (!ctx) {
            return;
        }
        const updateState = () => {
            const navState = ctx.eventController.getState();
            const handleState = ctx.eventController.getHandleState();
            const segmentsState = buildSegmentsState(navState.location, handleState.segmentOrder);
            const nextSelected = selector ? selector(segmentsState) : segmentsState;
            if (!shallowEqual(nextSelected, prevState.current)) {
                prevState.current = nextSelected;
                setState(nextSelected);
            }
        };
        // Initial update in case SSR state differs from client state
        updateState();
        // Subscribe to both state sources
        const unsubscribeNav = ctx.eventController.subscribe(updateState);
        const unsubscribeHandles = ctx.eventController.subscribeToHandles(updateState);
        return () => {
            unsubscribeNav();
            unsubscribeHandles();
        };
    }, [selector]);
    return state;
}
//# sourceMappingURL=use-segments.js.map