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

/** Full-screen VN overlay with prose, choices, and desktop story log sidebar. */
export function StoryPanel() {
  const open = useGameStore((s) => s.storyPanelOpen);
  const story = useGameStore((s) => s.story);
  const storyLog = useGameStore((s) => s.storyLog);

  if (!open) return null;

  const hasChoices = story.choices.length > 0;

  return (
    <div
      className="fixed inset-0 z-50 flex bg-black/80"
      role="dialog"
      aria-modal="true"
      aria-label="Story"
    >
      <div className="flex flex-1 flex-col md:flex-row">
        <aside className="hidden max-h-full w-full overflow-y-auto border-slate-700 border-r p-4 md:block md:w-1/3">
          <h3 className="mb-2 font-medium text-slate-400 text-xs uppercase tracking-wide">
            Story log
          </h3>
          <ul className="flex flex-col gap-2 text-slate-300 text-sm">
            {storyLog.map((entry) => (
              <li key={`${entry.nodeId}:${entry.choiceLabel ?? ''}:${entry.prose}`}>
                {entry.choiceLabel ? (
                  <span className="text-amber-400/80">[{entry.choiceLabel}] </span>
                ) : null}
                {entry.prose}
              </li>
            ))}
          </ul>
        </aside>
        <main className="flex flex-1 flex-col gap-4 p-6">
          <p className="flex-1 text-lg text-slate-100 leading-relaxed">{story.currentProse}</p>
          {hasChoices ? (
            <div className="flex flex-col gap-2">
              {story.choices.map((choice) => (
                <button
                  key={choice.id}
                  type="button"
                  disabled={choice.disabled}
                  title={choice.disabled ? (choice.disabledReason ?? undefined) : undefined}
                  onClick={() => gameRuntime.applyStoryChoice(choice.id)}
                  className="rounded-lg border border-slate-600 bg-slate-900/60 px-4 py-3 text-left transition-colors hover:border-amber-500/60 disabled:cursor-not-allowed disabled:opacity-40"
                >
                  {choice.label}
                </button>
              ))}
            </div>
          ) : (
            <button
              type="button"
              onClick={() => gameRuntime.continueStory()}
              className="self-start rounded-lg bg-amber-600 px-4 py-2 transition-colors hover:bg-amber-500"
            >
              Continue
            </button>
          )}
          <button
            type="button"
            onClick={() => gameRuntime.closeStoryPanel()}
            className="self-end text-slate-400 text-sm transition-colors hover:text-slate-200"
          >
            Close
          </button>
        </main>
      </div>
    </div>
  );
}
