'use client';

import { useEffect, useRef, useState } from 'react';
import { X, BookOpen } from 'lucide-react';
import { useGameStore } from '@/stores/gameStore';
import { TUTORIAL_STEPS, TutorialStep, TUTORIAL_MAP } from './tutorialSteps';
import { api } from '@/lib/api';

/**
 * Phase 5 — TutorialManager : orchestre les lightbox tutorielles.
 *
 * Monté dans GameLayout.tsx après les overlays. Écoute les changements
 * de uiVisibility via Zustand. Quand une clé passe de false→true et que
 * le joueur n'a pas encore vu ce tuto (tutorialSeen), empile le step
 * dans une file d'attente et affiche le premier.
 *
 * Pas de dépendance externe (driver.js etc.) — lightbox maison.
 */

export function TutorialManager() {
  const uiVisibility = useGameStore((s) => s.uiVisibility);
  const tutorialSeen = useGameStore((s) => s.tutorialSeen);
  const markTutorialSeen = useGameStore((s) => s.markTutorialSeen);

  const [queue, setQueue] = useState<TutorialStep[]>([]);
  const [current, setCurrent] = useState<TutorialStep | null>(null);
  // Init with current state to avoid triggering ALL tutorials on first mount
  const prevVisibilityRef = useRef<Record<string, boolean> | null>(null);

  // Detect newly unlocked features → enqueue tutorials
  useEffect(() => {
    // Build snapshot of current visibility
    const snapshot: Record<string, boolean> = {};
    for (const k of Object.keys(uiVisibility)) {
      snapshot[k] = !!(uiVisibility as any)[k];
    }

    // First mount: just record current state, don't trigger any tutorials
    if (prevVisibilityRef.current === null) {
      prevVisibilityRef.current = snapshot;
      return;
    }

    const prev = prevVisibilityRef.current;
    const newSteps: TutorialStep[] = [];

    for (const step of TUTORIAL_STEPS) {
      const key = step.triggerKey as keyof typeof uiVisibility;
      const wasVisible = !!prev[key];
      const isNowVisible = !!(uiVisibility as any)[key];
      const alreadySeen = !!tutorialSeen[step.triggerKey];

      if (!wasVisible && isNowVisible && !alreadySeen) {
        newSteps.push(step);
      }
    }

    prevVisibilityRef.current = snapshot;

    if (newSteps.length > 0) {
      setQueue((q) => [...q, ...newSteps]);
    }
  }, [uiVisibility, tutorialSeen]);

  // Pop from queue when nothing is showing
  useEffect(() => {
    if (!current && queue.length > 0) {
      setCurrent(queue[0]);
      setQueue((q) => q.slice(1));
    }
  }, [current, queue]);

  const handleDismiss = () => {
    if (current) {
      markTutorialSeen(current.triggerKey);
      // Fire-and-forget backend persist
      api.player?.markTutorialSeen?.(current.triggerKey).catch(() => null);
      setCurrent(null);
    }
  };

  if (!current) return null;

  const isSpotlight = current.type === 'spotlight' && current.targetAttr;

  // Spotlight: find target element and compute position
  const targetEl = isSpotlight
    ? document.querySelector(`[data-tutorial="${current.targetAttr}"]`) as HTMLElement | null
    : null;
  const targetRect = targetEl?.getBoundingClientRect() ?? null;

  // Spotlight overlay with clip-path hole
  if (isSpotlight && targetRect) {
    const pad = 8; // padding around the target
    const rx = targetRect.x - pad;
    const ry = targetRect.y - pad;
    const rw = targetRect.width + pad * 2;
    const rh = targetRect.height + pad * 2;
    const br = 12; // border radius

    // Tooltip position: below the target, centered
    const tooltipTop = targetRect.bottom + 16;
    const tooltipLeft = Math.max(16, Math.min(window.innerWidth - 340, targetRect.left + targetRect.width / 2 - 160));

    return (
      <div className="fixed inset-0 z-[3000]">
        {/* Overlay with hole */}
        <svg className="absolute inset-0 w-full h-full pointer-events-auto" onClick={handleDismiss}>
          <defs>
            <mask id="spotlight-mask">
              <rect x="0" y="0" width="100%" height="100%" fill="white" />
              <rect x={rx} y={ry} width={rw} height={rh} rx={br} fill="black" />
            </mask>
          </defs>
          <rect x="0" y="0" width="100%" height="100%" fill="rgba(0,0,0,0.7)" mask="url(#spotlight-mask)" />
        </svg>

        {/* Highlight border around target */}
        <div
          className="absolute pointer-events-none"
          style={{
            left: rx, top: ry, width: rw, height: rh,
            borderRadius: br,
            border: '2px solid var(--color-gold)',
            boxShadow: '0 0 20px rgba(212,168,67,0.3)',
          }}
        />

        {/* Tooltip below target */}
        <div
          className="absolute pointer-events-auto rounded-2xl overflow-hidden"
          style={{
            left: tooltipLeft, top: tooltipTop,
            width: 320, maxWidth: 'calc(100vw - 32px)',
            background: 'var(--bg-panel)',
            border: '1px solid var(--border-dark)',
            boxShadow: '0 20px 60px rgba(0,0,0,0.5), 0 0 30px rgba(212,168,67,0.1)',
          }}
          onClick={(e) => e.stopPropagation()}
        >
          {/* Arrow pointing up */}
          <div
            className="absolute -top-2 left-1/2 -translate-x-1/2 w-4 h-4 rotate-45"
            style={{ background: 'var(--bg-panel)', border: '1px solid var(--border-dark)', borderRight: 'none', borderBottom: 'none' }}
          />
          <div className="px-4 py-3">
            <div className="flex items-center gap-2 mb-2">
              {current.icon && <span className="text-lg">{current.icon}</span>}
              <p className="text-sm font-bold" style={{ color: 'var(--color-gold)' }}>{current.title}</p>
            </div>
            <p className="text-xs leading-relaxed" style={{ color: 'var(--text-secondary)' }}>{current.body}</p>
          </div>
          <div className="flex items-center justify-end px-4 py-2" style={{ borderTop: '1px solid var(--border-dark)' }}>
            <button
              onClick={handleDismiss}
              className="px-4 py-1.5 rounded-xl text-xs font-bold transition-all hover:scale-[1.02]"
              style={{ background: 'var(--color-gold)', color: '#000' }}
            >
              {queue.length > 0 ? `Suivant (${queue.length + 1})` : "J'ai compris"}
            </button>
          </div>
        </div>
      </div>
    );
  }

  // Lightbox mode (default)
  return (
    <div className="fixed inset-0 z-[3000] flex items-center justify-center pointer-events-none">
      {/* Backdrop — semi-transparent */}
      <div
        className="absolute inset-0 pointer-events-auto"
        style={{ background: 'rgba(0,0,0,0.6)' }}
        onClick={handleDismiss}
      />

      {/* Lightbox */}
      <div
        className="relative pointer-events-auto w-[88vw] max-w-[420px] rounded-2xl overflow-hidden"
        style={{
          background: 'var(--bg-panel)',
          border: '1px solid var(--border-dark)',
          boxShadow: '0 20px 80px rgba(0,0,0,0.5), 0 0 40px rgba(212,168,67,0.15)',
        }}
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div
          className="flex items-center justify-between px-5 py-4"
          style={{ borderBottom: '1px solid var(--border-dark)' }}
        >
          <div className="flex items-center gap-3">
            {current.icon && (
              <span className="text-2xl">{current.icon}</span>
            )}
            <div>
              <p className="text-sm font-bold" style={{ color: 'var(--color-gold)' }}>
                Nouveau : {current.title}
              </p>
              <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>
                Fonctionnalite deverrouillee
              </p>
            </div>
          </div>
          <button
            onClick={handleDismiss}
            className="w-8 h-8 rounded-lg flex items-center justify-center hover:opacity-80"
            style={{ background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.08)' }}
          >
            <X size={14} style={{ color: 'var(--text-muted)' }} />
          </button>
        </div>

        {/* Body */}
        <div className="px-5 py-4">
          <p className="text-xs leading-relaxed" style={{ color: 'var(--text-secondary)' }}>
            {current.body}
          </p>
        </div>

        {/* Footer */}
        <div
          className="flex items-center justify-between px-5 py-3"
          style={{ borderTop: '1px solid var(--border-dark)' }}
        >
          {current.docAnchor ? (
            <a
              href={`/documentation#${current.docAnchor}`}
              target="_blank"
              rel="noopener noreferrer"
              className="flex items-center gap-1.5 text-[10px] hover:underline"
              style={{ color: 'var(--text-muted)' }}
            >
              <BookOpen size={11} />
              En savoir plus
            </a>
          ) : (
            <span />
          )}

          <button
            onClick={handleDismiss}
            className="px-5 py-2 rounded-xl text-xs font-bold transition-all hover:scale-[1.02]"
            style={{
              background: 'var(--color-gold)',
              color: '#000',
            }}
          >
            {queue.length > 0 ? `Suivant (${queue.length + 1})` : "J'ai compris"}
          </button>
        </div>

        {/* Queue indicator */}
        {queue.length > 0 && (
          <div className="px-5 pb-3">
            <div className="flex gap-1">
              {[current, ...queue].map((_, i) => (
                <div
                  key={i}
                  className="h-1 rounded-full flex-1"
                  style={{
                    background: i === 0 ? 'var(--color-gold)' : 'rgba(255,255,255,0.1)',
                  }}
                />
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
