import { getCollection } from 'astro:content';

import type {
    CollectionName,
    CtaLink,
    FooterLead,
    FooterNavigationGroup,
    NavigationItem,
    PageDefinition,
    PageFamily,
    ShellTone,
    SitePath,
    SiteMetadata,
    SurfaceAvailability,
    VisualFoundationContract,
} from '@/types/site';

export const siteMetadata: SiteMetadata = {
    siteName: 'TenantAtlas',
    siteTagline: 'Governance of record for Microsoft tenant operations.',
    siteDescription:
        'TenantAtlas helps MSP and enterprise teams keep Microsoft tenant change history observable, reviewable, and safer to operate.',
    siteUrl: import.meta.env.PUBLIC_SITE_URL ?? 'https://tenantatlas.example',
};

export const visualFoundationContract: VisualFoundationContract = {
    pageFamilies: ['landing', 'trust', 'content'],
    ctaHierarchy: ['primary', 'secondary', 'ghost'],
    requiredColorRoles: [
        'background',
        'foreground',
        'muted',
        'muted-foreground',
        'card',
        'card-foreground',
        'border',
        'input',
        'primary',
        'primary-foreground',
        'secondary',
        'secondary-foreground',
        'accent',
        'accent-foreground',
        'success',
        'warning',
        'destructive',
        'info',
    ],
    accessibilityBaseline: [
        'focus-visible',
        'readable-contrast',
        'non-color-only-semantics',
        'navigation-vs-cta-differentiation',
        'mobile-readable-density',
    ],
    surfaceLayers: ['page-background', 'default-content', 'card', 'elevated', 'muted-inset', 'highlighted'],
};

type CollectionGatedNavigationItem = NavigationItem & {
    collection?: CollectionName;
};

interface FooterGroupSeed {
    collection?: CollectionName;
    items: CollectionGatedNavigationItem[];
    title: string;
}

export const contactCta: CtaLink = {
    href: '/contact',
    label: 'Request a working session',
    helper: 'Bring your governance questions, rollout concerns, or evaluation goals.',
    variant: 'primary',
};

const footerLeadByFamily: Record<PageFamily, FooterLead> = {
    landing: {
        eyebrow: 'Keep the next move obvious',
        title: 'Product, trust, progress, and contact should stay connected.',
        description:
            'Landing pages should move visitors from orientation into product understanding, trust review, changelog proof, or the contact path without fake maturity signals.',
        intent: 'conversion',
        primaryCta: contactCta,
    },
    trust: {
        eyebrow: 'Trust stays actionable',
        title: 'Trust, legal context, and the next conversation should reinforce one another.',
        description:
            'Trust-oriented pages should keep legal context, product posture, and the working-session route connected instead of turning diligence into friction.',
        intent: 'guidance',
        primaryCta: {
            href: '/contact',
            label: 'Discuss trust requirements',
            helper: 'Bring current review, legal, or rollout questions into one working conversation.',
            variant: 'primary',
        },
    },
    content: {
        eyebrow: 'Reading should still progress',
        title: 'Supporting pages should still route visitors back into the core journey.',
        description:
            'Changelog, contact, legal, privacy, imprint, and retained secondary routes should feel deliberate and connected to the evaluation path instead of behaving like detached documents.',
        intent: 'legal',
        primaryCta: {
            href: '/contact',
            label: 'Continue the evaluation path',
            helper: 'Move from the reading surface back into a product or trust conversation.',
            variant: 'primary',
        },
    },
};

const headerCtaByFamily: Record<PageFamily, CtaLink> = {
    landing: {
        href: '/contact',
        label: 'Request a working session',
        helper: 'Bring your governance questions, rollout concerns, or evaluation goals.',
        variant: 'secondary',
    },
    trust: {
        href: '/contact',
        label: 'Discuss trust requirements',
        helper: 'Route trust, legal, or rollout questions into one conversation.',
        variant: 'secondary',
    },
    content: {
        href: '/contact',
        label: 'Start the contact path',
        helper: 'Turn the reading path into a concrete next step.',
        variant: 'secondary',
    },
};

