'use client';

import React, {
  useState,
  useEffect,
  useRef,
  useId,
  useLayoutEffect,
  Fragment,
} from 'react';
import ReactDOM from 'react-dom';
import { animate } from 'motion';
import './profile-comparison-slider.css';

const useIsomorphicLayoutEffect =
  typeof window !== 'undefined' ? useLayoutEffect : useEffect;

export const SLIDER_ASSETS: Record<string, string> = {
  avatar: '/addons/avatar.jpg',
  creator: '/addons/creator.png',
  discord: '/addons/discord.svg',
  spotify: '/addons/spotify.png',
  github: '/addons/github.png',
  diamond: '/addons/diamond.png',
  crown: '/addons/crown.png',
  verified: '/addons/verified.png',
  logo: '/addons/logo.svg',
  avatarFrame: '/addons/avatarFrame.png',
  profileBackground: '/addons/profileBackground.jpg',
  cardFrame: '/addons/cardFrame.png',
  communityBackground: '/addons/communityBackground.webp',
  wealthy: '/addons/wealthy.png',
  investor: '/addons/investor.png',
};

const DISCORD = 'https://discord.gg/sinss';

function SliderIcon({
  name,
  size,
  ...props
}: { name: string; size?: number | string } & React.SVGProps<SVGSVGElement>) {
  const paths: Record<string, React.ReactNode> = {
    spark: (
      <path d="m12 3 2.4 6.6L21 12l-6.6 2.4L12 21l-2.4-6.6L3 12l6.6-2.4L12 3Z" />
    ),
    eye: (
      <path
        fill="currentColor"
        stroke="none"
        d="M12 9a3 3 0 0 0-3 3a3 3 0 0 0 3 3a3 3 0 0 0 3-3a3 3 0 0 0-3-3m0 8a5 5 0 0 1-5-5a5 5 0 0 1 5-5a5 5 0 0 1 5 5a5 5 0 0 1-5 5m0-12.5C7 4.5 2.73 7.61 1 12c1.73 4.39 6 7.5 11 7.5s9.27-3.11 11-7.5c-1.73-4.39-6-7.5-11-7.5"
      />
    ),
  };
  return (
    <svg
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.5"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
      data-icon={name}
      style={size ? { width: size, height: size } : undefined}
      {...props}
    >
      {paths[name] || paths.spark}
    </svg>
  );
}

function SliderAsset({
  name,
  ...props
}: { name: string } & React.ImgHTMLAttributes<HTMLImageElement>) {
  // eslint-disable-next-line @next/next/no-img-element
  return <img src={SLIDER_ASSETS[name]} alt="" {...props} />;
}

const PROFILE_SOCIALS: [string, string, string][] = [
  ['github', 'https://github.com', 'GitHub'],
  ['discord', DISCORD, 'Discord'],
  ['spotify', 'https://open.spotify.com', 'Spotify'],
];

const BADGE_LABELS: Record<string, string> = {
  creator: 'Supporter',
  diamond: 'Premium user',
  crown: 'Site owner',
};

