import { useCallback, useRef, useState } from 'react';
import type { CSSProperties, PointerEvent } from 'react';
import { Picture } from '@/site/components/media/picture';
import { CardGrid } from '@/site/components/sections/card-grid';
import { SectionHeading } from '@/site/components/ui/heading';
import { ArrowRight } from '@/site/components/ui/icons';
import { SiteLink } from '@/site/components/ui/link';
import { useOnEnter } from '@/site/hooks/use-in-view';
import { useT } from '@/site/i18n';
import { motionEnabled } from '@/site/lib/scroll-engine';
import type { BeforeAfterPair } from '@/site/types';

/**
 * Before and after photos of the home page (docs/DECISIONS.md K46), in the
 * place of the former "Yaklaşımımız" section. The photos are files on the
 * public disk (media/before-after/{name}-before.* and -after.*, see
 * SitePresenter::beforeAfter); until the clinic adds some the section is
 * not rendered at all.
 *
 * Each pair is one frame: the "after" photo fills it and the "before"
 * photo lies over its left part, up to a dividing line the visitor drags
 * (a horizontal drag; a vertical one still scrolls the page) or moves with
 * the arrow keys (a native range input, visually hidden, carries the value
 * for the keyboard and screen readers). When a frame first comes into view
 * the line swings once to each side and back, to show that it moves.
 * The frame is laid out left to right in every language: the photos are.
 */
export function BeforeAfter({ pairs }: { pairs: BeforeAfterPair[] }) {
    const t = useT();
    const copy = t.home.beforeAfter;

    if (pairs.length === 0) {
        return null;
    }

    return (
        <section className="stage-light section-y">
            <div className="shell">
                <SectionHeading
                    eyebrow={copy.eyebrow}
                    title={copy.title}
                    lead={copy.lead}
                />
                <CardGrid
                    items={pairs}
                    itemKey={(pair) => pair.key}
                    className="mt-14"
                >
                    {(pair) => <Comparison pair={pair} />}
                </CardGrid>
            </div>
        </section>
    );
}

/** The swing a frame plays once when it comes into view: line positions over time. */
const SWING = [50, 26, 72, 50];
const SWING_MS = 1800;

const ease = (x: number) => 0.5 - Math.cos(Math.PI * x) / 2;

function Comparison({ pair }: { pair: BeforeAfterPair }) {
    const t = useT();
    const copy = t.home.beforeAfter;
    const frame = useRef<HTMLDivElement>(null);
    const touched = useRef(false);
    const dragging = useRef(false);
    const [position, setPosition] = useState(50);

    const follow = (event: PointerEvent<HTMLDivElement>) => {
        const box = event.currentTarget.getBoundingClientRect();

        setPosition(
            Math.min(
                100,
                Math.max(0, ((event.clientX - box.left) / box.width) * 100),
            ),
        );
    };

    const swing = useCallback(() => {
        if (!motionEnabled() || touched.current) {
            return;
        }

        const start = performance.now();
        const legs = SWING.length - 1;

        const step = (now: number) => {
            // The visitor took over: leave the line where they put it.
            if (touched.current) {
                return;
            }

            const progress = Math.min(1, (now - start) / SWING_MS);
            const leg = Math.min(legs - 1, Math.floor(progress * legs));
            const local = ease(progress * legs - leg);

            setPosition(SWING[leg] + (SWING[leg + 1] - SWING[leg]) * local);

            if (progress < 1) {
                requestAnimationFrame(step);
            }
        };

        requestAnimationFrame(step);
    }, []);

    useOnEnter(frame, swing, '0px 0px -25% 0px');

    const label = pair.name ? copy.compare(pair.name) : copy.slider;
    const ratio =
        pair.after.width && pair.after.height
            ? `${pair.after.width} / ${pair.after.height}`
            : '4 / 5';

    return (
        <figure className="flex flex-col gap-4">
            <div
                ref={frame}
                dir="ltr"
                onPointerDown={(event) => {
                    touched.current = true;
                    dragging.current = true;
                    event.currentTarget.setPointerCapture(event.pointerId);
                    follow(event);
                }}
                onPointerMove={(event) => {
                    if (dragging.current) {
                        follow(event);
                    }
                }}
                onPointerUp={() => {
                    dragging.current = false;
                }}
                onPointerCancel={() => {
                    dragging.current = false;
                }}
                // A photo would otherwise start a native drag and cancel the pointer.
                onDragStart={(event) => event.preventDefault()}
                className="before-after bg-stage-2 relative isolate overflow-hidden rounded-lg"
                style={
                    {
                        aspectRatio: ratio,
                        '--pos': `${position}%`,
                    } as CSSProperties
                }
            >
                <Picture
                    media={{
                        ...pair.after,
                        alt: `${pair.name ? `${pair.name} — ` : ''}${copy.after}`,
                    }}
                    sizes="(min-width: 1280px) 33vw, (min-width: 640px) 50vw, 100vw"
                    className="absolute inset-0"
                />
                {/* The "before" photo, cut at the line: the outer box moves left, the photo back right. */}
                <div className="before-after-cut">
                    <div className="before-after-photo">
                        <Picture
                            media={{
                                ...pair.before,
                                alt: `${pair.name ? `${pair.name} — ` : ''}${copy.before}`,
                            }}
                            sizes="(min-width: 1280px) 33vw, (min-width: 640px) 50vw, 100vw"
                            className="absolute inset-0"
                        />
                    </div>
                </div>

                <span aria-hidden="true" className="before-after-tag start-3">
                    {copy.before}
                </span>
                <span aria-hidden="true" className="before-after-tag end-3">
                    {copy.after}
                </span>

                {/* The dividing line and its handle. */}
                <div aria-hidden="true" className="before-after-line">
                    <span className="before-after-handle">
                        <ArrowRight className="size-4 -scale-x-100" />
                        <ArrowRight className="size-4" />
                    </span>
                </div>

                <input
                    type="range"
                    min={0}
                    max={100}
                    step={1}
                    value={Math.round(position)}
                    aria-label={label}
                    aria-valuetext={`${copy.before} ${Math.round(position)}%`}
                    onKeyDown={() => {
                        touched.current = true;
                    }}
                    onChange={(event) => {
                        touched.current = true;
                        setPosition(Number(event.currentTarget.value));
                    }}
                    className="before-after-input sr-only"
                />
            </div>

            {pair.name ? (
                <figcaption className="flex items-center justify-between gap-4">
                    {pair.url ? (
                        <SiteLink
                            href={pair.url}
                            className="hover:text-accent-fg inline-flex items-center gap-2 font-medium transition-colors duration-300"
                        >
                            {pair.name}
                            <ArrowRight className="size-4 rtl:-scale-x-100" />
                        </SiteLink>
                    ) : (
                        <span className="font-medium">{pair.name}</span>
                    )}
                </figcaption>
            ) : null}
        </figure>
    );
}
