import InsightsStore from '../insights/store/insights-store';
import TotalClicks from '../insights/widgets/total-clicks';
import MostPopularLinks from '../insights/widgets/most-popular-links';
import RecentClicks from '../insights/widgets/recent-clicks';

import SharedDateRangeSelector from '../insights/ui/date-range-selector';
import SharedLinkSelector from '../insights/ui/link-selector';
import { initLinkTitleFilters } from '../insights/ui/link-title-cell';
import { initDrilldownTriggers } from '../insights/drilldown/triggers';

document.addEventListener('DOMContentLoaded', function () {
    let store;
    
    if (!store) {
        store = new InsightsStore();
    }

    const dateRangeSelector = new SharedDateRangeSelector(store);
    const linkSelector = new SharedLinkSelector(store);

    dateRangeSelector.init();
    linkSelector.init();
    initDrilldownTriggers(store);
    initLinkTitleFilters(store, linkSelector);

    

    const totalClicks = new TotalClicks(store, dateRangeSelector);
    const mostPopularLinks = new MostPopularLinks(store);
    const recentClicks = new RecentClicks(store);

    totalClicks.init();
    mostPopularLinks.init();
    recentClicks.init();

    

    store.subscribe((snapshot) => {
        const responseFilters = snapshot?.context?.filters;
        if (
            store.filters.preset === 'since_start' &&
            responseFilters?.preset === 'since_start' &&
            responseFilters?.since_start &&
            snapshot.context.resolved_period?.start &&
            snapshot.context.resolved_period?.end
        ) {
            const start = new Date(snapshot.context.resolved_period.start + 'T00:00:00');
            const end = new Date(snapshot.context.resolved_period.end + 'T00:00:00');
            dateRangeSelector.updateDateRange(start, end, 'since_start', true);
        }
    });

    dateRangeSelector.triggerInitialLoad();
});
