'use client';

import React, {
  useState,
  useEffect,
  useRef,
  useId,
  useLayoutEffect,
  Fragment,
} from 'react';
import Link from 'next/link';
import ReactDOM from 'react-dom';
import { animate, stagger } from 'motion';
import './addons-showcase.css';

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

export const 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.webp',
  profileBackground: '/addons/profileBackground.jpg',
  cardFrame: '/addons/cardFrame.webp',
  communityBackground: '/addons/communityBackground.webp',
  wealthy: '/addons/wealthy.png',
  investor: '/addons/investor.png',
};

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

function Icon({ name, size, ...props }: { name: string; size?: number | string } & React.SVGProps<SVGSVGElement>) {
  const paths: Record<string, React.ReactNode> = {
    menu: <path d="M4 6h16M4 12h16M4 18h16" />,
    overview: (
      <>
        <circle cx="12" cy="12" r="9" />
        <path d="m16 8-2.5 5.5L8 16l2.5-5.5L16 8Z" />
      </>
    ),
    premiumPlan: (
      <>
        <path d="m12 2 8 5v10l-8 5-8-5V7l8-5Z" />
        <path d="m4 7 8 4 8-4M12 11v11M8 4.5l8 4.5" />
      </>
    ),
    addons: (
      <path d="M8 3h3a3 3 0 1 1 6 0h4v7a3 3 0 1 0 0 6v5h-7a3 3 0 1 0-6 0H3v-6a3 3 0 1 0 0-6V3h5Z" />
    ),
    gift: (
      <>
        <rect x="3" y="8" width="18" height="4" rx="1" />
        <path d="M5 12v9h14v-9M12 8v13M12 8H8a3 3 0 1 1 3-3l1 3Zm0 0h4a3 3 0 1 0-3-3l-1 3Z" />
      </>
    ),
    share: (
      <>
        <circle cx="5" cy="12" r="3" />
        <circle cx="19" cy="5" r="3" />
        <circle cx="19" cy="19" r="3" />
        <path d="m7.7 10.6 8.6-4.2m-8.6 7 8.6 4.2" />
      </>
    ),
    star: (
      <path d="m12 3 2.8 5.8 6.4.9-4.6 4.5 1.1 6.3-5.7-3-5.7 3 1.1-6.3-4.6-4.5 6.4-.9L12 3Z" />
    ),
    link: (
      <>
        <path d="m10 13 4-4m-6 5-1 1a3.5 3.5 0 0 1-5-5l4-4a3.5 3.5 0 0 1 5 0m2 12a3.5 3.5 0 0 0 5 0l4-4a3.5 3.5 0 0 0-5-5l-1 1" />
      </>
    ),
    palette: (
      <>
        <path d="M12 3a9 9 0 1 0 0 18h1a2 2 0 0 0 1.2-3.6 1.5 1.5 0 0 1 1-2.7H17a4 4 0 0 0 4-4A8 8 0 0 0 12 3Z" />
        <circle cx="7" cy="10" r=".8" />
        <circle cx="11" cy="7" r=".8" />
        <circle cx="16" cy="8" r=".8" />
      </>
    ),
    coins: (
      <>
        <ellipse cx="9" cy="6" rx="6" ry="3" />
        <path d="M3 6v4c0 1.7 2.7 3 6 3h1M3 10v4c0 1.7 2.7 3 6 3h1" />
        <ellipse cx="16" cy="13" rx="5" ry="3" />
        <path d="M11 13v5c0 1.7 2.2 3 5 3s5-1.3 5-3v-5" />
      </>
    ),
    history: (
      <>
        <path d="M3 10a9 9 0 1 1 1.6 7M3 4v6h6M12 7v5l3 2" />
      </>
    ),
    grid: (
      <>
        <rect x="3" y="3" width="7" height="7" rx="1.5" />
        <rect x="14" y="3" width="7" height="7" rx="1.5" />
        <rect x="3" y="14" width="7" height="7" rx="1.5" />
        <rect x="14" y="14" width="7" height="7" rx="1.5" />
      </>
    ),
    user: (
      <>
        <circle cx="12" cy="8" r="4" />
        <path d="M5 21v-2a7 7 0 0 1 14 0v2" />
      </>
    ),
    badge: (
      <>
        <path d="m12 2 3 2 3.6.4.5 3.6L21 11l-1.9 3-.5 3.6-3.6.4-3 2-3-2-3.6-.4L5 14l-2-3 2-3 .4-3.6L9 4l3-2Z" />
        <path d="m8.5 11 2.2 2.2 4.8-4.7" />
      </>
    ),
    arrow: <path d="M4 12h16M14 6l6 6-6 6" />,
    chevron: <path d="m9 5 7 7-7 7" />,
    bag: (
      <>
        <path d="M5 7h14l1 14H4L5 7Z" />
        <path d="M8 8V6a4 4 0 0 1 8 0v2" />
      </>
    ),
    diamond: (
      <>
        <path d="m3 8 4-5h10l4 5-9 13L3 8Z" />
        <path d="M3 8h18M7 3l5 18 5-18" />
      </>
    ),
    check: <path d="m5 12 4 4L19 6" />,
    close: <path d="m6 6 12 12M6 18 18 6" />,
    plus: <path d="M12 5v14M5 12h14" />,
    lock: (
      <>
        <rect x="5" y="10" width="14" height="11" rx="3" />
        <path d="M8 10V7a4 4 0 0 1 8 0v3M12 14v3" />
      </>
    ),
    sliders: (
      <>
        <path d="M4 7h5m4 0h7M4 17h9m4 0h3" />
        <circle cx="11" cy="7" r="2" />
        <circle cx="15" cy="17" r="2" />
      </>
    ),
    layers: (
      <>
        <path d="m12 3 10 5-10 5L2 8l10-5ZM2 12l10 5 10-5M2 16l10 5 10-5" />
      </>
    ),
    upload: (
      <>
        <path d="M12 16V3m-5 5 5-5 5 5M4 15v5a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-5" />
      </>
    ),
    globe: (
      <>
        <circle cx="12" cy="12" r="9" />
        <ellipse cx="12" cy="12" rx="4" ry="9" />
        <path d="M3 12h18" />
      </>
    ),
    heart: (
      <path d="M20.8 4.6a5.5 5.5 0 0 0-7.8 0L12 5.7l-1.1-1.1a5.5 5.5 0 0 0-7.8 7.8L12 21l8.8-8.6a5.5 5.5 0 0 0 0-7.8Z" />
    ),
    crown: (
      <>
        <path d="m3 6 5 4 4-7 4 7 5-4-3 12H6L3 6ZM6 21h12" />
      </>
    ),
    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 Asset({ name, ...props }: { name: string } & React.ImgHTMLAttributes<HTMLImageElement>) {
  // eslint-disable-next-line @next/next/no-img-element
  return <img src={ASSETS[name]} alt="" {...props} />;
}

export interface ProductItem {
  id: string;
  name: string;
  category?: string;
  label: string;
  price: number;
  color: string;
  description: string;
  features: string[];
  icon?: string;
  image?: string;
}

export const products: ProductItem[] = [
  {
    id: 'bundle-starter',
    name: 'Creator Bundle',
    category: 'Bundles',
    label: 'Everything you need to stand out',
    price: 10.99,
    color: '#f5e1e1',
    description:
      'Our best value combo. Get permanent Lifetime Premium, 1 Username Rename Token, and +3 Audio Slots with synchronized lyrics.',
    features: [
      'Lifetime Premium pass ($6.99 value)',
      '1 Username Rename Token ($1.99 value)',
      '+3 Audio Playlist Slots ($2.49 value)',
      'Permanent profile capacity & upgrades',
    ],
    icon: 'spark',
  },
  {
    id: 'alias',
    name: 'Alias Slot',
    category: 'Profile',
    label: 'Another name. Same you.',
    price: 1.99,
    color: '#ef7b7b',
    description: 'Claim another Sinss URL and connect it to any of your profiles.',
    features: [
      'One additional profile URL',
      'Connect to any of your profiles',
      'Swap with your username anytime',
    ],
    icon: 'link',
  },
  {
    id: 'verified',
    name: 'Verified Badge',
    category: 'Badges',
    label: 'Recognizable at a glance',
    price: 14.99,
    color: '#e86d6d',
    description:
      'Stand out with a verified checkmark and a matching Discord role.',
    features: [
      'Blue verified profile checkmark',
      'Matching community role',
      'Visible on every profile',
    ],
    image: 'verified',
  },
  {
    id: 'custom',
    name: 'Custom Badge',
    category: 'Badges',
    label: 'A badge with your personality',
    price: 9.99,
    color: '#c31c1c',
    description:
      'Your icon, your label, your color. Create something that is completely you.',
    features: [
      'Choose your own icon and color',
      'Custom label and description',
      'Update your badge anytime',
    ],
    icon: 'palette',
  },
  {
    id: 'donator',
    name: 'Donator Badge',
    category: 'Badges',
    label: 'A little support goes a long way',
    price: 3.99,
    color: '#dc3a3a',
    description:
      'Support what we are building. Get a special badge and a few extra perks.',
    features: [
      'Supporter profile badge',
      'Access to community polls',
      'Supporter Discord channels',
    ],
    image: 'creator',
  },
  {
    id: 'og',
    name: 'OG Badge',
    category: 'Badges',
    label: 'Here before the rest',
    price: 4.99,
    color: '#7e1717',
    description:
      'A little piece of history. An exclusive badge for the original ones.',
    features: [
      'Original member profile badge',
      'Matching OG Discord role',
      'Limited early-adopter edition',
    ],
    icon: 'history',
  },
  {
    id: 'promoter',
    name: 'Promoter Badge',
    category: 'Badges',
    label: 'Dynamic Status Perk',
    price: 0,
    color: '#d87b7b',
    description:
      'Put sinss in your Discord custom status to unlock the exclusive Promoter badge, animated profile card aura, and site perks.',
    features: [
      'Promoter badge & animated card aura on your profile',
      '1.5x multiplier on daily Sinss Credits rewards',
      'Direct file hosting unlock on dashboard',
      'VIP Global Chat flair & highlighted leaderboard rank',
      'Free automatic unlock via Discord custom status',
    ],
    icon: 'spark',
  },

  {
    id: 'username-token',
    name: 'Rename Token',
    category: 'Profile',
    label: 'A fresh new handle',
    price: 1.99,
    color: '#f8e3e3',
    description: 'Change your primary username without losing your badges, views, or profile customization.',
    features: [
      '1 Username change credit',
      'Keeps all badges & stats',
      'Instant handle transfer',
    ],
    icon: 'spark',
  },
  {
    id: 'extra-audio-slots',
    name: '+3 Audio Slots',
    category: 'Profile',
    label: 'More music & synced lyrics',
    price: 2.49,
    color: '#f7d9d9',
    description: 'Expand your floating audio player with 3 additional track slots and LRCLIB synchronized lyrics.',
    features: [
      '3 Additional audio playlist slots',
      'Synchronized lyrics support',
      'Permanent profile capacity',
    ],
    icon: 'sliders',
  },

];

export const premium: ProductItem = {
  id: 'premium',
  name: 'Lifetime Premium',
  label: 'One upgrade. Endless possibilities.',
  price: 6.99,
  color: '#ffffff',
  description:
    'Every customization tool, five unique profiles, and a little more room to be yourself. Yours for one payment.',
  features: [
    '5 fully customizable profile slots',
    'Live audio-reactive visualizer (soundwaves)',
    'Cinematic card entrance transitions',
    'Custom entrance typography & styling',
    'Custom lyrics styles (Neon, Karaoke, Align & Glow)',
    'Custom fonts and profile click sounds',
    'Premium badge and Discord role',
  ],
  image: 'diamond',
};

function ProductArt({ id }: { id: string }) {
  return (
    <div className="product-art" aria-hidden="true">
      {id === 'bundle-starter' && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 16px', background: 'rgba(245, 225, 225, 0.08)', borderRadius: 14, border: '1px solid rgba(245, 225, 225, 0.25)' }}>
          <Asset name="diamond" style={{ width: 44, height: 44, filter: 'drop-shadow(0 0 12px rgba(245, 225, 225, 0.4))' }} />
          <div style={{ textAlign: 'left' }}>
            <strong style={{ display: 'block', fontSize: 13, color: '#feeeee', fontWeight: 700 }}>Starter Value Bundle</strong>
            <small style={{ color: '#fcf1f1', fontSize: 11, display: 'block' }}>Lifetime + Token + 3 Audio Slots</small>
          </div>
        </div>
      )}
      {id === 'alias' && (
        <>
          <div className="alias-lines">
            <div className="chip">
              sinss.lol/<strong>you</strong>
            </div>
            <div className="chip">
              sinss.lol/<strong>alsoyou</strong>
            </div>
          </div>
          <div className="connector" />
          <div className="mini-profile">
            <Asset name="avatar" />
          </div>
        </>
      )}
      {id === 'verified' && (
        <div className="verified-demo">
          <div className="verified-tip">Officially, unmistakably you.</div>
          <Asset name="avatar" className="small-avatar" />
          <div>
            <strong>
              you <Asset name="verified" />
            </strong>
            <small>Account verified by sinss.lol</small>
          </div>
        </div>
      )}
      {id === 'custom' && (
        <div className="custom-badges">
          <div className="chip">
            <Icon name="heart" /> hopeless romantic
          </div>
          <div className="chip">
            <Icon name="star" /> made of stardust
          </div>
        </div>
      )}
      {id === 'donator' && (
        <div className="donation-stack">
          <div className="donation-tile">
            <Asset name="creator" />
            <small>Supporter</small>
          </div>
          <div className="donation-tile">
            <Asset name="investor" />
            <small>Investor</small>
          </div>
          <div className="donation-tile">
            <Asset name="wealthy" />
            <small>Wealthy</small>
          </div>
        </div>
      )}
      {id === 'og' && (
        <div className="og-demo">
          <div className="og-symbol">OG</div>
          <div>
            <strong>you</strong>
            <small>One of the original ones.</small>
          </div>
        </div>
      )}
      {id === 'promoter' && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 16px', background: 'rgba(216, 123, 123, 0.08)', borderRadius: 14, border: '1px solid rgba(216, 123, 123, 0.25)' }}>
          <span style={{ fontSize: 32 }}>📢</span>
          <div style={{ textAlign: 'left' }}>
            <strong style={{ display: 'block', fontSize: 13, color: '#fd8989', fontWeight: 700 }}>Promoter Badge & Aura</strong>
            <small style={{ color: '#d87b7b', fontSize: 11, display: 'block' }}>Dynamic Status Perk · Free</small>
          </div>
        </div>
      )}
      {id === 'credits' && (
        <div className="credits-art">
          <div className="coin">
            <Icon name="coins" />
          </div>
          <div>
            <strong>1,000</strong>
            <small>Sinss credits</small>
          </div>
        </div>
      )}
      {id === 'premium' && (
        <Asset
          name="diamond"
          style={{ width: 85, height: 85, filter: 'drop-shadow(0 0 30px #ffffff44)' }}
        />
      )}
    </div>
  );
}

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',
  promoter: 'Promoter',
};

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);
        }}
      >
        <Asset 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 MobileNavigation({ onPremium }: { onPremium: () => void }) {
  const [open, setOpen] = useState(false);
  const wrapper = useRef<HTMLDivElement | null>(null);
  const toggle = useRef<HTMLButtonElement | null>(null);
  const panel = useRef<HTMLElement | null>(null);

  const close = (restore = false) => {
    setOpen(false);
    if (restore) toggle.current?.focus({ preventScroll: true });
  };

  useEffect(() => {
    if (!open) return;
    panel.current?.querySelector<HTMLElement>('a,button')?.focus({ preventScroll: true });
    const outside = (e: MouseEvent | TouchEvent) => {
      if (wrapper.current && !wrapper.current.contains(e.target as Node)) setOpen(false);
    };
    const escape = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        e.preventDefault();
        close(true);
      }
    };
    const desktop = () => {
      if (window.innerWidth > 680) close(false);
    };
    document.addEventListener('pointerdown', outside);
    document.addEventListener('keydown', escape);
    window.addEventListener('resize', desktop);
    return () => {
      document.removeEventListener('pointerdown', outside);
      document.removeEventListener('keydown', escape);
      window.removeEventListener('resize', desktop);
    };
  }, [open]);

  return (
    <div
      className="mobile-navigation"
      ref={wrapper}
      onBlur={(e) => {
        if (e.relatedTarget && !e.currentTarget.contains(e.relatedTarget as Node)) {
          setOpen(false);
        }
      }}
    >
      <button
        ref={toggle}
        type="button"
        className={'mobile-nav-toggle ' + (open ? 'is-open' : '')}
        aria-label={open ? 'Close navigation' : 'Open navigation'}
        aria-expanded={open}
        aria-controls="mobile-nav-panel"
        onClick={() => setOpen((v) => !v)}
      >
        <Icon name={open ? 'close' : 'menu'} />
      </button>
      {open && (
        <nav
          ref={panel}
          id="mobile-nav-panel"
          className="mobile-nav-panel"
          aria-label="Mobile navigation"
        >
          <span className="mobile-nav-caption">Explore sinss.lol</span>
          <a href="#profile" onClick={() => close(true)}>
            <Icon name="overview" />
            <span>Overview</span>
          </a>
          <button
            onClick={() => {
              close(true);
              onPremium();
            }}
          >
            <Icon name="premiumPlan" />
            <span>Premium</span>
            <small>One-time upgrade</small>
          </button>
          <a href="#addons" className="active" aria-current="page" onClick={() => close(true)}>
            <Icon name="addons" />
            <span>Add-ons</span>
          </a>
        </nav>
      )}
    </div>
  );
}

