"use client";

import { useEffect, useState } from "react";
import { useCreator } from "../CreatorContext";
import SelectorGrid from "../components/SelectorGrid";
import Modal from "../components/Modal";
import BackgroundBuilder from "../components/BackgroundBuilder";

export default function BackgroundStep() {
  const { backgrounds, refreshBackgrounds, draft, update } = useCreator();
  const [builderOpen, setBuilderOpen] = useState(false);

  useEffect(() => { refreshBackgrounds(); }, [refreshBackgrounds]);

  return (
    <div className="space-y-6">
      <div>
        <h2 className="text-2xl font-bold text-neutral-100">Choose a Background</h2>
        <p className="text-sm text-neutral-400 mt-1">Your character&apos;s life before adventuring.</p>
      </div>

      <SelectorGrid
        items={backgrounds}
        selectedId={draft.backgroundId}
        onSelect={(b) => update({ backgroundId: b.id })}
        onAddCustom={() => setBuilderOpen(true)}
        addLabel="Add Background"
        renderMeta={(b) => `${b.skillProficiencies?.length ?? 0} skills`}
      />

      <Modal open={builderOpen} onClose={() => setBuilderOpen(false)} title="Create Custom Background" wide confirmClose>
        <BackgroundBuilder
          onCancel={() => setBuilderOpen(false)}
          onSave={async (b) => {
            await refreshBackgrounds();
            update({ backgroundId: b.id });
            setBuilderOpen(false);
          }}
        />
      </Modal>
    </div>
  );
}
