'use client';

import { useState, useMemo } from 'react';
import { ChevronRight } from 'lucide-react';

/**
 * NarrativeCardPlayer — Displays mission narrative as a sequence of cards.
 *
 * Supports THREE formats:
 * 1. Plain text (regular missions): Split on double-newline, dialogue detection
 * 2. Structured JSON v1 (legacy prison missions): {intro, dialogue_*, choice_text, choice_a, choice_b}
 * 3. Structured JSON v2 (Phase 8 narratives complexes Hugues/H_01/H_02 — 2026-04-29) :
 *    {
 *      cards: [
 *        { type: 'narration', text: '...' },
 *        { type: 'dialogue', character: '...', text: '...' },
 *        { type: 'choice', text: '?', which: 1, choices: [{key:'A', label:'...'}, ...], gated_by?: 'A' }
 *        ...
 *      ]
 *    }
 *    - which: 1|2|3 → quel slot moral_choice* en backend
 *    - choices: array de 2 ou 3 entrées (A/B/C)
 *    - gated_by: optionnel — la card ne s'affiche que si moral_choice match cette
 *      valeur (ex: card "médecin propose évasion" affichée uniquement si choix A
 *      "Don 50% argent" a été fait à la card précédente). Format : 'A' (filter sur
 *      moral_choice 1) ou 'A_B' (filter sur c1=A ET c2=B).
 *
 * Props:
 * - narrative: the raw narrative string from the mission
 * - hasMoralChoice: whether this mission has a moral choice
 * - onComplete: called when all cards are read.
 *   Signature étendue v2 : (choices: { 1?: 'A'|'B'|'C', 2?: ..., 3?: ... }) => void
 *   Pour rétro-compat v1 : si seul moral_choice_1 set → passe 'a'/'b' simple aussi
 *   au format legacy.
 */

interface NarrativeCardChoice {
  key: 'A' | 'B' | 'C';
  label: string;
  /**
   * Phase 8 v2 narratives (2026-05-01) — Liste de prérequis à satisfaire
   * pour pouvoir cliquer ce choix. Les clés sont matchées contre le
   * `requirementsContext` passé en prop par le parent (MissionModal).
   * Si un prérequis n'est pas satisfait, le bouton apparaît grisé (disabled)
   * avec une infobulle indiquant le prérequis manquant.
   *
   * Exemples : ['has_vehicle'], ['has_phone', 'has_weapon']
   */
  requires?: string[];
}

interface NarrativeCard {
  type: 'narration' | 'dialogue' | 'choice';
  text: string;
  character?: string;
  // v1 legacy single choice
  choiceA?: string;
  choiceB?: string;
  // v2 multi-choix
  which?: 1 | 2 | 3;
  choices?: NarrativeCardChoice[];
  gated_by?: string;
}

export type MoralChoiceMap = Partial<Record<1 | 2 | 3, 'A' | 'B' | 'C'>>;

interface NarrativeCardPlayerProps {
  narrative: string;
  hasMoralChoice?: boolean;
  missionTitle?: string;
  /** Phase 8 v2 narratives — onComplete reçoit le map des choix indexé par which */
  onComplete: (choices: MoralChoiceMap) => void;
  /**
   * Phase 8 v2 narratives (2026-05-01) — Map state-keys → boolean utilisé
   * par les choix avec `requires`. Le parent (MissionModal) construit ce
   * dictionnaire selon l'état joueur (véhicule dispo, téléphone, etc.).
   * Si une clé absente du dico → considérée comme false (manquante).
   *
   * Clés actuellement supportées :
   *   - has_vehicle : true si player a au moins une voiture owned non-bloquée
   */
  requirementsContext?: Record<string, boolean>;
}

