import { useState, useRef, useEffect } from 'react';
import { createPortal } from 'react-dom';
import Picker from '@emoji-mart/react';
import data from '@emoji-mart/data';
import { useLang } from '../../../../core/infrastructure/i18n';

interface EmojiOnlyPickerProps {
  onSelect: (emoji: string) => void;
  onClose: () => void;
}

export default function EmojiOnlyPicker({ onSelect, onClose }: EmojiOnlyPickerProps) {
  const { lang } = useLang();
  const anchorRef = useRef<HTMLDivElement>(null);
  const [pos, setPos] = useState<{ top: number; left: number } | null>(null);

  useEffect(() => {
    const update = () => {
      const el = anchorRef.current?.parentElement;
      if (!el) return;
      const rect = el.getBoundingClientRect();
      const w = 350; // Slightly narrower for stories
      let left = rect.right - w;
      if (left < 8) left = 8;
      setPos({ top: rect.top - 8, left });
    };
    update();
    window.addEventListener('resize', update);
    return () => window.removeEventListener('resize', update);
  }, []);

  return (
    <>
      <div ref={anchorRef} className="hidden" />
      {createPortal(
        <>
          <div className="fixed inset-0 z-[9990]" onClick={onClose} />
          <div
            className="fixed z-[9991] rounded-[2rem] shadow-[0_32px_64px_-16px_rgba(0,0,0,0.6)] border border-white/10 overflow-hidden flex flex-col backdrop-blur-3xl"
            onClick={(e) => e.stopPropagation()}
            style={{
              width: 350,
              height: 400,
              bottom: pos ? `${window.innerHeight - pos.top}px` : undefined,
              left: pos ? pos.left : undefined,
              background: 'rgba(19, 19, 19, 0.85)',
              visibility: pos ? 'visible' : 'hidden',
            }}
          >
             <div className="px-5 py-3 border-b border-white/5 bg-black/20 flex-shrink-0">
                <span className="text-[10px] font-black uppercase tracking-[0.2em] text-primary">{lang === 'ru' ? 'Выбор эмодзи' : 'Choose Emoji'}</span>
             </div>
             
             <div className="flex-1 overflow-hidden">
                <Picker
                    data={data}
                    onEmojiSelect={(e: { native: string }) => onSelect(e.native)}
                    theme="dark"
                    locale={lang === 'ru' ? 'ru' : 'en'}
                    set="native"
                    previewPosition="none"
                    skinTonePosition="search"
                    perLine={8}
                    emojiSize={24}
                    emojiButtonSize={32}
                    maxFrequentRows={1}
                    navPosition="top"
                    dynamicWidth={false}
                    background="transparent"
                />
             </div>
          </div>
        </>,
        document.body
      )}
    </>
  );
}