export const canonicalCoreRoutes: SitePath[] = [
    '/',
    '/product',
    '/trust',
    '/changelog',
    '/contact',
    '/privacy',
    '/imprint',
];

export const retainedSecondaryRoutes: SitePath[] = ['/legal', '/terms', '/solutions', '/integrations'];
export const compatibilityRoutes: SitePath[] = ['/security-trust'];
export const primaryConversionRoute: SitePath = '/contact';
export const unpublishedEditorialCollections: CollectionName[] = ['articles'];

export async function getSurfaceAvailability(): Promise<SurfaceAvailability> {
    const changelog = await getCollection('changelog');

    return {
        articles: false,
        changelog: changelog.some((entry) => entry.data.draft !== true),
        resources: false,
    };
}

const primaryNavigationSeeds: CollectionGatedNavigationItem[] = [
    { href: '/product', label: 'Product', description: 'See how the product connects backup, restore, drift, and evidence.' },
    { href: '/trust', label: 'Trust', description: 'Review the operating posture and bounded public claims.' },
    { href: '/changelog', label: 'Changelog', description: 'Inspect dated product progress instead of placeholder content.' },
    { href: '/resources', label: 'Resources', description: 'Optional deeper content when substantive material exists.', collection: 'resources' },
    { href: '/contact', label: 'Contact', description: 'Move into a working session with one clear next step.' },
];

const footerNavigationGroupSeeds: FooterGroupSeed[] = [
    {
        title: 'Product',
        items: [
            { href: '/product', label: 'Product' },
            { href: '/changelog', label: 'Changelog' },
        ],
    },
    {
        title: 'Trust & Legal',
        items: [
            { href: '/trust', label: 'Trust' },
            { href: '/privacy', label: 'Privacy' },
            { href: '/imprint', label: 'Imprint' },
            { href: '/terms', label: 'Terms' },
        ],
    },
    {
        title: 'Contact',
        items: [{ href: '/contact', label: 'Contact' }],
    },
    {
        title: 'Content',
        collection: 'resources',
        items: [{ href: '/resources', label: 'Resources', collection: 'resources' }],
    },
];

function filterCollectionGatedItems(
    items: CollectionGatedNavigationItem[],
    availability: SurfaceAvailability,
): NavigationItem[] {
    return items
        .filter((item) => {
            if (!item.collection) {
                return true;
            }

            return availability[item.collection];
        })
        .map(({ collection: _collection, ...item }) => item);
}

export async function getPrimaryNavigation(): Promise<NavigationItem[]> {
    const availability = await getSurfaceAvailability();

    return filterCollectionGatedItems(primaryNavigationSeeds, availability);
}

export async function getFooterNavigationGroups(): Promise<FooterNavigationGroup[]> {
    const availability = await getSurfaceAvailability();

    return footerNavigationGroupSeeds
        .filter((group) => (group.collection ? availability[group.collection] : true))
        .map(({ collection: _collection, items, title }) => ({
            title,
            items: filterCollectionGatedItems(items, availability),
        }))
        .filter((group) => group.items.length > 0);
}