function ProfileSurface({
  enhanced = false,
  position = 50,
}: {
  enhanced?: boolean;
  position?: number;
}) {
  return (
    <div
      className={'comparison-layer ' + (enhanced ? 'is-premium' : 'is-free')}
      role="group"
      aria-label={enhanced ? 'Premium profile preview' : 'Free profile preview'}
    >
      <div className="comparison-card">
        {enhanced && (
          <>
            <Asset name="profileBackground" className="comparison-backdrop" />
            <div className="comparison-backdrop-fade" />
            <Asset 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>you</span>
                <Asset name="verified" className="verified-mark" />
              </div>
              <p className="comparison-bio">a little chaos, a lot of personality.</p>
              <div className="comparison-socials">
                {PROFILE_SOCIALS.map(([name]) => (
                  <span key={name}>
                    <Asset name={name} />
                  </span>
                ))}
              </div>
            </div>
            <div className="comparison-avatar">
              <Asset name="avatar" className="avatar-photo" />
              <span className="comparison-online" />
              {enhanced && (
                <>
                  <Asset name="avatarFrame" className="premium-avatar-frame" />
                  <span className="avatar-spark">
                    <Icon name="spark" />
                  </span>
                </>
              )}
            </div>
          </div>
          <div className="comparison-footer">
            <span className="views" aria-hidden="true">
              <Icon 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/you
      </span>
    </div>
  );
}

function ProfileCard() {
  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></span>Free
          </button>
          <button
            className="comparison-label premium-label"
            onClick={() => slideTo(0)}
            title="Show the full Premium profile"
          >
            <Asset 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} />
          </div>
          <div
            className="comparison-clip"
            style={{ clipPath: `inset(0 0 0 ${position}%)` }}
          >
            <ProfileSurface enhanced position={position} />
          </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="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="comparison-help">
        Compare Free and Premium profiles. Drag the handle or use arrow keys. Home shows
        Premium and End shows Free. Badges identify a supporter, a Premium user, and the
        site owner.
      </span>
    </div>
  );
}

