import { useState, useEffect, useRef, useCallback } from 'react';
import { X, ChevronLeft, ChevronRight } from 'lucide-react';
import styles from './StoryViewer.module.scss';

const STORY_DURATION = 6000;

const StoryViewer = ({ stories, onClose, initialIndex = 0, onStoryViewed }) => {
  const [currentIndex, setCurrentIndex] = useState(initialIndex);
  const [animClass, setAnimClass] = useState(styles.slideInFromRight);
  const [progress, setProgress] = useState(0); // 0..1

  const touchStartX = useRef(null);
  const touchStartY = useRef(null);
  const isPausedRef = useRef(false);
  const rafRef = useRef(null);
  const startTimeRef = useRef(null);
  const elapsedRef = useRef(0); // ms elapsed before last pause

  const isFirst = currentIndex === 0;
  const isLast = currentIndex === stories.length - 1;
  const currentStory = stories[currentIndex];

  // Scroll lock
  useEffect(() => {
    const orig = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => { document.body.style.overflow = orig; };
  }, []);

  // ── Core timer: runs per-frame, advances progress, fires goNext ──
  const startTimer = useCallback((onDone) => {
    if (rafRef.current) cancelAnimationFrame(rafRef.current);
    startTimeRef.current = Date.now();
    elapsedRef.current = 0;
    setProgress(0);

    const tick = () => {
      if (isPausedRef.current) {
        // While paused keep scheduling but don't advance
        rafRef.current = requestAnimationFrame(tick);
        return;
      }
      const now = Date.now();
      const delta = now - startTimeRef.current;
      startTimeRef.current = now;
      elapsedRef.current += delta;

      const p = Math.min(elapsedRef.current / STORY_DURATION, 1);
      setProgress(p);

      if (p >= 1) {
        onDone();
        return;
      }
      rafRef.current = requestAnimationFrame(tick);
    };

    rafRef.current = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(rafRef.current);
  }, []);

  // ── Navigate ──
  const goTo = useCallback((nextIndex, dir) => {
    if (nextIndex < 0 || nextIndex >= stories.length) return;
    if (rafRef.current) cancelAnimationFrame(rafRef.current);
    setAnimClass(dir === 'next' ? styles.slideInFromRight : styles.slideInFromLeft);
    setCurrentIndex(nextIndex);
  }, [stories.length]);

  const goToNext = useCallback(() => {
    if (!isLast) goTo(currentIndex + 1, 'next');
    else onClose();
  }, [currentIndex, isLast, goTo, onClose]);

  const goToPrevious = useCallback(() => {
    if (!isFirst) goTo(currentIndex - 1, 'prev');
  }, [currentIndex, isFirst, goTo]);

  // ── Start timer when index changes ──
  useEffect(() => {
    if (onStoryViewed) onStoryViewed(currentIndex);

    const cancel = startTimer(() => {
      if (currentIndex < stories.length - 1) {
        setAnimClass(styles.slideInFromRight);
        setCurrentIndex((i) => i + 1);
      } else {
        onClose();
      }
    });

    return cancel;
  }, [currentIndex, stories.length]); // NO isPaused here — handled by ref

  // ── Keyboard ──
  useEffect(() => {
    const onKey = (e) => {
      if (e.key === 'ArrowLeft') goToPrevious();
      if (e.key === 'ArrowRight') goToNext();
      if (e.key === 'Escape') onClose();
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [goToPrevious, goToNext, onClose]);

  // ── Touch swipe ──
  const handleTouchStart = (e) => {
    touchStartX.current = e.touches[0].clientX;
    touchStartY.current = e.touches[0].clientY;
  };
  const handleTouchEnd = (e) => {
    if (touchStartX.current === null) return;
    const dx = e.changedTouches[0].clientX - touchStartX.current;
    const dy = e.changedTouches[0].clientY - touchStartY.current;
    touchStartX.current = null;
    if (Math.abs(dx) < 40 || Math.abs(dx) < Math.abs(dy)) return;
    if (dx < 0) goToNext();
    else goToPrevious();
  };

  const handleMouseEnter = () => {
    isPausedRef.current = true;
    // Snapshot elapsed so we resume correctly
    if (startTimeRef.current !== null) {
      elapsedRef.current += Date.now() - startTimeRef.current;
      startTimeRef.current = null;
    }
  };

  const handleMouseLeave = () => {
    isPausedRef.current = false;
    startTimeRef.current = Date.now(); // reset delta start
  };

  if (!currentStory) return null;

  const getTimeAgo = (dateString) => {
    if (!dateString) return '';
    const diff = Math.floor((Date.now() - new Date(dateString)) / 1000);
    if (diff < 60) return 'şimdi';
    if (diff < 3600) return `${Math.floor(diff / 60)}d`;
    if (diff < 86400) return `${Math.floor(diff / 3600)}s`;
    return `${Math.floor(diff / 86400)}g`;
  };

  return (
    <div className={styles.overlay} onClick={onClose}>
      {!isFirst && (
        <button
          className={`${styles.outerNav} ${styles.outerNavLeft}`}
          onClick={(e) => { e.stopPropagation(); goToPrevious(); }}
          aria-label="Önceki"
        >
          <ChevronLeft size={28} />
        </button>
      )}

      <div
        className={styles.container}
        onClick={(e) => e.stopPropagation()}
        onMouseEnter={handleMouseEnter}
        onMouseLeave={handleMouseLeave}
        onTouchStart={handleTouchStart}
        onTouchEnd={handleTouchEnd}
      >
        {/* Progress bars — driven by JS progress state */}
        <div className={styles.progressBars}>
          {stories.map((_, idx) => (
            <div key={idx} className={styles.track}>
              {idx < currentIndex && (
                <div className={styles.bar} style={{ width: '100%' }} />
              )}
              {idx === currentIndex && (
                <div className={styles.bar} style={{ width: `${progress * 100}%` }} />
              )}
            </div>
          ))}
        </div>

        {/* Header */}
        <div className={styles.header}>
          <div className={styles.identity}>
            <div className={styles.avatar}>
              <img src={currentStory.thumbnail || currentStory.photo} alt={currentStory.title} />
            </div>
            <div>
              <p className={styles.name}>{currentStory.title}</p>
              {currentStory.createdAt && (
                <p className={styles.time}>{getTimeAgo(currentStory.createdAt)}</p>
              )}
            </div>
          </div>
          <button className={styles.close} onClick={onClose} aria-label="Kapat">
            <X size={20} />
          </button>
        </div>

        {/* Image */}
        <div className={styles.media}>
          <img
            key={currentIndex}
            src={currentStory.photo || currentStory.image}
            alt={currentStory.title}
            className={animClass}
          />
          <button
            className={`${styles.tap} ${styles.tapLeft}`}
            onClick={goToPrevious}
            disabled={isFirst}
            aria-label="Önceki"
          />
          <button
            className={`${styles.tap} ${styles.tapRight}`}
            onClick={goToNext}
            aria-label="Sonraki"
          />
        </div>

        {(currentStory.description || currentStory.caption) && (
          <div className={styles.footer}>
            <p className={styles.caption}>
              {currentStory.description || currentStory.caption}
            </p>
          </div>
        )}
      </div>

      {!isLast && (
        <button
          className={`${styles.outerNav} ${styles.outerNavRight}`}
          onClick={(e) => { e.stopPropagation(); goToNext(); }}
          aria-label="Sonraki"
        >
          <ChevronRight size={28} />
        </button>
      )}
    </div>
  );
};

export default StoryViewer;