import type { CSSProperties } from 'react';
import { SiteLink } from '@/site/components/ui/link';
import { cx } from '@/site/lib/cx';

/** Drawing size; hotspot coordinates below use the same space. */
const WIDTH = 400;
const HEIGHT = 520;

/**
 * Where each zone sits on the drawing. Keys are the values of
 * `treatments.zone` (App\Content\ContentFiles::ZONES). Zones that are not
 * on the bust (underarm, upper-arm, calf, thigh) have no point here and
 * are shown as "body area" by the caller.
 */
export const facePoints: Record<string, { x: number; y: number }> = {
    forehead: { x: 200, y: 104 },
    temples: { x: 279, y: 130 },
    brow: { x: 258, y: 139 },
    'crows-feet': { x: 281, y: 176 },
    'under-eye': { x: 244, y: 192 },
    'bunny-lines': { x: 216, y: 198 },
    nose: { x: 200, y: 204 },
    'nose-tip': { x: 200, y: 229 },
    cheeks: { x: 254, y: 218 },
    nasolabial: { x: 225, y: 243 },
    'gummy-smile': { x: 200, y: 249 },
    lips: { x: 200, y: 264 },
    'mouth-corners': { x: 231, y: 267 },
    masseter: { x: 268, y: 254 },
    jawline: { x: 243, y: 296 },
    chin: { x: 200, y: 303 },
    neck: { x: 200, y: 350 },
    trapezius: { x: 297, y: 389 },
    shoulders: { x: 352, y: 426 },
};

export function hasFacePoint(zone: string | null): boolean {
    return zone !== null && (zone in facePoints || zone === 'full-face');
}

/**
 * The line drawing itself — head, neck and shoulders — in the 400×520 space
 * of the hotspots. It carries no colour: strokes and fills come from the
 * element it is placed in (`stroke`, `currentColor`). Every path declares
 * a length of 1, which changes nothing about how it is drawn but lets a
 * hero draw the face stroke by stroke (`.face-lines` in site.css).
 */
export function FaceDrawing() {
    return (
        <>
            {/* Shoulders and collarbones */}
            <path
                pathLength={1}
                d="M140 372C112 386 62 392 30 420 16 434 10 462 10 520M260 372c28 14 78 20 110 48 14 14 20 42 20 100"
            />
            <path
                pathLength={1}
                d="M176 404c-26 6-60 6-90 14M224 404c26 6 60 6 90 14M188 398c6 8 18 8 24 0"
                opacity="0.55"
            />
            {/* Neck */}
            <path
                pathLength={1}
                d="M150 290c2 36 0 62-10 82M250 290c-2 36 0 62 10 82"
            />
            {/* Head */}
            <path
                pathLength={1}
                d="M200 40c48 0 88 38 91 100 2 56-7 106-35 142-16 20-34 38-56 38s-40-18-56-38c-28-36-37-86-35-142 3-62 43-100 91-100Z"
            />
            <path
                pathLength={1}
                d="M291 168c13-4 15 28-1 36M109 168c-13-4-15 28 1 36"
                opacity="0.7"
            />
            <path
                pathLength={1}
                d="M118 118c22-48 142-48 164 0"
                opacity="0.4"
            />
            {/* Brows */}
            <path
                pathLength={1}
                d="M218 150c16-9 38-9 54 1M182 150c-16-9-38-9-54 1"
            />
            {/* Eyes */}
            <path
                pathLength={1}
                d="M224 172c10-8 30-8 40 0-10 7-30 7-40 0ZM176 172c-10-8-30-8-40 0 10 7 30 7 40 0Z"
            />
            <circle
                cx="244"
                cy="172"
                r="3.4"
                fill="currentColor"
                stroke="none"
                opacity="0.6"
            />
            <circle
                cx="156"
                cy="172"
                r="3.4"
                fill="currentColor"
                stroke="none"
                opacity="0.6"
            />
            {/* Nose */}
            <path
                pathLength={1}
                d="M206 172c1 20 4 36 10 48-4 8-10 11-16 11s-12-3-16-11"
                opacity="0.85"
            />
            {/* Lips */}
            <path
                pathLength={1}
                d="M176 262c10-7 18-6 24-3 6-3 14-4 24 3M176 262c14 3 34 3 48 0M180 264c10 12 30 12 40 0"
            />
            <path pathLength={1} d="M192 296c5 3 11 3 16 0" opacity="0.4" />
        </>
    );
}

type FaceMapItem = { zone: string; name: string; url: string };

type FaceMapProps = {
    /** Treatments that have a zone; several may share one. */
    items: FaceMapItem[];
    /** Currently highlighted zone. */
    active: string | null;
    /** Pointer moved onto / off a hotspot. */
    onHover?: (zone: string | null) => void;
    /** Text alternative of the drawing. */
    label: string;
    className?: string;
};

