import { gameRuntime } from '../state/runtime';
import { useGameStore } from '../state/store';
import { StoryProseLog } from './StoryProseLog';
import { StoryTree } from './StoryTree';

export function StoryView() {
  const tree = useGameStore((s) => s.story.tree);
  const log = useGameStore((s) => s.storyLog);
  const selectedId = useGameStore((s) => s.selectedStoryNodeId);
  const currentProse = useGameStore((s) => s.story.currentProse);
  const choicesLength = useGameStore((s) => s.story.choices.length);

  // Boot intro: show Continue button when there's prose, no choices, and no tree yet
  const isBootIntro = currentProse != null && choicesLength === 0 && tree.length === 0;

  if (isBootIntro) {
    return (
      <div className="flex h-[calc(100dvh-6rem)] flex-col items-center justify-center gap-6">
        <p className="max-w-lg text-center text-lg leading-relaxed text-slate-100 whitespace-pre-wrap">
          {currentProse}
        </p>
        <button
          type="button"
          onClick={() => gameRuntime.continueStory()}
          className="cursor-pointer rounded-lg bg-amber-600 px-6 py-2.5 font-medium text-slate-100 transition-colors hover:bg-amber-500"
        >
          Continue
        </button>
      </div>
    );
  }

  return (
    <div className="grid h-[calc(100dvh-6rem)] grid-cols-[3fr_2fr] gap-4">
      <StoryTree
        nodes={tree}
        selectedId={selectedId}
        onSelect={(id) => useGameStore.getState().setSelectedStoryNodeId(id)}
      />
      <StoryProseLog log={log} selectedId={selectedId} />
    </div>
  );
}
