'use client';

import { useRef, useState } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import type { StoryPayload } from '../payloads';
import { saveSessionChoice } from '../session';
import ProgressBar from './ProgressBar';

interface StorySectionProps {
  data: StoryPayload;
  nextSection?: string;
  slug: string;
}

export default function StorySection({ data, nextSection, slug }: StorySectionProps) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const qs = searchParams.toString();
  const suffix = qs ? `?${qs}` : '';
  const [choice, setChoice] = useState<'yes' | 'no' | null>(null);
  const [videoLoaded, setVideoLoaded] = useState(false);
  const videoRef = useRef<HTMLVideoElement>(null);

  const handleClick = async (value: 'yes' | 'no') => {
    if (choice) return;
    setChoice(value);
    await saveSessionChoice(slug, value);
    if (nextSection) {
      setTimeout(() => {
        router.push(`/onboarding/${nextSection}${suffix}`);
      }, 400);
    }
  };

  const handleVideoCanPlay = () => {
    setVideoLoaded(true);
    videoRef.current?.play().catch(() => {});
  };

  return (
    <>
      <ProgressBar currentSlug={slug} />
      <main className="story-page">
        <div className="story-content">
          <h1 className="story-question">{data.question}</h1>

          <div className="story-media">
            {/* Thumbnail shown while video loads */}
            {!videoLoaded && (
              <img
                src={data.thumbnail}
                alt={data.title}
                className="story-thumbnail"
              />
            )}
            {/* Video loads in background, plays on loop once ready */}
            <video
              ref={videoRef}
              src={data.video}
              poster={data.thumbnail}
              loop
              muted
              playsInline
              preload="auto"
              onCanPlay={handleVideoCanPlay}
              style={{ display: videoLoaded ? 'block' : 'none' }}
            />
          </div>

          <p className="story-title">{data.title}</p>
        </div>

        <div className="story-buttons">
          <button
            type="button"
            className={`wholething-btn${choice === 'no' ? ' active' : ''}`}
            onClick={() => handleClick('no')}
            disabled={choice !== null}
          >
            <span className="emoji">👎</span>
            <span>No</span>
          </button>
          <button
            type="button"
            className={`wholething-btn${choice === 'yes' ? ' active' : ''}`}
            onClick={() => handleClick('yes')}
            disabled={choice !== null}
          >
            <span className="emoji">👍</span>
            <span>Yes</span>
          </button>
        </div>
      </main>
    </>
  );
}
