// DossierSuccessPage — Route #/dossier/success?session_id=...&dossier_id=...
// Post-paiement Stripe : poll le statut du dossier via SSE, puis lien vers le rapport HTML
// PR B — UI Dossier IA

(function () {
  'use strict';

  const { useState, useEffect, useRef } = React;

  const API_BASE = (window.VESTORA_CONFIG?.apiBase || '') + '/api/v1';

  async function _getAuthToken() {
    if (window.vestora && window.vestora.auth && typeof window.vestora.auth.getToken === 'function') {
      return window.vestora.auth.getToken();
    }
    return sessionStorage.getItem('vestora_token') || localStorage.getItem('vestora_token') || null;
  }

  async function _apiGet(path) {
    const token = await _getAuthToken();
    const headers = {};
    if (token) headers['Authorization'] = 'Bearer ' + token;
    const resp = await fetch(API_BASE + path, { headers });
    const data = await resp.json().catch(function () { return {}; });
    if (!resp.ok) {
      const msg = data.detail || data.message || 'Erreur ' + resp.status;
      const err = new Error(msg);
      err.status = resp.status;
      throw err;
    }
    return data;
  }

  // ---- Composant spinner ----
  function Spinner({ size }) {
    var s = size || 24;
    return (
      <span style={{
        display: 'inline-block', width: s, height: s,
        border: '3px solid var(--line)', borderTopColor: 'var(--accent)',
        borderRadius: '50%', animation: 'spin 0.7s linear infinite',
        flexShrink: 0,
      }}/>
    );
  }

  // ---- Barre de progression textuelle ----
  var PROGRESS_STEPS = [
    { label: 'Collecte des données du bien', icon: '📊' },
    { label: 'Analyse du marché local', icon: '🏙️' },
    { label: 'Calculs financiers', icon: '🔢' },
    { label: 'Rédaction de l\'analyse IA', icon: '🤖' },
    { label: 'Mise en forme du rapport', icon: '📄' },
  ];

  function ProgressSteps({ currentStep }) {
    return (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginBottom: 32 }}>
        {PROGRESS_STEPS.map(function (step, i) {
          var isDone = i < currentStep;
          var isActive = i === currentStep;
          return (
            <div
              key={i}
              style={{
                display: 'flex', alignItems: 'center', gap: 12,
                padding: '10px 14px',
                borderRadius: 8,
                background: isDone ? 'oklch(0.96 0.04 150)' : isActive ? 'oklch(0.96 0.04 250)' : 'var(--bg-warm)',
                border: '1px solid ' + (isDone ? 'oklch(0.88 0.06 150)' : isActive ? 'oklch(0.88 0.06 250)' : 'var(--line)'),
                transition: 'all 0.3s',
              }}
            >
              <div style={{ width: 28, textAlign: 'center', fontSize: 14 }}>
                {isDone ? '✅' : isActive ? <Spinner size={16}/> : step.icon}
              </div>
              <span style={{
                fontSize: 13, fontWeight: isActive ? 600 : 400,
                color: isDone ? 'oklch(0.32 0.10 145)' : isActive ? 'oklch(0.35 0.10 250)' : 'var(--ink-3)',
              }}>
                {step.label}
              </span>
            </div>
          );
        })}
      </div>
    );
  }

  // ---- Page principale ----
  function DossierSuccessPage({ lang, onBack }) {
    // Extraire les paramètres de l'URL
    var params = new URLSearchParams(window.location.hash.split('?')[1] || '');
    var sessionId = params.get('session_id');
    var dossierId = params.get('dossier_id');

    var [status, setStatus] = useState('pending'); // pending | generating | ready | failed | timeout
    var [pdfUrl, setPdfUrl] = useState(null);
    var [currentStep, setCurrentStep] = useState(0);
    var [error, setError] = useState(null);
    var [elapsed, setElapsed] = useState(0);
    var pollRef = useRef(null);
    var sseRef = useRef(null);
    var startedRef = useRef(false);

    // Trouver le dossier_id via le session_id si non fourni directement
    var resolvedDossierIdRef = useRef(dossierId);

    useEffect(function () {
      if (startedRef.current) return;
      startedRef.current = true;

      // Tracking analytics — paiement confirmé
      if (window.vestora && window.vestora.analytics) {
        window.vestora.analytics.track('Purchase', {
          value: 49,
          currency: 'CAD',
          content_name: 'dossier_ia',
        });
      }

      // Si on a un dossier_id direct → démarrer SSE
      if (dossierId) {
        resolvedDossierIdRef.current = dossierId;
        startSSE(dossierId);
        return;
      }

      // Sinon : chercher via session_id en pollinig GET /dossiers
      if (sessionId) {
        findDossierBySession(sessionId);
        return;
      }

      // Ni l'un ni l'autre → erreur
      setStatus('failed');
      setError('Paramètres manquants dans l\'URL. Consultez votre espace Mes dossiers.');
    }, []);

    async function findDossierBySession(sid) {
      // Poll GET /dossiers pour trouver le dossier correspondant à cette session Stripe
      var maxAttempts = 10;
      var attempt = 0;

      async function poll() {
        if (attempt >= maxAttempts) {
          setStatus('failed');
          setError('Dossier introuvable. Patientez quelques secondes et consultez Mes dossiers.');
          return;
        }
        attempt++;
        try {
          var data = await _apiGet('/dossiers?page=1&page_size=20');
          var items = data.items || [];
          // Chercher le dossier avec la session Stripe correspondante
          // (Le dossier récent en tête de liste, si pas de stripe_session_id dans DossierSummary, prendre le plus récent)
          if (items.length > 0) {
            var found = items[0]; // Le plus récent
            resolvedDossierIdRef.current = found.id;
            if (found.status === 'ready') {
              setStatus('ready');
              setPdfUrl(found.pdf_url);
              return;
            }
            if (found.status === 'failed') {
              setStatus('failed');
              setError('La génération a échoué. Contactez support@vestora.ca.');
              return;
            }
            // En cours → démarrer SSE
            startSSE(found.id);
            return;
          }
        } catch (e) {
          // Continue
        }
        setTimeout(poll, 2000);
      }

      setStatus('generating');
      poll();
    }

    async function startSSE(did) {
      setStatus('generating');
      var token = await _getAuthToken();
      var url = API_BASE + '/dossiers/' + did + '/stream';
      if (token) url += '?token=' + encodeURIComponent(token);

      var headers = {};
      if (token) headers['Authorization'] = 'Bearer ' + token;

      // Utiliser EventSource (SSE natif)
      // Note: EventSource ne supporte pas les headers custom — on passe le token en query param
      // ou on utilise fetch + ReadableStream si le backend est configuré pour.
      // Tentative 1 : EventSource direct
      try {
        var evtSource = new EventSource(url);
        sseRef.current = evtSource;

        evtSource.addEventListener('heartbeat', function (e) {
          try {
            var d = JSON.parse(e.data);
            setElapsed(d.elapsed || 0);
            // Avancer les étapes de progression visuelle
            setCurrentStep(function (prev) {
              var next = Math.min(PROGRESS_STEPS.length - 1, Math.floor((d.elapsed || 0) / 20));
              return Math.max(prev, next);
            });
          } catch (_) {}
        });

        evtSource.addEventListener('status', function (e) {
          try {
            var d = JSON.parse(e.data);
            if (d.status === 'ready') {
              setStatus('ready');
              setCurrentStep(PROGRESS_STEPS.length);
              if (d.pdf_url) setPdfUrl(d.pdf_url);
              evtSource.close();
            } else if (d.status === 'failed') {
              setStatus('failed');
              setError(d.error || 'La génération a échoué.');
              evtSource.close();
            } else if (d.status === 'timeout') {
              setStatus('timeout');
              evtSource.close();
            }
          } catch (_) {}
        });

        evtSource.addEventListener('done', function () {
          evtSource.close();
        });

        evtSource.onerror = function () {
          evtSource.close();
          // Fallback : polling simple
          startPolling(did);
        };
      } catch (_) {
        // EventSource non disponible → polling
        startPolling(did);
      }
    }

    function startPolling(did) {
      var maxAttempts = 90; // 90 * 3s = 4.5 min
      var attempt = 0;

      async function poll() {
        if (attempt >= maxAttempts) {
          setStatus('timeout');
          return;
        }
        attempt++;
        try {
          var data = await _apiGet('/dossiers/' + did);
          setElapsed(attempt * 3);
          setCurrentStep(function (prev) {
            return Math.max(prev, Math.min(PROGRESS_STEPS.length - 1, Math.floor(attempt / 8)));
          });

          if (data.status === 'ready') {
            setStatus('ready');
            setCurrentStep(PROGRESS_STEPS.length);
            setPdfUrl(data.pdf_url);
            return;
          }
          if (data.status === 'failed') {
            setStatus('failed');
            setError(data.error_message || 'La génération a échoué.');
            return;
          }
        } catch (e) {
          if (e.status === 404) {
            setStatus('failed');
            setError('Dossier introuvable. Consultez Mes dossiers.');
            return;
          }
        }
        pollRef.current = setTimeout(poll, 3000);
      }

      setStatus('generating');
      poll();
    }

    useEffect(function () {
      return function () {
        if (pollRef.current) clearTimeout(pollRef.current);
        if (sseRef.current) sseRef.current.close();
      };
    }, []);

    var content;

    if (status === 'pending' || status === 'generating') {
      content = (
        <div style={{ textAlign: 'center' }}>
          <div style={{ fontSize: 48, marginBottom: 20 }}>🤖</div>
          <h2 style={{
            fontFamily: 'var(--serif, Fraunces, serif)',
            fontSize: 24, fontWeight: 500, color: 'var(--ink-1)',
            margin: '0 0 12px', letterSpacing: '-0.01em',
          }}>
            Votre dossier est en cours de génération
          </h2>
          <p style={{ fontSize: 14, color: 'var(--ink-3)', margin: '0 0 32px', lineHeight: 1.6 }}>
            L'IA analyse ce bien en profondeur. Cela prend généralement 1 à 3 minutes.
            {elapsed > 0 && (
              <span style={{ display: 'block', marginTop: 4, fontSize: 12, color: 'var(--ink-4)' }}>
                Temps écoulé : {elapsed}s
              </span>
            )}
          </p>
          <ProgressSteps currentStep={currentStep} />
          <p style={{ fontSize: 13, color: 'var(--ink-4)', margin: 0 }}>
            Ne fermez pas cette page. Vous pouvez aussi consulter{' '}
            <a
              href="#/mes-dossiers"
              style={{ color: 'var(--accent-ink, oklch(0.36 0.07 155))', textDecoration: 'none' }}
            >
              Mes dossiers
            </a>
            {' '}pour revenir plus tard.
          </p>
        </div>
      );
    } else if (status === 'ready') {
      content = (
        <div style={{ textAlign: 'center' }}>
          <div style={{ fontSize: 56, marginBottom: 20 }}>🎉</div>
          <h2 style={{
            fontFamily: 'var(--serif, Fraunces, serif)',
            fontSize: 28, fontWeight: 500, color: 'var(--ink-1)',
            margin: '0 0 12px', letterSpacing: '-0.01em',
          }}>
            Votre dossier est prêt !
          </h2>
          <p style={{ fontSize: 15, color: 'var(--ink-2)', margin: '0 0 32px', lineHeight: 1.6 }}>
            L'analyse IA complète de ce bien est disponible.
          </p>

          <div style={{ display: 'flex', justifyContent: 'center', gap: 12, flexWrap: 'wrap', marginBottom: 24 }}>
            {pdfUrl ? (
              <a
                href={pdfUrl}
                target="_blank"
                rel="noopener noreferrer"
                style={{
                  display: 'inline-flex', alignItems: 'center', gap: 8,
                  padding: '13px 24px', borderRadius: 'var(--radius, 8px)',
                  background: 'var(--accent, oklch(0.36 0.07 155))',
                  color: '#fff', textDecoration: 'none',
                  fontSize: 15, fontWeight: 700, fontFamily: 'inherit',
                  boxShadow: 'var(--shadow-lg)',
                }}
              >
                <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.8">
                  <path d="M4 2h6l4 4v8a1 1 0 01-1 1H3a1 1 0 01-1-1V3a1 1 0 011-1z"/>
                  <path d="M10 2v4h4M6 10l2 2 2-2M8 7v5"/>
                </svg>
                Voir le rapport HTML
              </a>
            ) : resolvedDossierIdRef.current ? (
              <a
                href={'#/dossier/view/' + resolvedDossierIdRef.current}
                style={{
                  display: 'inline-flex', alignItems: 'center', gap: 8,
                  padding: '13px 24px', borderRadius: 'var(--radius, 8px)',
                  background: 'var(--accent, oklch(0.36 0.07 155))',
                  color: '#fff', textDecoration: 'none',
                  fontSize: 15, fontWeight: 700, fontFamily: 'inherit',
                }}
              >
                Voir le rapport
              </a>
            ) : null}

            <a
              href="#/mes-dossiers"
              style={{
                display: 'inline-flex', alignItems: 'center', gap: 8,
                padding: '13px 24px', borderRadius: 'var(--radius, 8px)',
                border: '1.5px solid var(--line)', background: 'var(--bg-elev)',
                color: 'var(--ink-1)', textDecoration: 'none',
                fontSize: 15, fontWeight: 600, fontFamily: 'inherit',
              }}
            >
              Mes dossiers
            </a>
          </div>

          <p style={{ fontSize: 13, color: 'var(--ink-4)', margin: 0 }}>
            Le rapport restera accessible dans{' '}
            <a href="#/mes-dossiers" style={{ color: 'var(--accent-ink)' }}>Mes dossiers</a>.
          </p>
        </div>
      );
    } else if (status === 'failed') {
      content = (
        <div style={{ textAlign: 'center' }}>
          <div style={{ fontSize: 48, marginBottom: 20 }}>❌</div>
          <h2 style={{
            fontFamily: 'var(--serif, Fraunces, serif)',
            fontSize: 24, fontWeight: 500, color: 'var(--ink-1)',
            margin: '0 0 12px',
          }}>
            La génération a échoué
          </h2>
          <p style={{ fontSize: 14, color: 'var(--ink-3)', margin: '0 0 24px', lineHeight: 1.6 }}>
            {error || 'Une erreur est survenue lors de la génération de votre dossier.'}
          </p>
          <div style={{ display: 'flex', justifyContent: 'center', gap: 12, flexWrap: 'wrap' }}>
            <a
              href="mailto:support@vestora.ca?subject=Dossier IA — demande de remboursement"
              style={{
                padding: '10px 20px', background: 'var(--accent)',
                color: '#fff', textDecoration: 'none',
                borderRadius: 8, fontSize: 14, fontWeight: 600, fontFamily: 'inherit',
              }}
            >
              Contacter le support
            </a>
            <a
              href="#/mes-dossiers"
              style={{
                padding: '10px 20px', background: 'var(--bg-elev)',
                border: '1.5px solid var(--line)', color: 'var(--ink-1)',
                textDecoration: 'none', borderRadius: 8, fontSize: 14, fontWeight: 600, fontFamily: 'inherit',
              }}
            >
              Mes dossiers
            </a>
          </div>
        </div>
      );
    } else if (status === 'timeout') {
      content = (
        <div style={{ textAlign: 'center' }}>
          <div style={{ fontSize: 48, marginBottom: 20 }}>⏱️</div>
          <h2 style={{
            fontFamily: 'var(--serif, Fraunces, serif)',
            fontSize: 24, fontWeight: 500, color: 'var(--ink-1)',
            margin: '0 0 12px',
          }}>
            Génération en cours
          </h2>
          <p style={{ fontSize: 14, color: 'var(--ink-3)', margin: '0 0 24px', lineHeight: 1.6 }}>
            La génération prend plus de temps que prévu. Consultez{' '}
            <a href="#/mes-dossiers" style={{ color: 'var(--accent-ink)' }}>Mes dossiers</a>
            {' '}dans quelques minutes.
          </p>
          <a
            href="#/mes-dossiers"
            style={{
              padding: '10px 24px', background: 'var(--accent)',
              color: '#fff', textDecoration: 'none',
              borderRadius: 8, fontSize: 14, fontWeight: 600, fontFamily: 'inherit',
              display: 'inline-block',
            }}
          >
            Aller à Mes dossiers
          </a>
        </div>
      );
    }

    return (
      <div style={{
        minHeight: '100vh',
        background: 'var(--bg, #f7f7f4)',
        fontFamily: 'var(--sans, Inter, sans-serif)',
      }}>
        {/* Header */}
        <div style={{
          position: 'sticky', top: 0, zIndex: 40,
          borderBottom: '1px solid var(--line)',
          background: 'var(--bg-elev, #fff)',
          padding: '0 24px', height: 56,
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        }}>
          <div style={{ width: 60 }} />
          <span style={{ fontWeight: 600, fontSize: 15, color: 'var(--ink-1)', letterSpacing: '-0.01em' }}>
            Vestora
          </span>
          <div style={{ width: 60 }} />
        </div>

        <div style={{
          maxWidth: 560, margin: '0 auto',
          padding: '80px 24px 80px',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          minHeight: 'calc(100vh - 56px)',
        }}>
          <div style={{ width: '100%' }}>
            {content}
          </div>
        </div>

        <style>{`
          @keyframes spin {
            from { transform: rotate(0deg); }
            to { transform: rotate(360deg); }
          }
        `}</style>
      </div>
    );
  }

  window.DossierSuccessPage = DossierSuccessPage;
})();