function ProfileBadge({
  name,
  enhanced,
  position,
}: {
  name: string;
  enhanced?: boolean;
  position: number;
}) {
  const trigger = useRef<HTMLButtonElement | null>(null);
  const tip = useRef<HTMLDivElement | null>(null);
  const closeTimer = useRef<NodeJS.Timeout | null>(null);
  const [visible, setVisible] = useState(false);
  const [open, setOpen] = useState(false);
  const [placement, setPlacement] = useState({ left: 0, top: 0, below: false });
  const [mounted, setMounted] = useState(false);
  const tipId = useId();

  useEffect(() => {
    setMounted(true);
  }, []);

  const cancelClose = () => {
    if (closeTimer.current) clearTimeout(closeTimer.current);
  };

  const show = () => {
    cancelClose();
    if (visible) {
      document.dispatchEvent(new CustomEvent('sinss:badge-tooltip', { detail: tipId }));
      setOpen(true);
    }
  };

  useEffect(() => {
    const closeOther = (e: Event) => {
      const customEvent = e as CustomEvent<string>;
      if (customEvent.detail !== tipId) {
        cancelClose();
        setOpen(false);
      }
    };
    document.addEventListener('sinss:badge-tooltip', closeOther);
    return () => document.removeEventListener('sinss:badge-tooltip', closeOther);
  }, [tipId]);

  const scheduleClose = () => {
    cancelClose();
    if (document.activeElement !== trigger.current) {
      closeTimer.current = setTimeout(() => setOpen(false), 120);
    }
  };

  useIsomorphicLayoutEffect(() => {
    const button = trigger.current;
    if (!button) return;
    const stage = button.closest('.comparison-stage') as HTMLElement;
    if (!stage) return;
    const measure = () => {
      const b = button.getBoundingClientRect();
      const s = stage.getBoundingClientRect();
      const split = s.left + (s.width * position) / 100;
      setVisible(enhanced ? b.left >= split - 0.5 : b.right <= split + 0.5);
    };
    measure();
    const observer = new ResizeObserver(measure);
    observer.observe(stage);
    observer.observe(button);
    return () => observer.disconnect();
  }, [position, enhanced]);

  useEffect(() => {
    if (!visible) {
      setOpen(false);
      if (document.activeElement === trigger.current) trigger.current?.blur();
    }
  }, [visible]);

  useEffect(() => () => cancelClose(), []);

  useIsomorphicLayoutEffect(() => {
    if (!open) return;
    const place = () => {
      if (!trigger.current) return;
      const r = trigger.current.getBoundingClientRect();
      const width = tip.current?.offsetWidth || 130;
      setPlacement({
        left: Math.max(
          width / 2 + 10,
          Math.min(window.innerWidth - width / 2 - 10, r.left + r.width / 2)
        ),
        top: r.top < 52 ? r.bottom + 9 : r.top - 9,
        below: r.top < 52,
      });
    };
    const escape = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        cancelClose();
        setOpen(false);
      }
    };
    const outside = (e: MouseEvent | TouchEvent) => {
      if (
        trigger.current &&
        !trigger.current.contains(e.target as Node) &&
        !tip.current?.contains(e.target as Node)
      ) {
        setOpen(false);
      }
    };
    place();
    window.addEventListener('resize', place);
    window.addEventListener('scroll', place, true);
    document.addEventListener('keydown', escape);
    document.addEventListener('pointerdown', outside);
    return () => {
      window.removeEventListener('resize', place);
      window.removeEventListener('scroll', place, true);
      document.removeEventListener('keydown', escape);
      document.removeEventListener('pointerdown', outside);
    };
  }, [open]);

  return (
    <>
      <button
        ref={trigger}
        type="button"
        className="badge-trigger"
        disabled={!visible}
        tabIndex={visible ? 0 : -1}
        aria-hidden={!visible}
        aria-label={BADGE_LABELS[name]}
        aria-describedby={open ? tipId : undefined}
        onPointerDown={(e) => e.stopPropagation()}
        onClick={(e) => {
          e.stopPropagation();
          show();
        }}
        onMouseEnter={show}
        onMouseLeave={scheduleClose}
        onFocus={show}
        onBlur={() => {
          cancelClose();
          closeTimer.current = setTimeout(() => setOpen(false), 120);
        }}
      >
        <SliderAsset name={name} />
      </button>
      {open &&
        visible &&
        mounted &&
        ReactDOM.createPortal(
          <div
            ref={tip}
            id={tipId}
            role="tooltip"
            className={'badge-tooltip ' + (placement.below ? 'below' : '')}
            style={{ left: placement.left, top: placement.top }}
            onMouseEnter={cancelClose}
            onMouseLeave={scheduleClose}
            onPointerDown={(e) => e.stopPropagation()}
          >
            {BADGE_LABELS[name]}
          </div>,
          document.body
        )}
    </>
  );
}

