'use client';

import { useState } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import type { AgePageData } from '../ageConfig';
import { saveSessionChoice } from '../session';
import ProgressBar from './ProgressBar';

interface AgeSectionProps {
  data: AgePageData;
  nextSection?: string;
  slug: string;
}

export default function AgeSection({ data, nextSection, slug }: AgeSectionProps) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const qs = searchParams.toString();
  const suffix = qs ? `?${qs}` : '';
  const [disabled, setDisabled] = useState(false);

  const handleClick = async (option: string) => {
    if (!nextSection || disabled) return;
    setDisabled(true);
    await saveSessionChoice(slug, option);
    router.push(`/onboarding/${nextSection}${suffix}`);
  };

  return (
    <>
      <ProgressBar currentSlug={slug} />
      <main className="age-page">
        <div className="age-card">
          <h1 className="age-question">{data.question}</h1>
          <div className="age-options">
            {data.options.map((option) => (
              <button
                key={option}
                type="button"
                className="age-option-btn"
                onClick={() => handleClick(option)}
                disabled={disabled}
              >
                {option}
              </button>
            ))}
          </div>
        </div>
      </main>
    </>
  );
}
