// onboarding-tour.jsx — Tour guidé first-login (sans dépendance externe)
// Implémentation home-made plus légère que react-joyride : highlight + tooltip
// + navigation prev/next/skip. Persisté dans localStorage `ae_onboarding_done`.

const { useState: _onbS, useEffect: _onbE, useMemo: _onbM, useRef: _onbR } = React;

const STEPS = [
  {
    id: 'welcome',
    title: '👋 Bienvenue sur Audits Énergies',
    body: 'Votre cockpit CEE complet : visites IA, dossiers, devis, facturation, signatures, IA agent — tout dans une interface unifiée.\n\nLaissez-nous vous faire visiter (~ 60 secondes).',
    target: null,
    placement: 'center',
  },
  {
    id: 'sidebar',
    title: '📂 Navigation latérale',
    body: 'Tous vos modules sont accessibles depuis cette barre. Cliquez sur le bouton de rétractation pour gagner de la place.',
    target: 'aside',
    placement: 'right',
  },
  {
    id: 'crm',
    title: '👥 CRM Clients',
    body: 'Gérez vos contacts Odoo + Discovery natifs. Sync auto, import depuis emails, fiche client 360° avec tous les liens (visites, études, devis…).',
    target: '[data-onb="nav-crm"]',
    placement: 'right',
  },
  {
    id: 'visites',
    title: '🎥 Visites Techniques IA',
    body: 'Capturez vidéo + audio terrain. Le pipeline IA détecte automatiquement les équipements (PAC, ballons, chaudières), lit les plaques signalétiques et suggère les FOST applicables.',
    target: '[data-onb="nav-visites"]',
    placement: 'right',
  },
  {
    id: 'dossiers',
    title: '📁 Dossiers CEE',
    body: 'Suivez le cycle de vie de vos dossiers en Kanban. Chaque dossier génère automatiquement son AH (attestation honneur PDF), sa fiche FOST et peut être déposé en EMMY XML.',
    target: '[data-onb="nav-dossiers"]',
    placement: 'right',
  },
  {
    id: 'chatbot',
    title: '🤖 Assistant IA',
    body: 'Cliquez sur la bulle en bas à droite pour poser vos questions à Claude : calculs FOST, navigation, conseils workflow. Il connaît votre contexte module.',
    target: null,
    placement: 'bottom-right',
  },
  {
    id: 'settings',
    title: '⚙️ Personnalisation',
    body: 'Configurez vos défauts par module : stages CRM, templates email, catalogues solaire, FOST favoris. Tout est persisté côté backend, partagé entre vos appareils.',
    target: '[data-onb="nav-settings"]',
    placement: 'right',
  },
  {
    id: 'done',
    title: '✓ Vous êtes prêt !',
    body: 'Vous pouvez relancer ce tour à tout moment depuis votre menu utilisateur (avatar en haut à droite > "Refaire le tour").\n\nBon usage 🚀',
    target: null,
    placement: 'center',
  },
];

const STORAGE_KEY = 'ae_onboarding_done';

function isOnboardingDone() {
  try { return localStorage.getItem(STORAGE_KEY) === '1'; } catch (_) { return false; }
}
function markOnboardingDone() {
  try { localStorage.setItem(STORAGE_KEY, '1'); } catch (_) {}
}
function resetOnboarding() {
  try { localStorage.removeItem(STORAGE_KEY); } catch (_) {}
}
window.AE_RESTART_ONBOARDING = () => {
  resetOnboarding();
  window.dispatchEvent(new CustomEvent('ae:start-onboarding'));
};