function ProfileSurface({
  enhanced = false,
  position = 50,
  username = 'you',
  bio = 'a little chaos, a lot of personality.',
}: {
  enhanced?: boolean;
  position?: number;
  username?: string;
  bio?: string;
}) {
  return (
    <div
      className={'comparison-layer ' + (enhanced ? 'is-premium' : 'is-free')}
      role="group"
      aria-label={enhanced ? 'Premium profile preview' : 'Free profile preview'}
    >
      {enhanced && (
        <div className="profile-particles">
          {Array.from({ length: 16 }, (_, i) => (
            <i
              key={i}
              style={{
                left: `${(i * 29 + 7) % 100}%`,
                top: `${(i * 43 + 11) % 100}%`,
                animationDelay: `-${i * 0.63}s`,
                animationDuration: `${4 + (i % 4)}s`,
              }}
            />
          ))}
        </div>
      )}
      <div className="comparison-card">
        {enhanced && (
          <>
            <SliderAsset name="profileBackground" className="comparison-backdrop" />
            <div className="comparison-backdrop-fade" />
            <SliderAsset name="cardFrame" className="profile-card-frame" />
          </>
        )}
        <div className="comparison-content">
          <div className="comparison-main" aria-hidden="true">
            <div className="comparison-identity">
              <div className="comparison-name">
                <span>{username}</span>
                <SliderAsset name="verified" className="verified-mark" />
              </div>
              <p className="comparison-bio">{bio}</p>
              <div className="comparison-socials">
                {PROFILE_SOCIALS.map(([name]) => (
                  <span key={name}>
                    <SliderAsset name={name} />
                  </span>
                ))}
              </div>
            </div>
            <div className="comparison-avatar">
              <SliderAsset name="avatar" className="avatar-photo" />
              <span className="comparison-online" />
              {enhanced && (
                <>
                  <SliderAsset name="avatarFrame" className="premium-avatar-frame" />
                  <span className="avatar-spark">
                    <SliderIcon name="spark" />
                  </span>
                </>
              )}
            </div>
          </div>
          <div className="comparison-footer">
            <span className="views" aria-hidden="true">
              <SliderIcon name="eye" />
              1,284
            </span>
            <div className="comparison-badges">
              {(enhanced
                ? ['creator', 'diamond', 'crown']
                : ['creator', 'crown']
              ).map((name) => (
                <ProfileBadge
                  key={name}
                  name={name}
                  enhanced={enhanced}
                  position={position}
                />
              ))}
            </div>
          </div>
        </div>
      </div>
      <span className="comparison-url" aria-hidden="true">
        sinss.lol/{username}
      </span>
    </div>
  );
}

