// BrokerOnboardingChecklist.jsx — Funnel d'activation courtier (Vague 1 PR-1.2)
//
// Objectif : amener le courtier à sa première valeur (une fiche PDF brandée
// envoyable à un client) en moins de 10 minutes.
//
// La checklist reflète l'ÉTAT RÉEL, elle n'est pas décorative :
//   1. Profil courtier configuré  -> GET /broker/profile (display_name rempli)
//   2. Première annonce analysée  -> historique localStorage vestora_broker_recent
//   3. Première fiche PDF générée -> une entrée d'historique porte un pdfUrl
//
// L'ordre n'est pas arbitraire : sans profil courtier, POST /broker/fiche
// renvoie 400 ("Configurez votre profil courtier d'abord"). L'étape 1 est donc
// un vrai prérequis technique, pas du confort.
//
// Se masque automatiquement quand les 3 étapes sont faites (et retient l'état),
// ou si le courtier ferme la bannière.
//
// Convention Vestora : React global, exposé sur window.BrokerOnboardingChecklist.

(function () {
  const React = window.React;
  if (!React) return;
  const { useState, useEffect } = React;

  const RECENT_KEY = 'vestora_broker_recent';
  const DISMISS_KEY = 'vestora_broker_onboarding_done';

  function readRecents() {
    try {
      const parsed = JSON.parse(localStorage.getItem(RECENT_KEY));
      return Array.isArray(parsed) ? parsed : [];
    } catch (_) {
      return [];
    }
  }

  function BrokerOnboardingChecklist({ lang, activeTab, onGoTab }) {
    const FR = lang !== 'en';

    const [dismissed, setDismissed] = useState(() => {
      try { return localStorage.getItem(DISMISS_KEY) === '1'; } catch (_) { return false; }
    });
    // null = profil en cours de chargement (on n'affiche rien tant qu'on ne sait pas)
    const [profileDone, setProfileDone] = useState(null);
    const [recents, setRecents] = useState(() => readRecents());

    // Profil courtier — source de vérité côté API (404 = pas encore de profil).
    useEffect(() => {
      let cancelled = false;
      const api = window.vestora && window.vestora.brokerApi;
      if (!api || typeof api.getProfile !== 'function') {
        setProfileDone(false);
        return;
      }
      api.getProfile().then(res => {
        if (cancelled) return;
        const name = res && res.ok && res.data && res.data.displayName;
        setProfileDone(!!(name && String(name).trim()));
      }).catch(() => { if (!cancelled) setProfileDone(false); });
      return () => { cancelled = true; };
    }, []);

    // Les étapes 2 et 3 vivent dans le localStorage : on re-lit à chaque
    // changement d'onglet (le courtier revient de « Analyse rapide »).
    useEffect(() => { setRecents(readRecents()); }, [activeTab]);

    const analysisDone = recents.length > 0;
    const ficheDone = recents.some(r => r && r.pdfUrl);
    const allDone = profileDone === true && analysisDone && ficheDone;

    // Une fois les 3 étapes faites, on retient et on ne réaffiche plus.
    useEffect(() => {
      if (allDone && !dismissed) {
        try { localStorage.setItem(DISMISS_KEY, '1'); } catch (_) {}
        setDismissed(true);
      }
    }, [allDone, dismissed]);

    if (dismissed || profileDone === null || allDone) return null;

    const close = () => {
      try { localStorage.setItem(DISMISS_KEY, '1'); } catch (_) {}
      setDismissed(true);
    };

    const steps = [
      {
        done: profileDone === true,
        label: FR ? 'Configure ton branding' : 'Set up your branding',
        hint: FR ? 'Logo, n° OACIQ, couleur — requis pour générer une fiche.'
                 : 'Logo, OACIQ number, color — required to generate a PDF.',
        cta: FR ? 'Ouvrir mon profil' : 'Open my profile',
        act: () => { window.location.hash = '#/courtier/profil'; },
      },
      {
        done: analysisDone,
        label: FR ? 'Analyse ta première annonce' : 'Analyze your first listing',
        hint: FR ? "Colle l'URL d'une annonce dans « Analyse rapide »."
                 : 'Paste a listing URL into "Quick analysis".',
        cta: FR ? 'Analyse rapide' : 'Quick analysis',
        act: () => { if (onGoTab) onGoTab('rapide'); },
      },
      {
        done: ficheDone,
        label: FR ? 'Génère ta première fiche brandée' : 'Generate your first branded PDF',
        hint: FR ? 'Un PDF à ton nom, prêt à envoyer à ton client.'
                 : 'A PDF in your name, ready to send to your client.',
        cta: FR ? 'Générer' : 'Generate',
        act: () => { if (onGoTab) onGoTab('rapide'); },
      },
    ];

    const doneCount = steps.filter(s => s.done).length;
    // Première étape non faite = celle qu'on met en avant.
    const currentIdx = steps.findIndex(s => !s.done);

    const wrap = {
      border: '1.5px solid #c7d2fe',
      borderRadius: 12,
      background: 'linear-gradient(135deg, #f5f7ff, #ffffff)',
      padding: '18px 20px',
      marginBottom: 20,
      position: 'relative',
    };
    const closeBtn = {
      position: 'absolute', top: 10, right: 12,
      background: 'none', border: 'none', cursor: 'pointer',
      color: '#9ca3af', fontSize: '1.05rem', lineHeight: 1, padding: 2,
    };
    const title = { fontWeight: 700, fontSize: '1rem', color: '#1a1a2e', marginBottom: 2 };
    const sub = { fontSize: '0.82rem', color: '#6b7280', marginBottom: 14 };
    const row = (isCurrent) => ({
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '9px 10px', borderRadius: 8, marginBottom: 6,
      background: isCurrent ? '#eef2ff' : 'transparent',
      border: isCurrent ? '1px solid #c7d2fe' : '1px solid transparent',
      flexWrap: 'wrap',
    });
    const bullet = (done) => ({
      width: 22, height: 22, borderRadius: '50%', flexShrink: 0,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontSize: '0.75rem', fontWeight: 700,
      background: done ? '#059669' : '#e5e7eb',
      color: done ? '#fff' : '#6b7280',
    });
    const stepLabel = (done) => ({
      fontWeight: 600, fontSize: '0.9rem',
      color: done ? '#6b7280' : '#1a1a2e',
      textDecoration: done ? 'line-through' : 'none',
    });
    const stepHint = { fontSize: '0.78rem', color: '#6b7280' };
    const ctaBtn = {
      marginLeft: 'auto', padding: '7px 14px',
      background: '#4f46e5', color: '#fff', border: 'none',
      borderRadius: 6, fontSize: '0.82rem', fontWeight: 700,
      cursor: 'pointer', whiteSpace: 'nowrap',
    };

    return (
      <div style={wrap} role="region" aria-label={FR ? 'Démarrage courtier' : 'Broker onboarding'}>
        <button style={closeBtn} onClick={close}
                aria-label={FR ? 'Masquer' : 'Dismiss'} title={FR ? 'Masquer' : 'Dismiss'}>✕</button>
        <div style={title}>
          {FR ? 'Ta première fiche brandée en 3 étapes' : 'Your first branded PDF in 3 steps'}
        </div>
        <div style={sub}>
          {FR ? `${doneCount}/3 — moins de 10 minutes.` : `${doneCount}/3 — under 10 minutes.`}
        </div>

        {steps.map((s, i) => (
          <div key={i} style={row(i === currentIdx)}>
            <span style={bullet(s.done)} aria-hidden="true">{s.done ? '✓' : (i + 1)}</span>
            <span style={{ minWidth: 180, flex: 1 }}>
              <span style={stepLabel(s.done)}>{s.label}</span>
              {!s.done && <div style={stepHint}>{s.hint}</div>}
            </span>
            {i === currentIdx && (
              <button style={ctaBtn} onClick={s.act}>{s.cta}</button>
            )}
          </div>
        ))}
      </div>
    );
  }

  window.BrokerOnboardingChecklist = BrokerOnboardingChecklist;
})();