/** Parse narrative into structured cards */
function parseNarrative(raw: string, hasMoralChoice?: boolean): NarrativeCard[] {
  if (!raw || !raw.trim()) return [{ type: 'narration', text: 'Aucun narratif disponible.' }];

  // Try JSON format
  try {
    const json = JSON.parse(raw);
    if (typeof json === 'object' && json !== null) {
      // ─── v2 format : array `cards: [...]` ───
      if (Array.isArray(json.cards)) {
        return json.cards.map((c: any) => ({
          type: c.type || 'narration',
          text: c.text || '',
          character: c.character,
          which: c.which,
          // Format seed v2 : choices peut utiliser `key` (legacy) OU `value`
          // (consigne user). On normalise sur `key` côté frontend.
          choices: Array.isArray(c.choices)
            ? c.choices.map((x: any) => ({
                key: x.key || x.value,
                label: x.label,
                requires: Array.isArray(x.requires) ? x.requires : undefined,
              }))
            : undefined,
          gated_by: c.gated_by,
          // Compatibility with v1 single-choice cards
          choiceA: Array.isArray(c.choices)
            ? (c.choices.find((x: any) => (x.key || x.value) === 'A')?.label)
            : c.choiceA,
          choiceB: Array.isArray(c.choices)
            ? (c.choices.find((x: any) => (x.key || x.value) === 'B')?.label)
            : c.choiceB,
        })) as NarrativeCard[];
      }

      // ─── v1 legacy format : {intro, dialogue_*, choice_text, choice_a, choice_b} ───
      if (json.intro) {
        const cards: NarrativeCard[] = [];
        if (json.intro) cards.push({ type: 'narration', text: json.intro });
        for (const [key, value] of Object.entries(json)) {
          if (key.startsWith('dialogue_') && typeof value === 'string') {
            const charName = key.replace('dialogue_', '').replace(/_/g, ' ');
            const formattedName = charName.charAt(0).toUpperCase() + charName.slice(1);
            cards.push({ type: 'dialogue', text: value, character: formattedName });
          }
        }
        if (json.choice_text && json.choice_a && json.choice_b) {
          // Phase 8.6a — choice_c support pour PR_TC_03 (3 choix sur 1 card)
          const choices: NarrativeCardChoice[] = [
            { key: 'A', label: json.choice_a },
            { key: 'B', label: json.choice_b },
          ];
          if (json.choice_c) choices.push({ key: 'C', label: json.choice_c });
          cards.push({
            type: 'choice',
            text: json.choice_text,
            which: 1,
            choices,
            choiceA: json.choice_a,
            choiceB: json.choice_b,
          });
        }
        // Phase 8.12 — final_text_a / final_text_b (épilogue par choix)
        // Affichés via gating gated_by='A' / 'B' en cards conditionnelles
        if (json.final_text_a) {
          cards.push({ type: 'narration', text: json.final_text_a, gated_by: 'A' });
        }
        if (json.final_text_b) {
          cards.push({ type: 'narration', text: json.final_text_b, gated_by: 'B' });
        }
        if (json.final_text) cards.push({ type: 'narration', text: json.final_text });
        return cards.length > 0 ? cards : [{ type: 'narration', text: raw }];
      }
    }
  } catch {
    // Not JSON, parse as plain text below
  }

  // Plain text format
  const paragraphs = raw.split(/\n\n+/).map(p => p.trim()).filter(Boolean);
  const cards: NarrativeCard[] = [];
  let choiceDetected = false;

  for (const para of paragraphs) {
    if (!choiceDetected && (para.includes('CHOIX MORAL') || para.includes('CHOIX :') || para.match(/^A\)/m))) {
      const lines = para.split('\n');
      let choiceText = '';
      let choiceA = '';
      let choiceB = '';
      for (const line of lines) {
        const trimmed = line.trim();
        if (trimmed.match(/^A[\)\.]/)) choiceA = trimmed.replace(/^A[\)\.]?\s*/, '');
        else if (trimmed.match(/^B[\)\.]/)) choiceB = trimmed.replace(/^B[\)\.]?\s*/, '');
        else if (!trimmed.startsWith('CHOIX')) choiceText += (choiceText ? ' ' : '') + trimmed;
      }
      if (choiceA && choiceB) {
        cards.push({ type: 'choice', text: choiceText || 'Que faites-vous ?', choiceA, choiceB,
          which: 1, choices: [{ key: 'A', label: choiceA }, { key: 'B', label: choiceB }] });
        choiceDetected = true;
        continue;
      }
    }

    const lines = para.split('\n');
    const firstLine = lines[0]?.trim() || '';
    const isDialogue = firstLine.startsWith('—') || firstLine.startsWith('--') ||
      firstLine.startsWith('"') || firstLine.startsWith('«') ||
      firstLine.startsWith('–');

    if (isDialogue) {
      let character: string | undefined;
      const dashMatch = firstLine.match(/^[—–-]+\s*(?:«\s*)?([A-Z][a-z]+(?:\s[A-Z][a-z]+)?)\s*[,.:]/);
      if (dashMatch) character = dashMatch[1];
      cards.push({ type: 'dialogue', text: para, character });
    } else {
      cards.push({ type: 'narration', text: para });
    }
  }

  if (hasMoralChoice && !choiceDetected) {
    cards.push({
      type: 'choice', text: 'Que choisissez-vous ?',
      choiceA: 'Choix A', choiceB: 'Choix B',
      which: 1, choices: [{ key: 'A', label: 'Choix A' }, { key: 'B', label: 'Choix B' }],
    });
  }

  return cards.length > 0 ? cards : [{ type: 'narration', text: raw }];
}

