import {createRouter, createWebHashHistory} from 'vue-router';
import Home from './views/Home.vue';
import Product from './views/Product.vue';
import CategoriesList from "./views/CategoriesList.vue";
import Cart from "./views/Cart.vue";
import Products from "@/views/Products.vue";
import Checkout from "@/views/Checkout.vue";
import OrderCreated from "@/views/OrderCreated.vue";
import Search from "@/views/Search.vue";
import Filters from "@/views/Filters.vue";
import Account from "@/views/Account.vue";
import {useYaMetrikaStore} from "@/stores/yaMetrikaStore.js";

const routes = [
    {
        path: '/',
        name: 'home',
        component: Home,
    },
    {path: '/filters', name: 'filters', component: Filters},
    {path: '/product/:id', name: 'product.show', component: Product},
    {
        path: '/products/:category_id',
        name: 'product.categories.show',
        component: Products,
    },
    {path: '/categories', name: 'categories', component: CategoriesList},
    {path: '/category/:id', name: 'category.show', component: CategoriesList},
    {path: '/cart', name: 'cart', component: Cart},
    {path: '/checkout', name: 'checkout', component: Checkout},
    {path: '/success', name: 'order_created', component: OrderCreated},
    {path: '/search', name: 'search', component: Search},
    {path: '/account', name: 'account', component: Account},
];

export const router = createRouter({
    history: createWebHashHistory('/image/catalog/tgshopspa/'),
    routes,
    scrollBehavior(to, from, savedPosition) {
        // Для страницы товара всегда скроллим наверх мгновенно
        if (to.name === 'product.show') {
            return {top: 0, behavior: 'instant'};
        }

        // Для страницы категории скролл будет восстановлен в компоненте через onActivated
        // Здесь просто предотвращаем автоматический скролл наверх
        if (to.name === 'product.categories.show') {
            // Если возвращаемся назад на категорию - используем savedPosition
            if (savedPosition) {
                return savedPosition;
            }
            return false; // Не скроллить автоматически
        }

        // Для остальных страниц используем savedPosition если есть, иначе наверх
        if (savedPosition) {
            return savedPosition;
        }

        return {top: 0, behavior: 'smooth'};
    },
});

router.beforeEach((to, from, next) => {
    const ym = useYaMetrikaStore();
    ym.prevPath = from.path;
    next();
});