export default function ProfileComparisonSlider({
  username = 'you',
  bio = 'a little chaos, a lot of personality.',
}: {
  username?: string;
  bio?: string;
}) {
  const [position, setPosition] = useState(50);
  const [dragging, setDragging] = useState(false);
  const stage = useRef<HTMLDivElement | null>(null);
  const handle = useRef<HTMLDivElement | null>(null);
  const activePointer = useRef<number | null>(null);
  const animation = useRef<{ stop: () => void } | null>(null);
  const current = useRef(50);

  const update = (value: number) => {
    const next = Math.max(0, Math.min(100, value));
    current.current = next;
    setPosition(next);
  };

  const stop = () => {
    animation.current?.stop();
    animation.current = null;
  };

  const fromPointer = (e: React.PointerEvent<HTMLDivElement>) => {
    if (!stage.current) return;
    const box = stage.current.getBoundingClientRect();
    if (box.width) update(((e.clientX - box.left) / box.width) * 100);
  };

  const slideTo = (value: number) => {
    stop();
    if (
      typeof window !== 'undefined' &&
      !window.matchMedia('(prefers-reduced-motion: reduce)').matches
    ) {
      animation.current = animate(current.current, value, {
        duration: 0.55,
        ease: [0.22, 1, 0.36, 1],
        onUpdate: update,
      });
    } else {
      update(value);
    }
  };

  useEffect(() => () => animation.current?.stop(), []);

  const release = (e: React.PointerEvent<HTMLDivElement>) => {
    if (e.pointerId !== activePointer.current) return;
    activePointer.current = null;
    setDragging(false);
    if (stage.current?.hasPointerCapture(e.pointerId)) {
      stage.current.releasePointerCapture(e.pointerId);
    }
  };

  const keyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {
    const step = e.shiftKey ? 10 : 2;
    let next;
    switch (e.key) {
      case 'ArrowLeft':
      case 'ArrowDown':
        next = current.current - step;
        break;
      case 'ArrowRight':
      case 'ArrowUp':
        next = current.current + step;
        break;
      case 'Home':
        next = 0;
        break;
      case 'End':
        next = 100;
        break;
      case 'PageDown':
        next = current.current - 10;
        break;
      case 'PageUp':
        next = current.current + 10;
        break;
      default:
        return;
    }
    e.preventDefault();
    stop();
    update(next);
  };

  return (
    <div className="preview-scene comparison-scene">
      <div
        className="comparison-shell"
        role="region"
        aria-label="Free and Premium profile comparison"
      >
        <div className="comparison-labels">
          <button
            className="comparison-label free-label"
            onClick={() => slideTo(100)}
            title="Show the full Free profile"
          >
            <span />Free
          </button>
          <button
            className="comparison-label premium-label"
            onClick={() => slideTo(0)}
            title="Show the full Premium profile"
          >
            <SliderAsset name="diamond" />
            Premium
          </button>
        </div>
        <div
          ref={stage}
          className={'comparison-stage ' + (dragging ? 'is-dragging' : '')}
          onPointerDown={(e) => {
            if (!e.isPrimary || e.button !== 0) return;
            stop();
            activePointer.current = e.pointerId;
            setDragging(true);
            e.currentTarget.setPointerCapture(e.pointerId);
            handle.current?.focus({ preventScroll: true });
            fromPointer(e);
          }}
          onPointerMove={(e) => {
            if (activePointer.current === e.pointerId) fromPointer(e);
          }}
          onPointerUp={release}
          onPointerCancel={release}
          onLostPointerCapture={() => {
            activePointer.current = null;
            setDragging(false);
          }}
        >
          <div
            className="comparison-clip"
            style={{ clipPath: `inset(0 ${100 - position}% 0 0)` }}
          >
            <ProfileSurface position={position} username={username} bio={bio} />
          </div>
          <div
            className="comparison-clip"
            style={{ clipPath: `inset(0 0 0 ${position}%)` }}
          >
            <ProfileSurface enhanced position={position} username={username} bio={bio} />
          </div>
          <div className="comparison-divider" style={{ left: `${position}%` }}>
            <div className="comparison-line" />
          </div>
          <div
            ref={handle}
            className="comparison-handle"
            role="slider"
            tabIndex={0}
            aria-label="Profile comparison split"
            aria-describedby="landing-comparison-help"
            aria-orientation="horizontal"
            aria-valuemin={0}
            aria-valuemax={100}
            aria-valuenow={Math.round(position)}
            aria-valuetext={`${Math.round(position)} percent Free, ${Math.round(
              100 - position
            )} percent Premium`}
            onKeyDown={keyDown}
            style={{ left: `${position}%` }}
          >
            <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
              {[5, 12, 19].map((y) => (
                <Fragment key={y}>
                  <circle cx="9" cy={y} r="1.3" />
                  <circle cx="15" cy={y} r="1.3" />
                </Fragment>
              ))}
            </svg>
          </div>
        </div>
      </div>
      <span className="sr-only" id="landing-comparison-help">
        Compare Free and Premium profiles. Drag the handle or use arrow keys. Home shows
        Premium and End shows Free.
      </span>
    </div>
  );
}