function Modal({
  children,
  onClose,
  label,
}: {
  children: React.ReactNode;
  onClose: () => void;
  label: string;
}) {
  const ref = useRef<HTMLElement | null>(null);

  useEffect(() => {
    const previous = document.activeElement as HTMLElement | null;
    const old = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    ref.current?.querySelector<HTMLElement>('button')?.focus();

    const handle = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose();
      if (e.key === 'Tab') {
        const nodes = Array.from(
          ref.current?.querySelectorAll<HTMLElement>(
            'button:not(:disabled),a[href],input'
          ) || []
        );
        const first = nodes[0];
        const last = nodes[nodes.length - 1];
        if (e.shiftKey && document.activeElement === first) {
          e.preventDefault();
          last?.focus();
        } else if (!e.shiftKey && document.activeElement === last) {
          e.preventDefault();
          first?.focus();
        }
      }
    };

    document.addEventListener('keydown', handle);
    if (ref.current && !window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
      animate(ref.current, { opacity: [0, 1], y: [15, 0], scale: [0.98, 1] }, { duration: 0.25 });
    }

    return () => {
      document.body.style.overflow = old;
      document.removeEventListener('keydown', handle);
      previous?.focus();
    };
  }, [onClose]);

  return (
    <div
      className="overlay"
      onClick={(e) => e.target === e.currentTarget && onClose()}
    >
      <section
        className="modal"
        ref={ref}
        role="dialog"
        aria-modal="true"
        aria-label={label}
      >
        <button className="close" onClick={onClose} aria-label="Close dialog">
          <Icon name="close" />
        </button>
        {children}
      </section>
    </div>
  );
}