const position = (point: { x: number; y: number }): CSSProperties => ({
    left: `${(point.x / WIDTH) * 100}%`,
    top: `${(point.y / HEIGHT) * 100}%`,
});

/**
 * A line drawing of a face, neck and shoulders with one hotspot per
 * treatment zone. The highlighted zone follows `active` (driven by the
 * treatment list next to it), so scrolling the list "walks" over the face.
 *
 * The hotspots are a pointer-only shortcut: the same links exist as real,
 * keyboard-reachable links in the list, so they are hidden from assistive
 * technology here.
 */
export function FaceMap({
    items,
    active,
    onHover,
    label,
    className,
}: FaceMapProps) {
    const zones = new Map<string, FaceMapItem>();

    for (const item of items) {
        if (!zones.has(item.zone)) {
            zones.set(item.zone, item);
        }
    }

    const activeItem = active ? zones.get(active) : undefined;
    const activePoint = active ? facePoints[active] : undefined;

    return (
        <div
            className={cx(
                'relative mx-auto aspect-[400/520] w-full max-w-md',
                className,
            )}
        >
            <svg
                viewBox={`0 0 ${WIDTH} ${HEIGHT}`}
                fill="none"
                role="img"
                aria-label={label}
                className="block size-full"
                stroke="currentColor"
                strokeWidth="1.2"
                strokeLinecap="round"
                strokeLinejoin="round"
            >
                <defs>
                    <radialGradient id="face-glow">
                        <stop
                            offset="0"
                            stopColor="var(--accent)"
                            stopOpacity="0.55"
                        />
                        <stop
                            offset="1"
                            stopColor="var(--accent)"
                            stopOpacity="0"
                        />
                    </radialGradient>
                </defs>

                {/* Soft light that travels to the active zone. */}
                <circle
                    r="74"
                    fill="url(#face-glow)"
                    stroke="none"
                    className="ease-out-expo transition-[transform,opacity] duration-700"
                    style={{
                        transform: `translate(${activePoint?.x ?? 200}px, ${activePoint?.y ?? 190}px) scale(${active === 'full-face' ? 2.1 : 1})`,
                        opacity:
                            active && (activePoint || active === 'full-face')
                                ? 1
                                : 0.25,
                    }}
                />

                <g className="text-fg" opacity="0.72">
                    <FaceDrawing />
                </g>

                {/* Whole-face ring for "full face" treatments */}
                <ellipse
                    cx="200"
                    cy="184"
                    rx="104"
                    ry="148"
                    stroke="var(--accent)"
                    strokeDasharray="2 7"
                    className="transition-opacity duration-500"
                    opacity={active === 'full-face' ? 0.9 : 0}
                />

                {[...zones.keys()].map((zone) => {
                    const point = facePoints[zone];

                    if (!point) {
                        return null;
                    }

                    const isActive = zone === active;

                    return (
                        <g
                            key={zone}
                            transform={`translate(${point.x} ${point.y})`}
                            stroke="none"
                        >
                            {isActive ? (
                                <circle
                                    r="9"
                                    fill="none"
                                    stroke="var(--accent)"
                                    strokeWidth="1"
                                    className="animate-pulse-ring origin-center [transform-box:fill-box]"
                                />
                            ) : null}
                            <circle
                                r={isActive ? 5 : 2.6}
                                fill="var(--accent)"
                                opacity={isActive ? 1 : 0.55}
                                className="transition-[r,opacity] duration-300"
                            />
                        </g>
                    );
                })}
            </svg>

            {/* Pointer-only shortcuts to the treatment pages. */}
            <div aria-hidden="true">
                {[...zones.entries()].map(([zone, item]) => {
                    const point = facePoints[zone];

                    return point ? (
                        <SiteLink
                            key={zone}
                            href={item.url}
                            tabIndex={-1}
                            title={item.name}
                            onMouseEnter={() => onHover?.(zone)}
                            onMouseLeave={() => onHover?.(null)}
                            className="absolute size-7 -translate-x-1/2 -translate-y-1/2 rounded-full"
                            style={position(point)}
                        />
                    ) : null;
                })}
            </div>

            {/* Name of the highlighted treatment, next to its point. */}
            {activeItem && activePoint ? (
                <p
                    aria-hidden="true"
                    className="border-line-strong bg-stage/80 pointer-events-none absolute z-10 -translate-y-1/2 rounded-full border px-3 py-1 text-xs font-medium whitespace-nowrap backdrop-blur-sm"
                    style={{
                        ...position(activePoint),
                        // Flip the label inwards when the point is near the right edge.
                        ...(activePoint.x > 270
                            ? {
                                  transform:
                                      'translate(calc(-100% - 14px), -50%)',
                              }
                            : { marginInlineStart: '14px' }),
                    }}
                >
                    {activeItem.name}
                </p>
            ) : null}
        </div>
    );
}
