import { router } from '@inertiajs/react';
import type { MouseEvent } from 'react';
import { ContourArt } from '@/site/components/art/contour-art';
import { MediaSlot } from '@/site/components/media/media-slot';
import { Reveal } from '@/site/components/motion/reveal';
import { CardGrid } from '@/site/components/sections/card-grid';
import { CtaBand } from '@/site/components/sections/cta-band';
import {
    heroFrame,
    PageHero,
    sheet,
} from '@/site/components/sections/page-hero';
import { PostCard, PostMeta } from '@/site/components/sections/post-card';
import { ButtonLink } from '@/site/components/ui/button';
import { SectionHeading } from '@/site/components/ui/heading';
import { ArrowRight } from '@/site/components/ui/icons';
import { SiteLink } from '@/site/components/ui/link';
import { useSectionSpy } from '@/site/hooks/use-section-spy';
import { useShared } from '@/site/hooks/use-shared';
import { formatDate, useT } from '@/site/i18n';
import { cx } from '@/site/lib/cx';
import type { PostCard as PostCardData, PostDetail } from '@/site/types';

type BlogShowProps = {
    post: PostDetail;
    related: PostCardData[];
    blogUrl: string;
    contactUrl: string;
};

/**
 * A blog post: hero, then the article with its table of contents beside
 * it (the line at the top of the window shows how far along the reader is).
 */
export default function BlogShow({
    post,
    related,
    blogUrl,
    contactUrl,
}: BlogShowProps) {
    const { locale } = useShared();
    const t = useT();
    const { category } = post;
    // The heading being read: its entry in the contents is marked.
    const reading = useSectionSpy(post.toc.map((entry) => entry.id));

    // Links inside the article are plain HTML: route the ones that stay on
    // the site through Inertia so they do not reload the page.
    const followInternalLinks = (event: MouseEvent<HTMLElement>) => {
        const link = (event.target as HTMLElement).closest('a');
        const href = link?.getAttribute('href');

        if (
            href?.startsWith('/') &&
            !event.defaultPrevented &&
            !event.metaKey &&
            !event.ctrlKey &&
            !event.shiftKey &&
            event.button === 0
        ) {
            event.preventDefault();
            router.visit(href);
        }
    };

    return (
        <div data-accent={category?.accent}>
            <PageHero
                accent={category?.accent}
                title={post.title}
                lead={post.excerpt}
                visual={
                    <MediaSlot
                        media={post.media}
                        priority
                        sizes="(min-width: 64rem) 40vw, 24rem"
                        className={heroFrame}
                        fallback={<ContourArt seed={post.key} alive />}
                    />
                }
                eyebrow={
                    category ? (
                        <SiteLink
                            href={category.url}
                            className="transition-opacity hover:opacity-80"
                        >
                            <span lang={category.lang ?? undefined}>
                                {category.name}
                            </span>
                        </SiteLink>
                    ) : (
                        t.blog.eyebrow
                    )
                }
            >
                <PostMeta post={post} />
            </PageHero>

            <section className={cx('stage-light section-y-sm', sheet)}>
                <div className="shell grid gap-12 lg:grid-cols-12">
                    {post.toc.length > 1 ? (
                        <nav aria-label={t.blog.toc} className="lg:col-span-3">
                            <div className="lg:sticky lg:top-[calc(var(--header-h)+2rem)]">
                                <p className="text-eyebrow text-soft font-semibold uppercase">
                                    {t.blog.toc}
                                </p>
                                <ol className="border-line mt-5 border-s text-[0.9375rem]">
                                    {post.toc.map((entry, index) => (
                                        <li
                                            key={entry.id}
                                            data-active={
                                                index === reading
                                                    ? ''
                                                    : undefined
                                            }
                                            className="toc-entry"
                                        >
                                            <a
                                                href={`#${entry.id}`}
                                                aria-current={
                                                    index === reading
                                                        ? 'location'
                                                        : undefined
                                                }
                                                className="text-soft hover:text-fg block py-1.5 ps-5 transition-colors duration-300"
                                            >
                                                {entry.text}
                                            </a>
                                        </li>
                                    ))}
                                </ol>
                            </div>
                        </nav>
                    ) : null}

                    <div
                        className={
                            post.toc.length > 1
                                ? 'lg:col-span-8 lg:col-start-5'
                                : 'lg:col-span-8 lg:col-start-3'
                        }
                    >
                        {/* eslint-disable-next-line -- delegated click handling for the links of the rendered Markdown */}
                        <article
                            className="prose-legal prose-article"
                            onClick={followInternalLinks}
                            dangerouslySetInnerHTML={{ __html: post.html }}
                        />

                        <div className="border-line text-soft mt-14 flex flex-col gap-3 border-t pt-8 text-sm">
                            <p className="max-w-3xl">
                                {t.treatment.disclaimer}
                            </p>
                            <p className="flex flex-wrap gap-x-6 gap-y-1">
                                {post.review ? (
                                    <span>
                                        {t.treatment.reviewed(post.review.by)}
                                        {post.review.at
                                            ? ` · ${formatDate(post.review.at, locale)}`
                                            : ''}
                                    </span>
                                ) : null}
                                {post.updatedAt ? (
                                    <span>
                                        {t.treatment.updated(
                                            formatDate(post.updatedAt, locale),
                                        )}
                                    </span>
                                ) : null}
                            </p>
                        </div>

                        <div className="mt-10 flex flex-wrap gap-4">
                            {category ? (
                                <ButtonLink
                                    href={category.url}
                                    variant="outline"
                                >
                                    {category.name}
                                </ButtonLink>
                            ) : null}
                            <ButtonLink href={contactUrl}>
                                {t.common.appointmentLong}
                            </ButtonLink>
                        </div>
                    </div>
                </div>
            </section>

            {related.length > 0 ? (
                <section className="stage-light border-line section-y border-t">
                    <div className="shell">
                        <div className="flex flex-wrap items-end justify-between gap-8">
                            <SectionHeading
                                eyebrow={t.blog.eyebrow}
                                title={t.blog.moreTitle}
                                size="display-4"
                            />
                            <Reveal>
                                <SiteLink
                                    href={blogUrl}
                                    className="text-accent-fg inline-flex items-center gap-2 font-medium"
                                >
                                    <span className="link-underline">
                                        {t.blog.all}
                                    </span>
                                    <ArrowRight className="size-4" />
                                </SiteLink>
                            </Reveal>
                        </div>
                        <CardGrid
                            items={related}
                            itemKey={(item) => item.key}
                            className="mt-12"
                        >
                            {(item) => <PostCard post={item} />}
                        </CardGrid>
                    </div>
                </section>
            ) : null}

            <CtaBand accent={category?.accent} />
        </div>
    );
}