export default function AddonsShowcase() {
  const [filter, setFilter] = useState('All add-ons');
  const [selected, setSelected] = useState<ProductItem | null>(null);
  const [view, setView] = useState<'bag' | 'compare' | null>(null);
  const [bag, setBag] = useState<string[]>(['premium']);
  const [toast, setToast] = useState('');
  const [checkoutLoading, setCheckoutLoading] = useState(false);

  const handleCheckout = async (itemId: string) => {
    if (itemId === 'promoter') {
      window.location.href = '/dashboard';
      return;
    }
    const resolvedId = itemId === 'credits' ? 'credits-1000' : itemId;
    setCheckoutLoading(true);
    try {
      const res = await fetch('/api/checkout/polar', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ itemId: resolvedId }),
      });
      const data = await res.json();
      if (data.url) {
        window.location.href = data.url;
      } else {
        setToast(data.error || 'Could not start checkout');
        setTimeout(() => setToast(''), 3500);
        setCheckoutLoading(false);
      }
    } catch {
      setToast('Network error loading checkout');
      setTimeout(() => setToast(''), 3500);
      setCheckoutLoading(false);
    }
  };
  const gridRef = useRef<HTMLDivElement | null>(null);

  useEffect(() => {
    try {
      const saved = localStorage.getItem('sinss-bag') || localStorage.getItem('sinss-demo-bag');
      if (saved) {
        const parsed = JSON.parse(saved);
        if (Array.isArray(parsed) && parsed.length > 0) {
          setBag(parsed.filter((id) => [...products, premium].some((p) => p.id === id)));
        }
      }
    } catch {}
  }, []);

  useEffect(() => {
    try {
      localStorage.setItem('sinss-bag', JSON.stringify(bag));
    } catch {}
  }, [bag]);

  useEffect(() => {
    if (!toast) return;
    const t = setTimeout(() => setToast(''), 2700);
    return () => clearTimeout(t);
  }, [toast]);

  useEffect(() => {
    if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
    const a = animate(
      '.hero-copy, .preview-scene',
      { opacity: [0, 1], y: [18, 0] },
      { duration: 0.65, delay: stagger(0.14), ease: [0.22, 1, 0.36, 1] }
    );
    return () => a.stop();
  }, []);

  useEffect(() => {
    if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
    if (!gridRef.current) return;
    const a = animate(
      gridRef.current.querySelectorAll('.product-card, .help-card'),
      { opacity: [0, 1], y: [12, 0] },
      { duration: 0.4, delay: stagger(0.045), ease: [0.22, 1, 0.36, 1] }
    );
    return () => a.stop();
  }, [filter]);

  const add = (p: ProductItem) => {
    if (!bag.includes(p.id)) {
      setBag([...bag, p.id]);
      setToast(`${p.name} added to your bag`);
    }
    setSelected(null);
  };

  const shown =
    filter === 'All add-ons'
      ? products
      : products.filter((p) => p.category === filter);

  const bagProducts = [...products, premium].filter((p) => bag.includes(p.id));

  return (
    <div className="addons-root">
      <header className="header">
        <div className="wrap header-inner">
          <Link className="brand" href="/" aria-label="Sinss.lol home">
            <Asset name="logo" />
            Sinss.lol
          </Link>
          <nav className="nav" aria-label="Main navigation">
            <Link href="/">
              <Icon name="overview" />
              Overview
            </Link>
            <button onClick={() => setSelected(premium)}>
              <Icon name="premiumPlan" />
              Premium
            </button>
            <a className="active" href="#addons" aria-current="page">
              <Icon name="addons" />
              Add-ons
            </a>
          </nav>
          <div className="header-actions">
            <a
              className="icon-button"
              href={DISCORD}
              target="_blank"
              rel="noopener noreferrer"
              aria-label="Join our Discord"
            >
              <Asset name="discord" />
            </a>
            <button className="bag-button" onClick={() => setView('bag')}>
              <Icon name="bag" />
              <span>Your bag</span>
              <span className="count">{bag.length}</span>
            </button>
            <MobileNavigation onPremium={() => setSelected(premium)} />
          </div>
        </div>
      </header>

      <main className="wrap">
        <div className="breadcrumb">
          <span>Shop</span>
          <Icon name="chevron" />
          <span>Add-ons</span>
        </div>

        <section className="hero" id="profile">
          <div className="hero-copy">
            <div className="eyebrow">SMALL UPGRADES, BIG PERSONALITY.</div>
            <h1>
              A little extra.
              <br />
              <span>A lot more you.</span>
            </h1>
            <p>
              Make your corner of the internet feel like you.
              <br />
              More possibilities, less blending in.
            </p>
            <div className="hero-buttons">
              <button className="primary" disabled={checkoutLoading} onClick={() => handleCheckout('premium')}>
                <Icon name="diamond" />
                {checkoutLoading ? 'Opening Checkout…' : <>Get Premium <span style={{ opacity: 0.45 }}>|</span> $6.99</>}
              </button>
              <button className="text-button" onClick={() => setView('compare')}>
                Compare plans <Icon name="arrow" />
              </button>
            </div>
            <div className="hero-note">
              <Icon name="check" />
              One payment. Yours forever.
            </div>
          </div>
          <ProfileCard />
        </section>

        <section className="perks" aria-label="Premium benefits">
          {[
            ['layers', '5 unique profiles', 'A different side of you, every time.'],
            ['sliders', 'Every effect, unlocked', 'Fine-tune every little detail.'],
            ['upload', 'Your own assets', 'Fonts, cursors, sounds. All yours.'],
            ['share', 'Made to be shared', 'Your presence, on your terms.'],
          ].map(([icon, title, text]) => (
            <div className="perk" key={title}>
              <Icon name={icon} />
              <div>
                <strong>{title}</strong>
                <span>{text}</span>
              </div>
            </div>
          ))}
        </section>

        <section className="shop" id="addons">
          <div className="section-top">
            <div>
              <div className="eyebrow">The finishing touches</div>
              <h2>Make it yours.</h2>
            </div>
            <p>Little upgrades that make a big difference.</p>
          </div>

          <div className="shop-toolbar">
            <div className="filters" role="group" aria-label="Filter products">
              {['All add-ons', 'Bundles', 'Profile', 'Badges', 'Extras'].map((f) => (
                <button
                  key={f}
                  className={'filter ' + (filter === f ? 'selected' : '')}
                  aria-pressed={filter === f}
                  onClick={() => setFilter(f)}
                >
                  <Icon
                    name={
                      {
                        'All add-ons': 'grid',
                        Bundles: 'spark',
                        Profile: 'user',
                        Badges: 'badge',
                        Extras: 'gift',
                      }[f] || 'grid'
                    }
                  />
                  {f}
                </button>
              ))}
            </div>
            <span className="product-count" aria-live="polite">
              {shown.length} products
            </span>
          </div>

          <div className="grid" ref={gridRef}>
            {shown.map((p) => (
              <article
                className="product-card"
                key={p.id}
                style={{ '--accent': p.color } as React.CSSProperties}
                tabIndex={0}
                role="button"
                aria-label={`View ${p.name}, $${p.price}`}
                onClick={() => setSelected(p)}
                onKeyDown={(e) => {
                  if (e.key === 'Enter' || e.key === ' ') {
                    e.preventDefault();
                    setSelected(p);
                  }
                }}
              >
                <ProductArt id={p.id} />
                <div className="product-info">
                  <span className="product-category">{p.label}</span>
                  <h3>{p.name}</h3>
                  <p>{p.description}</p>
                </div>
                <div className="product-footer">
                  <span className="price">
                    {p.price === 0 ? 'Free' : '$' + p.price.toFixed(2)}
                    <small>{p.id === 'promoter' ? 'status perk' : p.id === 'credits' ? 'per pack' : 'one-time'}</small>
                  </span>
                  <span className="read-more">
                    Explore <Icon name="arrow" />
                  </span>
                </div>
              </article>
            ))}

            {filter === 'All add-ons' && (
              <aside className="help-card">
                <Asset
                  name="communityBackground"
                  className="help-card-art"
                  aria-hidden="true"
                  loading="lazy"
                />
                <div className="help-icon">
                  <Asset name="discord" />
                </div>
                <h3>Ready to purchase? We&apos;re here.</h3>
                <p>
                  All upgrades unlock automatically on your account. Need support or custom orders? Reach out anytime.
                </p>
                <a
                  className="secondary"
                  href={DISCORD}
                  target="_blank"
                  rel="noopener noreferrer"
                >
                  <Asset name="discord" className="discord-button-logo" />
                  Join Discord Community
                </a>
              </aside>
            )}
          </div>
        </section>

        <section className="faq" id="questions">
          <div>
            <div className="eyebrow">Good to know</div>
            <h2>The little details.</h2>
            <p>A few answers before you make it yours.</p>
          </div>
          <div>
            <details>
              <summary>
                Are add-ons a one-time purchase?
                <Icon name="plus" />
              </summary>
              <p>
                Profile upgrades and custom badges use one-time pricing, and credits are sold per pack. Instant checkout with Card, Apple Pay, Google Pay, or Cash App.
              </p>
            </details>
            <details>
              <summary>
                Do I need Premium to use add-ons?
                <Icon name="plus" />
              </summary>
              <p>
                Add-ons can be purchased separately or alongside Premium. Checkout directly on-site and your upgrades activate immediately.
              </p>
            </details>
            <details>
              <summary>
                How do I get my add-ons?
                <Icon name="plus" />
              </summary>
              <p>
                Add items to your bag or click upgrade directly. Once checkout is completed, your account is credited automatically.
              </p>
            </details>
          </div>
        </section>
      </main>

      <footer className="footer">
        <div className="wrap footer-inner">
          <div className="footer-left">
            <Link href="/" className="brand" aria-label="Sinss.lol home">
              <Asset name="logo" />
              Sinss.lol
            </Link>
            <span>A space to be yourself.</span>
          </div>
          <div className="footer-right">
            <span className="footer-status">Built for individuality</span>
            <a href={DISCORD} target="_blank" rel="noopener noreferrer">
              Community
            </a>
            <span>© {new Date().getFullYear()} Sinss.lol</span>
          </div>
        </div>
      </footer>

      {selected && (
        <Modal onClose={() => setSelected(null)} label={selected.name}>
          <div style={{ '--accent': selected.color } as React.CSSProperties}>
            <ProductArt id={selected.id} />
            <div
              className="eyebrow"
              style={{ color: selected.color, justifyContent: 'flex-start' }}
            >
              {selected.label}
            </div>
            <h2>{selected.name}</h2>
            <p className="modal-description">{selected.description}</p>
            <ul>
              {selected.features.map((f) => (
                <li key={f}>
                  <Icon name="check" />
                  {f}
                </li>
              ))}
            </ul>
            <div className="modal-bottom">
              <span className="price">
                {selected.price === 0 ? 'Free' : '$' + selected.price.toFixed(2)}
                <small>{selected.id === 'promoter' ? 'status perk' : selected.id === 'credits' ? 'per pack' : 'one-time'}</small>
              </span>
              {selected.id === 'promoter' ? (
                <a
                  href="/dashboard"
                  className="primary"
                  style={{ textDecoration: 'none', display: 'inline-flex', alignItems: 'center', gap: 8 }}
                >
                  <Icon name="spark" />
                  View in Dashboard
                </a>
              ) : (
                <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
                  <button
                    className="primary"
                    disabled={checkoutLoading}
                    onClick={() => handleCheckout(selected.id)}
                  >
                    <Icon name="diamond" />
                    {checkoutLoading ? 'Opening Checkout…' : 'Purchase with Card / Apple Pay'}
                  </button>
                  <button
                    className="secondary"
                    onClick={() =>
                      bag.includes(selected.id)
                        ? (setSelected(null), setView('bag'))
                        : add(selected)
                    }
                  >
                    <Icon name="bag" />
                    {bag.includes(selected.id) ? 'In bag' : 'Add to bag'}
                  </button>
                </div>
              )}
            </div>
            <p className="modal-note">{selected.id === 'promoter' ? 'Keep sinss in your Discord custom status to keep perks active.' : 'Instant automated fulfillment via Apple Pay, Google Pay, or Card.'}</p>
          </div>
        </Modal>
      )}

      {view === 'bag' && (
        <Modal onClose={() => setView(null)} label="Your bag">
          <div
            className="eyebrow"
            style={{ justifyContent: 'flex-start', marginTop: 8 }}
          >
            Your next little upgrade
          </div>
          <h2>
            Your bag<span style={{ color: '#2e1414' }}> ({bag.length})</span>
          </h2>
          {bagProducts.length ? (
            <>
              {bagProducts.map((p) => (
                <div className="bag-row" key={p.id}>
                  {p.icon ? (
                    <Icon
                      name={p.icon}
                      className="bag-product-icon"
                      style={{ color: p.color }}
                    />
                  ) : (
                    <Asset name={p.image || ''} />
                  )}
                  <div>
                    <strong>{p.name}</strong>
                    <small>
                      {p.id === 'credits' ? '1,000 credit pack' : 'One-time upgrade'}
                    </small>
                  </div>
                  <span className="bag-price">${p.price.toFixed(2)}</span>
                  <button
                    aria-label={`Remove ${p.name}`}
                    onClick={() => setBag(bag.filter((id) => id !== p.id))}
                  >
                    <Icon name="close" />
                  </button>
                </div>
              ))}
              <div className="modal-bottom" style={{ marginTop: 24, border: 0 }}>
                <div>
                  <div style={{ fontSize: 10, color: '#2a0d0d', marginBottom: 5 }}>
                    Estimated total
                  </div>
                  <span className="price">
                    $
                    {bagProducts
                      .reduce((sum, p) => sum + p.price, 0)
                      .toFixed(2)}
                  </span>
                </div>
                <button
                  className="primary"
                  disabled={checkoutLoading}
                  onClick={() => {
                    const first = bagProducts[0];
                    if (first) handleCheckout(first.id);
                  }}
                >
                  {checkoutLoading ? 'Redirecting…' : 'Checkout with Card / Apple Pay'} <Icon name="arrow" />
                </button>
              </div>
              <p className="modal-note">
                Instant automated fulfillment linked to your account.
              </p>
            </>
          ) : (
            <div className="empty-bag">
              <Icon name="bag" />
              <p>A little room for something good.</p>
              <button
                className="secondary"
                onClick={() => {
                  setView(null);
                  document.getElementById('addons')?.scrollIntoView({ behavior: 'smooth' });
                }}
              >
                Explore add-ons <Icon name="arrow" />
              </button>
            </div>
          )}
        </Modal>
      )}

      {view === 'compare' && (
        <Modal onClose={() => setView(null)} label="Compare plans">
          <div
            className="eyebrow"
            style={{ justifyContent: 'flex-start', marginTop: 8 }}
          >
            Find your fit
          </div>
          <h2>A little more freedom.</h2>
          <p className="modal-description">
            Start with the essentials. Upgrade when you want to make every detail yours.
          </p>
          <table className="compare-table">
            <thead>
              <tr>
                <th>Included</th>
                <th>Free</th>
                <th>Premium</th>
              </tr>
            </thead>
            <tbody>
              {[
                ['Price', '$0', '$6.99 once'],
                ['Profile slots', '1', '5'],
                ['Links per profile', '10', '25'],
                ['Audio tracks', '1', '10'],
                ['Widgets per profile', '3', '10'],
                ['Custom assets', 'Not included', 'Included'],
                ['Advanced effects', 'Not included', 'Included'],
              ].map((row) => (
                <tr key={row[0]}>
                  {row.map((cell, i) => (
                    <td key={i}>{cell}</td>
                  ))}
                </tr>
              ))}
            </tbody>
          </table>
          <button
            className="primary"
            style={{ width: '100%' }}
            disabled={checkoutLoading}
            onClick={() => handleCheckout('premium')}
          >
            <Icon name="diamond" />
            {checkoutLoading ? 'Redirecting…' : 'Upgrade to Lifetime Premium — $6.99'}
          </button>
          <p className="modal-note">Instant automated activation via Card, Apple Pay, or Google Pay.</p>
        </Modal>
      )}

      {toast && (
        <div className="toast" role="status">
          <Icon name="check" />
          {toast}
        </div>
      )}
    </div>
  );
}
