// src/pages/vistualNovelHandler.jsx
import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import '../css/global.css';
import { fetchYamlData } from './components/fetchYamlData';
import StoryPage from './storyPage';
import ConversationPage from './conversationPage.jsx';
import OptionPage from './optionPage.jsx';
import LoadingScene from './components/loadingScene.jsx';
import TransitionPage from './transitionPage.jsx';

function VitualNovelHandler() {
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);
  const [currentStep, setCurrentStep] = useState(0);
  const navigate = useNavigate();
  const { char, lang, step } = useParams();

  useEffect(() => {
    const loadData = async () => {
      try {
        const yamlPath = `/yml/Dialog${char}${lang}.yml`;
        const parsedData = await fetchYamlData({ src: yamlPath });
        if (!Array.isArray(parsedData)) {
          throw new Error('YAML data is not an array');
        }
        setData(parsedData);
      } catch (error) {
        setError(error.message);
      }
    };
    loadData();
  }, []);

  useEffect(() => {
    // Update the current step from the URL parameter
    if (step && !isNaN(step)) {
      setCurrentStep(parseInt(step, 10));
    }
  }, [step]);

  if (error) {
    return <div>Error loading YAML data: {error}</div>;
  }

  if (!data) {
    return <div>Loading...</div>;
  }

  const handleNextStep = (nextstep) => {
    // console.log(data);
    console.log(nextstep)
    if (typeof nextstep !== 'number' || Number.isNaN(nextstep)) {
        navigate(`/end`);//44 is last page
//         console.log("currentStep:", currentStep);
//         console.log("data at currentStep:", data[currentStep]);
    }
    else{
      setCurrentStep(nextstep);
      navigate(`/vs/${char}/${lang}/${nextstep}`);
//       console.log("currentStep:", currentStep);
//       console.log("data at currentStep:", data[currentStep]);
    }
  };

  const currentStepData = data[currentStep] === null ? "end" : data[currentStep];

  const renderComponent = (type) => {
    switch (type) {
      case "story":
        return <StoryPage data={currentStepData} onClicked={handleNextStep}/>;
      case "conversation":
        return <ConversationPage data={currentStepData} onClicked={handleNextStep}/>;
      case "option":
        return <OptionPage data={currentStepData} onClicked={handleNextStep}/>;
      case "transition":
        return <TransitionPage data={currentStepData} onChanged={handleNextStep}/>
      default:
        return <LoadingScene />;
    }
  };

  return (
    <div style={{ width: "100svw", height: "100svh" }}>
      {renderComponent(currentStepData.type === null ? "end" : currentStepData.type)}
    </div>
  );
}

export default VitualNovelHandler;
