'use client';

import { useState } from 'react';
import { useGameStore } from '@/stores/gameStore';
import { api } from '@/lib/api';
import { StepName } from './steps/StepName';
import { StepArrival } from './steps/StepArrival';
import { StepHousing } from './steps/StepHousing';
import { StepFirstNight } from './steps/StepFirstNight';
import { StepJournal } from './steps/StepJournal';
import { StepPhone } from './steps/StepPhone';
import { StepFirstJob } from './steps/StepFirstJob';
import { StepExtraBill } from './steps/StepExtraBill';
import { StepPhoneTutorial } from './steps/StepPhoneTutorial';
import { StepComplete } from './steps/StepComplete';

/**
 * Onboarding steps — order matters.
 * Step 0: StepName (character name — immersive dialogue)
 * Step 1: StepArrival (country/city selection + map click for territory)
 * Step 2: StepHousing (find a roof)
 * Step 3: StepFirstNight (personality quiz — axes)
 * Step 4: StepJournal (discover the journal)
 * Step 5: StepPhone (find a phone)
 * Step 6: StepFirstJob (first job)
 * Step 7: StepExtraBill (the extra bill)
 * Step 8: StepPhoneTutorial (phone tutorial)
 * Step 9: StepComplete (final — "let's get serious")
 */
const STEPS = [
  { id: 0, component: StepName, title: 'Ton Nom' },
  { id: 1, component: StepArrival, title: "L'Arrivée" },
  { id: 2, component: StepHousing, title: 'Trouver un Toit' },
  { id: 3, component: StepFirstNight, title: 'Première Nuit' },
  { id: 4, component: StepJournal, title: 'Le Journal' },
  { id: 5, component: StepPhone, title: 'Trouver un Téléphone' },
  { id: 6, component: StepFirstJob, title: 'Premier Boulot' },
  { id: 7, component: StepExtraBill, title: 'Le Billet Supplémentaire' },
  { id: 8, component: StepPhoneTutorial, title: 'Le Téléphone' },
  { id: 9, component: StepComplete, title: 'Passons aux choses sérieuses' },
];

interface OnboardingProps {
  onComplete: () => void;
}

export function OnboardingManager({ onComplete }: OnboardingProps) {
  const { player, updateOnboardingStep, unlockUI } = useGameStore();
  const [currentStep, setCurrentStep] = useState(player?.onboarding_step ?? 0);

  const goNext = async () => {
    const next = currentStep + 1;
    updateOnboardingStep(next);

    // Persist step to backend (fire-and-forget)
    if (player?.id) {
      api.player.updateProfile(player.id, { onboarding_step: next }).catch((err) => {
        console.warn('[Onboarding] Step persist failed:', err);
      });
    }

    // Progressive UI unlock at specific steps
    if (next === 4) unlockUI('journal');         // After journal step
    if (next === 5) unlockUI('phone');           // After phone step
    if (next === 5) unlockUI('missions');        // Missions appear after phone
    if (next === 6) unlockUI('employment');      // After first job step
    if (next === 7) unlockUI('inventory');       // After extra bill step
    if (next === 8) unlockUI('contacts');        // After phone tutorial

    if (next >= STEPS.length) {
      // Final: unlock everything remaining + mark onboarding complete
      unlockUI('sidebar_left');
      unlockUI('sidebar_right');
      unlockUI('map');
      unlockUI('chat');
      unlockUI('finances');
      unlockUI('businesses');

      // Call backend to mark onboarding as completed
      if (player?.id) {
        try {
          await api.player.completeOnboarding(player.id, {
            character_name: player.character_name || undefined,
          });
        } catch (err) {
          console.error('[Onboarding] completeOnboarding failed:', err);
        }
      }

      onComplete();
    } else {
      setCurrentStep(next);
    }
  };

  const step = STEPS[currentStep];
  if (!step) return null;

  const StepComponent = step.component;

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center overflow-y-auto"
      style={{ background: 'var(--bg-primary)' }}
    >
      {/* Progress bar */}
      <div className="absolute top-0 left-0 right-0 h-1" style={{ background: 'var(--bg-tertiary)' }}>
        <div
          className="h-full transition-all duration-500"
          style={{
            width: `${((currentStep + 1) / STEPS.length) * 100}%`,
            background: 'linear-gradient(90deg, var(--color-red-dark), var(--color-gold))',
          }}
        />
      </div>

      {/* Step indicator */}
      <div className="absolute top-4 right-6 text-xs" style={{ color: 'var(--text-muted)' }}>
        {currentStep + 1} / {STEPS.length}
      </div>

      {/* Step content */}
      <div className="w-full max-w-2xl px-6 py-12">
        <StepComponent onNext={goNext} />
      </div>
    </div>
  );
}
