import { Head, router, usePage } from '@inertiajs/react';
import { useEffect, useRef, useState } from 'react';
import { SiteLayout } from '@/components/layout/site-layout';
import { ServicesPreviewSection } from '@/components/sections/services-preview-section';

export default function ServicesIndex({ seo, services, searchQuery }) {
    const { props } = usePage();
    const { routes } = props;

    const [search, setSearch] = useState(searchQuery ?? '');
    const isFirstRender = useRef(true);

    useEffect(() => {
        if (isFirstRender.current) {
            isFirstRender.current = false;
            return;
        }

        const timeout = setTimeout(() => {
            router.get(routes?.services, { q: search || undefined }, { preserveState: true, preserveScroll: true, replace: true });
        }, 400);

        return () => clearTimeout(timeout);
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [search]);

    return (
        <SiteLayout>
            <Head>
                <title>{seo?.title}</title>
                {seo?.description && <meta name="description" content={seo.description} />}
            </Head>

            {/* Same component as the Home page — sticky "Services / My Expertise" heading +
                stacking cards — so both pages look and animate identically. */}
            {services.length === 0 ? (
                <div className="bg-background px-4 sm:px-6 py-16 text-center text-paragraph">No services match your search.</div>
            ) : (
                <ServicesPreviewSection services={services} servicesUrl={routes?.services} />
            )}
        </SiteLayout>
    );
}