/**
 * Vérifie si une card gated_by doit être affichée selon les choix faits.
 * Format gated_by : 'A' (match c1=A) ou 'A_B' (match c1=A ET c2=B) ou 'A_B_C' etc.
 */
function gatePass(gated_by: string | undefined, choices: MoralChoiceMap): boolean {
  if (!gated_by) return true;
  const required = gated_by.split('_');
  for (let i = 0; i < required.length; i++) {
    const slot = (i + 1) as 1 | 2 | 3;
    if (choices[slot] !== required[i]) return false;
  }
  return true;
}

export function NarrativeCardPlayer({ narrative, hasMoralChoice, missionTitle, onComplete, requirementsContext }: NarrativeCardPlayerProps) {
  const allCards = useMemo(() => parseNarrative(narrative, hasMoralChoice), [narrative, hasMoralChoice]);
  const [currentIndex, setCurrentIndex] = useState(0);
  const [choices, setChoices] = useState<MoralChoiceMap>({});
  const [pendingChoice, setPendingChoice] = useState<'A' | 'B' | 'C' | null>(null);

  // Cards visibles = filtrées par gated_by selon les choix actuels
  const visibleCards = useMemo(
    () => allCards.filter((c) => gatePass(c.gated_by, choices)),
    [allCards, choices],
  );

  const card = visibleCards[currentIndex];
  const isLast = currentIndex >= visibleCards.length - 1;
  const isChoice = card?.type === 'choice';
  const progress = visibleCards.length > 1 ? ((currentIndex + 1) / visibleCards.length) * 100 : 100;

  const handleNext = () => {
    if (isChoice && !pendingChoice) return;
    if (isChoice && card.which && pendingChoice) {
      // Persist choix dans le map indexé par `which`
      const newChoices = { ...choices, [card.which]: pendingChoice };

      // Phase 8 v3 (2026-05-03) FIX critique — Le `isLast` calculé en haut
      // utilise les ANCIENNES visibleCards (avant ce choix). Pour un choice,
      // les nouveaux choices peuvent débloquer des cards `gated_by` qui
      // étendent visibleCards → on doit RECALCULER avec newChoices avant de
      // décider si la mission est finie ou non. Bug avant fix : à C2 (last
      // card de la liste pré-choix), onComplete était appelé PRÉMATURÉMENT
      // → la mission se terminait sans afficher les cards A_A finales.
      const newVisibleCards = allCards.filter((c) => gatePass(c.gated_by, newChoices));
      const newCurrentIndex = newVisibleCards.indexOf(card);
      const nextIndex = newCurrentIndex + 1;

      setChoices(newChoices);
      setPendingChoice(null);

      if (nextIndex >= newVisibleCards.length) {
        // Aucune card suivante visible → vraie fin
        onComplete(newChoices);
        return;
      }
      setCurrentIndex(nextIndex);
      return;
    }
    if (isLast) {
      onComplete(choices);
    } else {
      setCurrentIndex(currentIndex + 1);
    }
  };

  if (!card) {
    // Fallback : si tous les cards sont gated_by et none match, on appelle quand même onComplete
    if (allCards.length > 0 && visibleCards.length === 0) {
      // Edge case : sécurité
      return (
        <button onClick={() => onComplete(choices)} className="w-full py-2.5 rounded-xl text-xs font-bold"
          style={{ background: 'var(--color-gold)', color: '#000' }}>Continuer</button>
      );
    }
    return null;
  }

  const choicesToRender = card.choices ?? (card.choiceA && card.choiceB ? [
    { key: 'A' as const, label: card.choiceA },
    { key: 'B' as const, label: card.choiceB },
  ] : []);

  return (
    <div className="flex flex-col gap-3">
      <div className="flex items-center gap-2">
        <div className="flex-1 h-1 rounded-full overflow-hidden" style={{ background: 'var(--bg-tertiary)' }}>
          <div className="h-full rounded-full transition-all duration-300" style={{ width: `${progress}%`, background: 'var(--color-gold)' }} />
        </div>
        <span className="text-[9px] shrink-0" style={{ color: 'var(--text-muted)' }}>{currentIndex + 1}/{visibleCards.length}</span>
      </div>

      <div
        className="p-4 rounded-xl text-xs leading-relaxed min-h-[120px]"
        style={{
          background: isChoice ? 'rgba(139,92,246,0.06)' : card.type === 'dialogue' ? 'rgba(200,155,60,0.06)' : 'var(--bg-tertiary)',
          border: isChoice ? '1px solid rgba(139,92,246,0.2)' : card.type === 'dialogue' ? '1px solid rgba(200,155,60,0.15)' : '1px solid var(--border-dark)',
        }}
      >
        {card.character && (
          <p className="text-[10px] font-bold mb-2" style={{ color: 'var(--color-gold)' }}>{card.character}</p>
        )}

        {card.text.split('\n').map((line, i) => {
          const trimmed = line.trim();
          if (!trimmed) return <br key={i} />;
          if (trimmed.startsWith('—') || trimmed.startsWith('--') || trimmed.startsWith('"') || trimmed.startsWith('«')) {
            return <p key={i} className="my-1 font-medium" style={{ color: 'var(--text-primary)' }}>{trimmed}</p>;
          }
          return <p key={i} className="my-1" style={{ color: 'var(--text-secondary)', fontStyle: card.type === 'narration' ? 'italic' : 'normal' }}>{trimmed}</p>;
        })}

        {isChoice && choicesToRender.length > 0 && (
          <div className="mt-3 flex flex-col gap-2">
            {choicesToRender.map((c) => {
              // Phase 8 v2 narratives (2026-05-01) — Si requires non satisfait,
              // bouton grisé + cliquable interdit + tooltip listant les manques.
              const reqs = (c as NarrativeCardChoice).requires ?? [];
              const missing = reqs.filter((r) => !requirementsContext?.[r]);
              const isLocked = missing.length > 0;
              const tooltip = isLocked
                ? `Choix indisponible. Prérequis manquant : ${missing.join(', ')}`
                : undefined;
              return (
                <button
                  key={c.key}
                  onClick={() => { if (!isLocked) setPendingChoice(c.key); }}
                  disabled={isLocked}
                  title={tooltip}
                  className="w-full p-3 rounded-lg text-[11px] text-left transition-all disabled:cursor-not-allowed"
                  style={{
                    background: isLocked
                      ? 'rgba(255,255,255,0.02)'
                      : pendingChoice === c.key
                        ? 'rgba(200,155,60,0.15)'
                        : 'rgba(255,255,255,0.03)',
                    border: isLocked
                      ? '1px dashed var(--border-dark)'
                      : pendingChoice === c.key
                        ? '2px solid var(--color-gold)'
                        : '1px solid var(--border-dark)',
                    color: isLocked
                      ? 'var(--text-muted)'
                      : pendingChoice === c.key
                        ? 'var(--color-gold)'
                        : 'var(--text-secondary)',
                    fontWeight: pendingChoice === c.key ? 700 : 400,
                    opacity: isLocked ? 0.45 : 1,
                  }}
                >
                  <span className="font-bold" style={{ color: 'var(--text-primary)' }}>{c.key}.</span> {c.label}
                  {isLocked && <span className="block text-[9px] mt-1" style={{ color: 'var(--color-red-light)' }}>🔒 {tooltip}</span>}
                </button>
              );
            })}
          </div>
        )}
      </div>

      <button
        onClick={handleNext}
        disabled={isChoice && !pendingChoice}
        className="w-full py-2.5 rounded-xl text-xs font-bold flex items-center justify-center gap-1 transition-all disabled:opacity-40"
        style={{
          background: (isChoice && !pendingChoice) ? 'rgba(255,255,255,0.06)' : 'var(--color-gold)',
          color: (isChoice && !pendingChoice) ? 'var(--text-muted)' : '#000',
        }}
      >
        {isLast ? (isChoice ? 'Confirmer et continuer' : 'Continuer') : 'Suivant'}
        {!isLast && <ChevronRight size={14} />}
      </button>
    </div>
  );
}

export { parseNarrative };
export type { NarrativeCard };