export const pageDefinitions: Record<SitePath, PageDefinition> = {
    '/': {
        path: '/',
        canonicalPath: '/',
        pageRole: 'home',
        family: 'landing',
        shellTone: 'brand',
        priority: 'required',
        journeyStage: 'entry',
        surfaceGroup: 'core',
        inSitemap: true,
    },
    '/product': {
        path: '/product',
        canonicalPath: '/product',
        pageRole: 'product',
        family: 'landing',
        shellTone: 'brand',
        priority: 'required',
        journeyStage: 'first-clarification',
        surfaceGroup: 'core',
        inSitemap: true,
    },
    '/trust': {
        path: '/trust',
        canonicalPath: '/trust',
        pageRole: 'trust',
        family: 'trust',
        shellTone: 'trust',
        priority: 'required',
        journeyStage: 'deepening',
        surfaceGroup: 'core',
        inSitemap: true,
    },
    '/changelog': {
        path: '/changelog',
        canonicalPath: '/changelog',
        pageRole: 'changelog',
        family: 'content',
        shellTone: 'neutral',
        priority: 'recommended',
        journeyStage: 'deepening',
        surfaceGroup: 'core',
        inSitemap: true,
    },
    '/contact': {
        path: '/contact',
        canonicalPath: '/contact',
        pageRole: 'contact',
        family: 'content',
        shellTone: 'neutral',
        priority: 'required',
        journeyStage: 'action',
        surfaceGroup: 'core',
        inSitemap: true,
    },
    '/privacy': {
        path: '/privacy',
        canonicalPath: '/privacy',
        pageRole: 'privacy',
        family: 'content',
        shellTone: 'neutral',
        priority: 'required',
        journeyStage: 'deepening',
        surfaceGroup: 'legal',
        inSitemap: true,
    },
    '/imprint': {
        path: '/imprint',
        canonicalPath: '/imprint',
        pageRole: 'imprint',
        family: 'content',
        shellTone: 'neutral',
        priority: 'required',
        journeyStage: 'deepening',
        surfaceGroup: 'legal',
        inSitemap: true,
    },
    '/legal': {
        path: '/legal',
        canonicalPath: '/legal',
        pageRole: 'legal',
        family: 'content',
        shellTone: 'trust',
        priority: 'secondary',
        journeyStage: 'deepening',
        surfaceGroup: 'legal',
        inSitemap: true,
    },
    '/terms': {
        path: '/terms',
        canonicalPath: '/terms',
        pageRole: 'terms',
        family: 'content',
        shellTone: 'neutral',
        priority: 'secondary',
        journeyStage: 'deepening',
        surfaceGroup: 'legal',
        inSitemap: true,
    },
    '/solutions': {
        path: '/solutions',
        canonicalPath: '/solutions',
        pageRole: 'solutions',
        family: 'content',
        shellTone: 'neutral',
        priority: 'secondary',
        journeyStage: 'deepening',
        surfaceGroup: 'supporting',
        inSitemap: true,
    },
    '/integrations': {
        path: '/integrations',
        canonicalPath: '/integrations',
        pageRole: 'integrations',
        family: 'content',
        shellTone: 'neutral',
        priority: 'secondary',
        journeyStage: 'deepening',
        surfaceGroup: 'supporting',
        inSitemap: true,
    },
    '/security-trust': {
        path: '/security-trust',
        canonicalPath: '/trust',
        pageRole: 'trust',
        family: 'trust',
        shellTone: 'trust',
        priority: 'compatibility',
        journeyStage: 'deepening',
        surfaceGroup: 'compatibility',
        inSitemap: false,
    },
};

export const publishedSitemapRoutes = [...canonicalCoreRoutes, ...retainedSecondaryRoutes];

export function getPageDefinition(path: string): PageDefinition {
    return pageDefinitions[path as SitePath] ?? pageDefinitions['/'];
}

export function getCanonicalPath(path: string): SitePath {
    return getPageDefinition(path).canonicalPath;
}

export function getPageFamily(path: string): PageFamily {
    return getPageDefinition(path).family;
}

export function getShellTone(path: string): ShellTone {
    return getPageDefinition(path).shellTone;
}

export function getHeaderCta(path: string): CtaLink {
    const definition = getPageDefinition(path);

    return {
        ...headerCtaByFamily[definition.family],
        ...definition.headerCta,
    };
}

export function getFooterLead(path: string): FooterLead {
    const definition = getPageDefinition(path);

    return {
        ...footerLeadByFamily[definition.family],
        ...definition.footerLead,
    };
}

export function isActiveNavigationPath(currentPath: string, href: string): boolean {
    if (href === '/') {
        return currentPath === '/';
    }

    return currentPath === href || currentPath.startsWith(`${href}/`);
}
