import { useId } from 'react';
import type { CSSProperties } from 'react';
import { cx } from '@/site/lib/cx';
import { blobPath, seededRandom } from '@/site/lib/generative';

type ContourArtProps = {
    /** Any stable text (a treatment or category key): same seed, same drawing. */
    seed: string;
    /** Number of contour rings. */
    rings?: number;
    /**
     * For a page's hero: the rings enter one by one, turn slowly and lean
     * with the mouse (`.contour-alive` in site.css; the pointer comes from
     * the hero's Spotlight). Elsewhere the drawing stays still.
     */
    alive?: boolean;
    className?: string;
};

/**
 * Generative placeholder artwork: nested contour lines, like a topographic
 * map of a face, unique per seed and tinted by the nearest [data-accent].
 * It fills image slots until real photography arrives (see MediaSlot).
 *
 * The drawing is one path reused with <use> at growing scales, so the
 * markup stays around 2 KB however many rings are drawn.
 */
export function ContourArt({
    seed,
    rings = 13,
    alive = false,
    className,
}: ContourArtProps) {
    const id = useId();
    const random = seededRandom(`${seed}:layout`);

    const twist = 3 + random() * 5;
    const driftX = (random() - 0.5) * 14;
    const driftY = (random() - 0.5) * 14;
    const start = random() * 360;
    const [dotAngle, dotRing] = [
        random() * Math.PI * 2,
        4 + Math.floor(random() * 4),
    ];

    const scaleOf = (index: number) => 0.16 + (index / (rings - 1)) * 1.02;
    const dotRadius = 100 * scaleOf(dotRing);

    const ring = (index: number) => {
        const scale = scaleOf(index);

        return (
            <use
                key={index}
                href={`#${id}-ring`}
                stroke="var(--accent)"
                strokeWidth={index % 4 === 0 ? 1.1 : 0.6}
                opacity={(0.9 - (index / rings) * 0.6).toFixed(2)}
                transform={`translate(${(driftX * (1 - scale)).toFixed(1)} ${(driftY * (1 - scale)).toFixed(1)}) rotate(${(start + index * twist).toFixed(1)}) scale(${scale.toFixed(3)})`}
            />
        );
    };

    // A single marked point: reads as "the place we work on".
    const dot = (
        <g
            transform={`translate(${(Math.cos(dotAngle) * dotRadius).toFixed(1)} ${(Math.sin(dotAngle) * dotRadius).toFixed(1)})`}
        >
            <circle r="9" fill="var(--accent)" opacity="0.18" />
            <circle r="2.6" fill="var(--accent)" />
        </g>
    );

    return (
        <svg
            viewBox="-130 -130 260 260"
            aria-hidden="true"
            className={cx(
                'block size-full',
                alive && 'contour-alive',
                className,
            )}
            fill="none"
        >
            <defs>
                <path
                    id={`${id}-ring`}
                    d={blobPath(seed)}
                    vectorEffect="non-scaling-stroke"
                />
                <radialGradient id={`${id}-glow`}>
                    <stop
                        offset="0"
                        stopColor="var(--accent)"
                        stopOpacity="0.5"
                    />
                    <stop
                        offset="1"
                        stopColor="var(--accent)"
                        stopOpacity="0"
                    />
                </radialGradient>
            </defs>

            <circle r="118" fill={`url(#${id}-glow)`} opacity="0.55" />

            {alive ? (
                // One group per ring: the place for its entrance and its
                // lean. The marked point turns with the rings.
                <g className="contour-rings">
                    {Array.from({ length: rings }, (_, index) => (
                        <g
                            key={index}
                            className="contour-ring"
                            style={{ '--i': index } as CSSProperties}
                        >
                            {ring(index)}
                        </g>
                    ))}
                    {dot}
                </g>
            ) : (
                <>
                    {Array.from({ length: rings }, (_, index) => ring(index))}
                    {dot}
                </>
            )}
        </svg>
    );
}
