// DossierPage — Route #/mes-dossiers
// Liste les dossiers IA de l'utilisateur connecté avec statut + lien vers le rendu HTML
// PR B — UI Dossier IA

(function () {
  'use strict';

  const { useState, useEffect, useCallback } = 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;
  }

  // Libellés statuts
  const STATUS_CONFIG = {
    pending_payment: { label: 'En attente de paiement', color: 'oklch(0.55 0.10 60)', bg: 'oklch(0.97 0.04 60)', icon: '⏳' },
    paid:            { label: 'Paiement confirmé', color: 'oklch(0.42 0.13 150)', bg: 'oklch(0.96 0.04 150)', icon: '✅' },
    generating:      { label: 'En génération…', color: 'oklch(0.45 0.10 250)', bg: 'oklch(0.96 0.04 250)', icon: '🤖' },
    ready:           { label: 'Prêt', color: 'oklch(0.32 0.10 145)', bg: 'oklch(0.95 0.06 145)', icon: '✅' },
    failed:          { label: 'Échec', color: 'oklch(0.35 0.12 25)', bg: 'oklch(0.97 0.03 25)', icon: '❌' },
    refunded:        { label: 'Remboursé', color: 'var(--ink-3)', bg: 'var(--bg-warm)', icon: '↩️' },
  };

  // Libellés stratégies
  const STRATEGY_LABELS = {
    buy_and_hold:       'Achat & conservation',
    value_add:          'Valeur ajoutée',
    brrrr:              'BRRRR',
    flip:               'Revente rapide',
    short_term_rental:  'Location courte durée',
    custom:             'Stratégie personnalisée',
  };

  function StatusBadge({ status }) {
    const cfg = STATUS_CONFIG[status] || { label: status, color: 'var(--ink-3)', bg: 'var(--bg-warm)', icon: '?' };
    return (
      <span style={{
        display: 'inline-flex', alignItems: 'center', gap: 5,
        padding: '3px 10px', borderRadius: 20,
        fontSize: 12, fontWeight: 600,
        background: cfg.bg, color: cfg.color,
      }}>
        <span>{cfg.icon}</span>
        {cfg.label}
      </span>
    );
  }

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

  function DossierCard({ dossier, onRefresh }) {
    const fmtDate = (d) => {
      if (!d) return '—';
      try {
        return new Date(d).toLocaleDateString('fr-CA', { day: 'numeric', month: 'short', year: 'numeric' });
      } catch { return d; }
    };

    const strategyLabel = STRATEGY_LABELS[dossier.strategy] || dossier.strategy;
    const isGenerating = dossier.status === 'generating' || dossier.status === 'paid';
    const isReady = dossier.status === 'ready';
    const isFailed = dossier.status === 'failed';

    return (
      <div style={{
        background: 'var(--bg-elev, #fff)',
        border: '1px solid var(--line, #e8e8e0)',
        borderRadius: 'var(--radius-lg, 12px)',
        padding: '20px 24px',
        display: 'flex', flexDirection: 'column', gap: 12,
      }}>
        {/* En-tête */}
        <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 12 }}>
          <div style={{ minWidth: 0 }}>
            <div style={{ fontSize: 13, color: 'var(--ink-3)', marginBottom: 2 }}>
              Listing #{dossier.listing_id}
            </div>
            <div style={{ fontWeight: 600, fontSize: 15, color: 'var(--ink-1)', marginBottom: 4 }}>
              {strategyLabel}
            </div>
          </div>
          <StatusBadge status={dossier.status} />
        </div>

        {/* Meta */}
        <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap' }}>
          <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>
            Créé le {fmtDate(dossier.created_at)}
          </div>
          {dossier.generated_at && (
            <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>
              Généré le {fmtDate(dossier.generated_at)}
            </div>
          )}
          <div style={{ fontSize: 12, color: 'var(--ink-4)', fontFamily: 'var(--mono)' }}>
            v{dossier.prompt_version}
          </div>
        </div>

        {/* En génération */}
        {isGenerating && (
          <div style={{
            display: 'flex', alignItems: 'center', gap: 10,
            background: 'oklch(0.96 0.04 250)', borderRadius: 8, padding: '10px 14px',
            fontSize: 13, color: 'oklch(0.35 0.10 250)',
          }}>
            <SpinnerIcon />
            L'IA analyse ce bien. Le rapport sera prêt dans quelques minutes.
            <button
              onClick={onRefresh}
              style={{
                marginLeft: 'auto', background: 'none', border: 'none',
                cursor: 'pointer', fontSize: 12, color: 'oklch(0.45 0.10 250)',
                fontFamily: 'inherit', textDecoration: 'underline', padding: 0,
              }}
            >
              Actualiser
            </button>
          </div>
        )}

        {/* Prêt — lien vers rapport HTML */}
        {isReady && dossier.pdf_url && (
          <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
            <a
              href={dossier.pdf_url}
              target="_blank"
              rel="noopener noreferrer"
              style={{
                display: 'inline-flex', alignItems: 'center', gap: 6,
                padding: '9px 16px', borderRadius: 'var(--radius, 8px)',
                background: 'var(--accent, oklch(0.36 0.07 155))',
                color: '#fff', textDecoration: 'none',
                fontSize: 13, fontWeight: 600, fontFamily: 'inherit',
              }}
            >
              <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.5">
                <path d="M7 1v8M4 6l3 3 3-3M2 11h10"/>
              </svg>
              Voir le rapport HTML
            </a>
          </div>
        )}

        {/* Prêt mais pas encore de pdf_url (rapport HTML via /dossiers/{id}) */}
        {isReady && !dossier.pdf_url && (
          <div style={{ display: 'flex', gap: 10 }}>
            <a
              href={'#/dossier/success?dossier_id=' + dossier.id}
              style={{
                display: 'inline-flex', alignItems: 'center', gap: 6,
                padding: '9px 16px', borderRadius: 'var(--radius, 8px)',
                background: 'var(--accent, oklch(0.36 0.07 155))',
                color: '#fff', textDecoration: 'none',
                fontSize: 13, fontWeight: 600, fontFamily: 'inherit',
              }}
            >
              Voir le rapport
            </a>
          </div>
        )}

        {/* Échec */}
        {isFailed && (
          <div style={{
            background: 'oklch(0.97 0.03 25)', border: '1px solid oklch(0.88 0.06 25)',
            borderRadius: 8, padding: '10px 14px',
            fontSize: 12, color: 'oklch(0.35 0.12 25)',
          }}>
            La génération a échoué. Contactez support@vestora.ca pour un remboursement.
          </div>
        )}
      </div>
    );
  }

  function DossierPage({ lang, onBack, currentUser }) {
    const [dossiers, setDossiers] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const [page, setPage] = useState(1);
    const [total, setTotal] = useState(0);
    const PAGE_SIZE = 20;

    const fetchDossiers = useCallback(async (p) => {
      setLoading(true);
      setError(null);
      try {
        const data = await _apiGet('/dossiers?page=' + p + '&page_size=' + PAGE_SIZE);
        setDossiers(data.items || []);
        setTotal(data.total || 0);
      } catch (e) {
        if (e.status === 401 || e.status === 403) {
          setError('Veuillez vous connecter pour voir vos dossiers.');
        } else if (e.status === 404) {
          // Feature désactivée
          setError('La fonctionnalité Dossier IA n\'est pas encore disponible publiquement.');
        } else {
          setError(e.message || 'Impossible de charger vos dossiers.');
        }
      } finally {
        setLoading(false);
      }
    }, []);

    useEffect(() => {
      if (!currentUser) {
        setLoading(false);
        return;
      }
      fetchDossiers(page);
    }, [currentUser, page, fetchDossiers]);

    const totalPages = Math.ceil(total / PAGE_SIZE);

    return (
      <div style={{
        minHeight: '100vh',
        background: 'var(--bg, #f7f7f4)',
        fontFamily: 'var(--sans, Inter, sans-serif)',
      }}>
        {/* Header sticky */}
        <div style={{
          position: 'sticky', top: 0, zIndex: 40,
          borderBottom: '1px solid var(--line, #e8e8e0)',
          background: 'var(--bg-elev, #fff)',
          padding: '0 24px', height: 56,
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        }}>
          <button
            onClick={onBack || (() => window.navigateTo('#/'))}
            style={{
              display: 'flex', alignItems: 'center', gap: 6,
              background: 'none', border: 'none', cursor: 'pointer',
              color: 'var(--ink-2)', fontSize: 14, fontFamily: 'inherit', padding: '4px 0',
            }}
          >
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
              <path d="M10 3L5 8l5 5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
            Retour
          </button>
          <span style={{ fontWeight: 600, fontSize: 15, color: 'var(--ink-1)', letterSpacing: '-0.01em' }}>
            Vestora
          </span>
          <div style={{ width: 60 }} />
        </div>

        <div style={{ maxWidth: 720, margin: '0 auto', padding: '40px 24px 80px' }}>

          {/* Titre */}
          <div style={{ marginBottom: 32 }}>
            <h1 style={{
              fontFamily: 'var(--serif, Fraunces, serif)', fontSize: 28, fontWeight: 500,
              color: 'var(--ink-1)', margin: '0 0 8px', letterSpacing: '-0.02em',
            }}>
              Mes dossiers IA
            </h1>
            <p style={{ fontSize: 14, color: 'var(--ink-3)', margin: 0, lineHeight: 1.6 }}>
              Retrouvez ici toutes vos analyses IA de propriétés.
            </p>
          </div>

          {/* Non connecté */}
          {!currentUser && !loading && (
            <div style={{
              background: 'var(--bg-elev, #fff)',
              border: '1px solid var(--line, #e8e8e0)',
              borderRadius: 'var(--radius-lg, 12px)',
              padding: '40px 32px', textAlign: 'center',
            }}>
              <div style={{ fontSize: 32, marginBottom: 16 }}>🔒</div>
              <div style={{ fontSize: 16, fontWeight: 600, color: 'var(--ink-1)', marginBottom: 8 }}>
                Connexion requise
              </div>
              <div style={{ fontSize: 14, color: 'var(--ink-3)', marginBottom: 20 }}>
                Connectez-vous pour accéder à vos dossiers IA.
              </div>
              <button
                onClick={() => {
                  if (window.vestora && window.vestora.auth && typeof window.vestora.auth.openModal === 'function') {
                    window.vestora.auth.openModal();
                  }
                }}
                style={{
                  padding: '10px 24px', background: 'var(--accent, oklch(0.36 0.07 155))',
                  color: '#fff', border: 'none', borderRadius: 'var(--radius, 8px)',
                  fontSize: 14, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit',
                }}
              >
                Se connecter
              </button>
            </div>
          )}

          {/* Chargement */}
          {loading && (
            <div style={{ display: 'flex', justifyContent: 'center', padding: '60px 0' }}>
              <SpinnerIcon />
            </div>
          )}

          {/* Erreur */}
          {error && !loading && (
            <div style={{
              background: 'oklch(0.97 0.03 25)', border: '1px solid oklch(0.85 0.08 25)',
              borderRadius: 12, padding: '20px 24px',
              fontSize: 14, color: 'oklch(0.35 0.12 25)',
            }}>
              {error}
            </div>
          )}

          {/* Liste vide */}
          {!loading && !error && currentUser && dossiers.length === 0 && (
            <div style={{
              background: 'var(--bg-elev, #fff)',
              border: '1px solid var(--line, #e8e8e0)',
              borderRadius: 'var(--radius-lg, 12px)',
              padding: '48px 32px', textAlign: 'center',
            }}>
              <div style={{ fontSize: 40, marginBottom: 16 }}>📄</div>
              <div style={{ fontSize: 16, fontWeight: 600, color: 'var(--ink-1)', marginBottom: 8 }}>
                Aucun dossier pour l'instant
              </div>
              <div style={{ fontSize: 14, color: 'var(--ink-3)', marginBottom: 20, lineHeight: 1.6 }}>
                Générez votre premier dossier IA directement depuis la fiche d'une propriété.
              </div>
              <button
                onClick={onBack || (() => window.navigateTo('#/'))}
                style={{
                  padding: '10px 24px', background: 'var(--accent, oklch(0.36 0.07 155))',
                  color: '#fff', border: 'none', borderRadius: 'var(--radius, 8px)',
                  fontSize: 14, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit',
                }}
              >
                Explorer les propriétés
              </button>
            </div>
          )}

          {/* Liste des dossiers */}
          {!loading && !error && dossiers.length > 0 && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
              {dossiers.map((d) => (
                <DossierCard
                  key={d.id}
                  dossier={d}
                  onRefresh={() => fetchDossiers(page)}
                />
              ))}
            </div>
          )}

          {/* Pagination */}
          {totalPages > 1 && (
            <div style={{
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 12,
              marginTop: 32,
            }}>
              <button
                onClick={() => setPage(p => Math.max(1, p - 1))}
                disabled={page === 1}
                style={{
                  padding: '8px 16px', background: 'var(--bg-elev)', border: '1px solid var(--line)',
                  borderRadius: 8, cursor: page === 1 ? 'not-allowed' : 'pointer',
                  opacity: page === 1 ? 0.45 : 1, fontFamily: 'inherit', fontSize: 13,
                }}
              >
                ← Précédent
              </button>
              <span style={{ fontSize: 13, color: 'var(--ink-3)' }}>
                Page {page} sur {totalPages}
              </span>
              <button
                onClick={() => setPage(p => Math.min(totalPages, p + 1))}
                disabled={page >= totalPages}
                style={{
                  padding: '8px 16px', background: 'var(--bg-elev)', border: '1px solid var(--line)',
                  borderRadius: 8, cursor: page >= totalPages ? 'not-allowed' : 'pointer',
                  opacity: page >= totalPages ? 0.45 : 1, fontFamily: 'inherit', fontSize: 13,
                }}
              >
                Suivant →
              </button>
            </div>
          )}
        </div>

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

  window.DossierPage = DossierPage;
})();