function OnboardingTour() {
  const [active, setActive] = _onbS(false);
  const [step, setStep] = _onbS(0);
  const [targetRect, setTargetRect] = _onbS(null);

  // Auto-start si first-login (et user authentifié)
  _onbE(() => {
    const onUser = () => {
      if (!isOnboardingDone()) {
        // Délai pour que l'UI soit montée
        setTimeout(() => setActive(true), 1500);
      }
    };
    const onRestart = () => { setStep(0); setActive(true); };
    window.addEventListener('ae:user-changed', onUser);
    window.addEventListener('ae:start-onboarding', onRestart);
    // Si déjà loggué au montage du widget
    if (window.ME && window.ME.id && !isOnboardingDone()) {
      setTimeout(() => setActive(true), 1500);
    }
    return () => {
      window.removeEventListener('ae:user-changed', onUser);
      window.removeEventListener('ae:start-onboarding', onRestart);
    };
  }, []);

  // Calcule la position du target à chaque step
  _onbE(() => {
    if (!active) return;
    const s = STEPS[step];
    if (!s.target) { setTargetRect(null); return; }
    const el = document.querySelector(s.target);
    if (!el) { setTargetRect(null); return; }
    const rect = el.getBoundingClientRect();
    setTargetRect({ top: rect.top, left: rect.left, width: rect.width, height: rect.height });
    // Scroll si nécessaire
    el.scrollIntoView({ behavior: 'smooth', block: 'center', inline: 'center' });
  }, [active, step]);

  if (!active) return null;
  const s = STEPS[step];
  const isLast = step === STEPS.length - 1;

  const finish = (skipped) => {
    setActive(false);
    setStep(0);
    markOnboardingDone();
    if (window.toast && !skipped) window.toast.success('Tour terminé — bon usage !');
  };

  return (
    <>
      {/* Overlay backdrop */}
      <div style={{
        position: 'fixed', inset: 0, zIndex: 99980,
        background: 'rgba(14,16,16,0.55)', backdropFilter: 'blur(2px)',
        pointerEvents: 'auto',
      }} onClick={() => finish(true)} />

      {/* Highlight cutout */}
      {targetRect && (
        <div style={{
          position: 'fixed', zIndex: 99981, pointerEvents: 'none',
          top: targetRect.top - 6, left: targetRect.left - 6,
          width: targetRect.width + 12, height: targetRect.height + 12,
          borderRadius: 8, border: '3px solid var(--signal)',
          boxShadow: '0 0 0 9999px rgba(14,16,16,0.55), 0 0 24px var(--signal-soft)',
          transition: 'all 300ms ease-out',
        }} />
      )}

      {/* Tooltip */}
      <div style={{
        position: 'fixed', zIndex: 99982,
        ...(s.placement === 'center' ? {
          top: '50%', left: '50%', transform: 'translate(-50%, -50%)',
        } : s.placement === 'right' && targetRect ? {
          top: Math.max(20, targetRect.top + (targetRect.height / 2) - 100),
          left: Math.min(window.innerWidth - 360 - 20, targetRect.left + targetRect.width + 20),
        } : s.placement === 'bottom-right' ? {
          bottom: 100, right: 100,
        } : {
          top: '50%', left: '50%', transform: 'translate(-50%, -50%)',
        }),
        width: 360, padding: 20,
        background: 'var(--paper)', border: '1px solid var(--line-2)',
        borderRadius: 12, boxShadow: 'var(--shadow-3)',
        animation: 'fade-up 280ms cubic-bezier(.2,.8,.2,1) both',
      }}>
        {/* Progress dots */}
        <div style={{ display: 'flex', gap: 4, marginBottom: 14 }}>
          {STEPS.map((_, i) => (
            <div key={i} style={{
              width: i === step ? 18 : 6, height: 6, borderRadius: 3,
              background: i <= step ? 'var(--signal)' : 'var(--paper-3)',
              transition: 'all 200ms',
            }} />
          ))}
        </div>

        <div style={{ fontSize: 16, fontWeight: 700, marginBottom: 8 }}>{s.title}</div>
        <div style={{ fontSize: 13, color: 'var(--ink-3)', lineHeight: 1.6, marginBottom: 18, whiteSpace: 'pre-wrap' }}>{s.body}</div>

        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <button onClick={() => finish(true)} style={{
            fontSize: 11, color: 'var(--ink-4)', padding: '4px 8px',
            background: 'transparent', border: 'none', cursor: 'pointer',
          }}>Passer</button>
          <span style={{ flex: 1 }} />
          <span style={{ fontSize: 11, color: 'var(--ink-4)' }}>{step + 1} / {STEPS.length}</span>
          {step > 0 && (
            <button onClick={() => setStep(s => s - 1)} style={{
              padding: '6px 12px', fontSize: 12,
              background: 'var(--paper-2)', border: '1px solid var(--line-2)',
              borderRadius: 5, cursor: 'pointer',
            }}>← Précédent</button>
          )}
          <button onClick={() => isLast ? finish(false) : setStep(s => s + 1)} style={{
            padding: '6px 14px', fontSize: 12, fontWeight: 600,
            background: 'var(--ink)', color: 'var(--paper)', border: 'none',
            borderRadius: 5, cursor: 'pointer',
          }}>{isLast ? 'Terminer' : 'Suivant →'}</button>
        </div>
      </div>
    </>
  );
}

window.OnboardingTour = OnboardingTour;
