export type JourneyWidgetId =
    | 'overview'
    | 'top_pages'
    | 'funnel'
    | 'auth'
    | 'exit_intent'
    | 'commerce'
    | 'acquisition'
    | 'wedding'
    | 'search'
    | 'entry_exit'
    | 'link_clicks'
    | 'item_cart';

export type JourneyWidgetSize = 'half' | 'full';

export type JourneyLayoutItem = {
    id: JourneyWidgetId;
    size: JourneyWidgetSize;
};

export type JourneyLayoutState = {
    version: 1;
    items: JourneyLayoutItem[];
};

export type JourneyWidgetDef = {
    id: JourneyWidgetId;
    title: string;
    description: string;
    defaultSize: JourneyWidgetSize;
};

export const JOURNEY_WIDGET_DEFS: JourneyWidgetDef[] = [
    {
        id: 'overview',
        title: 'General',
        description: 'Snapshot metrik + realtime active users ',
        defaultSize: 'full',
    },
    {
        id: 'top_pages',
        title: 'Landing pages',
        description: 'Halaman pertama saat session dimulai (entry page)',
        defaultSize: 'half',
    },
    {
        id: 'funnel',
        title: 'Purchase Journey',
        description: 'Funnel chart, donat, step conversion, dan tabel order sukses',
        defaultSize: 'full',
    },
    {
        id: 'auth',
        title: 'Auth',
        description: 'Login & signup success rate',
        defaultSize: 'half',
    },
    {
        id: 'exit_intent',
        title: 'Exit intent',
        description: 'Modal shown & unlock rate',
        defaultSize: 'half',
    },
    {
        id: 'commerce',
        title: 'Product insights',
        description: 'ATC, purchase, top products',
        defaultSize: 'half',
    },
    {
        id: 'acquisition',
        title: 'Acquisition',
        description: 'Channel/campaign acquisition breakdown + trend',
        defaultSize: 'full',
    },
    {
        id: 'wedding',
        title: 'Wedding funnel',
        description: 'Preview → checkout / order',
        defaultSize: 'half',
    },
    {
        id: 'search',
        title: 'Search insights',
        description: 'Search sessions & top queries',
        defaultSize: 'half',
    },
    {
        id: 'item_cart',
        title: 'Add to Cart Item',
        description: 'Views, add to cart, pembelian, dan revenue per item',
        defaultSize: 'full',
    },
    {
        id: 'entry_exit',
        title: 'Entry & exit pages',
        description: 'Top entry / exit path',
        defaultSize: 'full',
    },
    {
        id: 'link_clicks',
        title: 'Aurum Linktree',
        description: 'Click links from Shopee, Tokopedia, TikTok, etc. from the /links page',
        defaultSize: 'full',
    },
];

export const JOURNEY_WIDGET_MAP = Object.fromEntries(
    JOURNEY_WIDGET_DEFS.map((d) => [d.id, d])
) as Record<JourneyWidgetId, JourneyWidgetDef>;

/** Default B: Overview + Funnel + Top pages */
export const DEFAULT_JOURNEY_LAYOUT: JourneyLayoutState = {
    version: 1,
    items: [
        { id: 'overview', size: 'full' },
        { id: 'funnel', size: 'full' },
    ],
};

export const JOURNEY_LAYOUT_STORAGE_KEY = 'au_uj_layout_v1';

export function loadJourneyLayout(): JourneyLayoutState {
    if (typeof window === 'undefined') return DEFAULT_JOURNEY_LAYOUT;
    try {
        const raw = localStorage.getItem(JOURNEY_LAYOUT_STORAGE_KEY);
        if (!raw) return DEFAULT_JOURNEY_LAYOUT;
        const parsed = JSON.parse(raw) as JourneyLayoutState;
        if (parsed?.version !== 1 || !Array.isArray(parsed.items)) {
            return DEFAULT_JOURNEY_LAYOUT;
        }
        const seen = new Set<string>();
        const valid = parsed.items
            .map((item) =>
                String(item?.id) === 'funnel_table' ? { ...item, id: 'funnel' as JourneyWidgetId } : item
            )
            .filter((item) => {
                if (!item?.id || !JOURNEY_WIDGET_MAP[item.id as JourneyWidgetId]) return false;
                if (seen.has(item.id)) return false;
                seen.add(item.id);
                return true;
            }) as JourneyLayoutItem[];
        if (!valid.length) return DEFAULT_JOURNEY_LAYOUT;
        return { version: 1, items: valid };
    } catch {
        return DEFAULT_JOURNEY_LAYOUT;
    }
}

export function saveJourneyLayout(state: JourneyLayoutState) {
    if (typeof window === 'undefined') return;
    try {
        localStorage.setItem(JOURNEY_LAYOUT_STORAGE_KEY, JSON.stringify(state));
    } catch {
        // ignore quota
    }
}

export function getAvailableWidgets(items: JourneyLayoutItem[]): JourneyWidgetDef[] {
    const used = new Set(items.map((item) => item.id));
    return JOURNEY_WIDGET_DEFS.filter((def) => !used.has(def.id));
}
