// DossierModal — Sélection stratégie + Stripe Checkout one-shot 49$ CAD
// PR B — UI Dossier IA
// Feature-gated sur window.VESTORA_CONFIG.dossierAiEnabled (default false)

(function () {
  'use strict';

  const { useState, useEffect } = React;

  // Libellés humains des stratégies — alignés avec humanize_dossier côté backend
  const STRATEGIES = [
    {
      value: 'buy_and_hold',
      label: 'Achat & conservation',
      desc: 'Revenus locatifs stables à long terme, constitution de patrimoine.',
      icon: '🏠',
    },
    {
      value: 'value_add',
      label: 'Valeur ajoutée',
      desc: 'Rénovations ciblées pour augmenter les loyers et la valeur du bien.',
      icon: '🔨',
    },
    {
      value: 'brrrr',
      label: 'BRRRR',
      desc: 'Acheter, rénover, louer, refinancer, recommencer.',
      icon: '♻️',
    },
    {
      value: 'flip',
      label: 'Revente rapide',
      desc: 'Acheter sous le marché, rénover, revendre avec plus-value.',
      icon: '💰',
    },
    {
      value: 'short_term_rental',
      label: 'Location courte durée',
      desc: 'Airbnb / VRBO — revenus plus élevés, gestion plus intensive.',
      icon: '🛏️',
    },
    {
      value: 'custom',
      label: 'Stratégie personnalisée',
      desc: 'Décrivez votre objectif dans les notes — l\'IA s\'adapte.',
      icon: '✏️',
    },
  ];

  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;
  }

  function showToast(msg, type) {
    var el = document.createElement('div');
    el.textContent = msg;
    Object.assign(el.style, {
      position: 'fixed', bottom: '24px', left: '50%', transform: 'translateX(-50%)',
      background: type === 'error' ? 'oklch(0.35 0.12 25)' : 'oklch(0.18 0.012 85)',
      color: '#fff',
      padding: '12px 24px', borderRadius: '8px', zIndex: 10000,
      fontSize: '14px', fontFamily: 'Inter, sans-serif',
      boxShadow: '0 4px 16px rgba(0,0,0,0.25)',
    });
    document.body.appendChild(el);
    setTimeout(function () { el.remove(); }, 4000);
  }

  // ---- DossierModal ----
  function DossierModal({ open, onClose, listing, currentUser }) {
    const [strategy, setStrategy] = useState('buy_and_hold');
    const [notes, setNotes] = useState('');
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);

    // Reset on open
    useEffect(() => {
      if (open) {
        setStrategy('buy_and_hold');
        setNotes('');
        setError(null);
      }
    }, [open]);

    if (!open) return null;

    const handleCheckout = async () => {
      if (!currentUser) {
        // Ouvrir LoginModal via le hook global
        if (window.vestora && window.vestora.auth && typeof window.vestora.auth.openModal === 'function') {
          window.vestora.auth.openModal();
        }
        onClose();
        return;
      }

      setLoading(true);
      setError(null);

      try {
        const token = await _getAuthToken();
        const headers = { 'Content-Type': 'application/json' };
        if (token) headers['Authorization'] = 'Bearer ' + token;

        const body = {
          listing_id: String(listing.id),
          strategy: strategy,
        };

        // Ajouter les notes comme user_options si présentes
        if (notes.trim()) {
          body.user_options = { analyste_notes: notes.trim() };
        }

        const resp = await fetch(API_BASE + '/dossiers/checkout', {
          method: 'POST',
          headers: headers,
          body: JSON.stringify(body),
        });

        const data = await resp.json().catch(function () { return {}; });

        if (!resp.ok) {
          const msg = data.detail || data.message || 'Erreur ' + resp.status;
          throw new Error(msg);
        }

        if (!data.checkout_url) {
          throw new Error('Réponse backend inattendue (pas de checkout_url).');
        }

        // Tracking analytics
        if (window.vestora && window.vestora.analytics) {
          window.vestora.analytics.track('InitiateCheckout', {
            value: 49,
            currency: 'CAD',
            content_name: 'dossier_ia',
            strategy: strategy,
          });
        }

        // Redirection Stripe Checkout
        window.location.href = data.checkout_url;

      } catch (e) {
        setError(e.message || 'Une erreur est survenue.');
        setLoading(false);
      }
    };

    const selectedStrategy = STRATEGIES.find(s => s.value === strategy);

    return (
      <div
        style={{
          position: 'fixed', inset: 0, zIndex: 1000,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          background: 'rgba(0,0,0,0.55)',
          padding: '16px',
        }}
        onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}
      >
        <div style={{
          background: 'var(--bg-elev, #fff)',
          borderRadius: 'var(--radius-lg, 12px)',
          width: '100%', maxWidth: 560,
          maxHeight: '90vh', overflowY: 'auto',
          boxShadow: '0 24px 64px rgba(0,0,0,0.18)',
          fontFamily: 'var(--sans, Inter, sans-serif)',
        }}>
          {/* Header */}
          <div style={{
            padding: '20px 24px 16px',
            borderBottom: '1px solid var(--line, #e8e8e0)',
            display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 12,
          }}>
            <div>
              <div style={{ fontSize: 12, color: 'var(--ink-3)', marginBottom: 4, textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 600 }}>
                Dossier IA — Analyse one-shot
              </div>
              <h2 style={{ margin: 0, fontSize: 18, fontWeight: 700, color: 'var(--ink-1)', fontFamily: 'var(--serif, Fraunces, serif)' }}>
                {listing.address}
              </h2>
              <div style={{ fontSize: 13, color: 'var(--ink-3)', marginTop: 4 }}>
                {listing.city} · {listing.units} unités · {window.fmt ? window.fmt.money(listing.price) : listing.price + ' $'}
              </div>
            </div>
            <button
              onClick={onClose}
              style={{
                background: 'none', border: 'none', cursor: 'pointer',
                color: 'var(--ink-3)', padding: 4, flexShrink: 0,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}
              aria-label="Fermer"
            >
              <svg width="14" height="14" viewBox="0 0 14 14" stroke="currentColor" strokeWidth="1.4" fill="none">
                <path d="M2 2l10 10M12 2L2 12"/>
              </svg>
            </button>
          </div>

          {/* Body */}
          <div style={{ padding: '20px 24px' }}>

            {/* Sélection stratégie */}
            <div style={{ marginBottom: 20 }}>
              <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink-1)', marginBottom: 12 }}>
                Choisissez votre stratégie d'investissement
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
                {STRATEGIES.map((s) => (
                  <button
                    key={s.value}
                    onClick={() => setStrategy(s.value)}
                    style={{
                      padding: '12px 14px',
                      borderRadius: 'var(--radius, 8px)',
                      border: strategy === s.value
                        ? '2px solid var(--accent, oklch(0.36 0.07 155))'
                        : '1.5px solid var(--line, #e8e8e0)',
                      background: strategy === s.value
                        ? 'var(--accent-soft, oklch(0.95 0.04 155))'
                        : 'var(--bg-warm, #f9f9f6)',
                      cursor: 'pointer',
                      textAlign: 'left',
                      transition: 'all 0.15s',
                      fontFamily: 'inherit',
                    }}
                  >
                    <div style={{ fontSize: 15, marginBottom: 4 }}>{s.icon}</div>
                    <div style={{
                      fontSize: 13, fontWeight: 600,
                      color: strategy === s.value ? 'var(--accent-ink, oklch(0.26 0.07 155))' : 'var(--ink-1)',
                      marginBottom: 2,
                    }}>
                      {s.label}
                    </div>
                    <div style={{ fontSize: 11, color: 'var(--ink-3)', lineHeight: 1.4 }}>
                      {s.desc}
                    </div>
                  </button>
                ))}
              </div>
            </div>

            {/* Notes optionnelles */}
            <div style={{ marginBottom: 20 }}>
              <label style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink-1)', display: 'block', marginBottom: 8 }}>
                Notes pour l'analyste IA
                <span style={{ fontSize: 11, fontWeight: 400, color: 'var(--ink-3)', marginLeft: 8 }}>
                  Optionnel · max 500 caractères
                </span>
              </label>
              <textarea
                value={notes}
                onChange={(e) => {
                  if (e.target.value.length <= 500) setNotes(e.target.value);
                }}
                placeholder="Ex : Budget réno 50 000$, horizon 5 ans, financement 80%, objectif cash-flow +500$/mois..."
                rows={3}
                style={{
                  width: '100%', padding: '10px 12px',
                  borderRadius: 'var(--radius, 8px)',
                  border: '1.5px solid var(--line, #e8e8e0)',
                  background: 'var(--bg, #fff)',
                  fontSize: 13, color: 'var(--ink-1)',
                  fontFamily: 'inherit', resize: 'vertical',
                  outline: 'none',
                  boxSizing: 'border-box',
                }}
                onFocus={(e) => { e.target.style.borderColor = 'var(--accent, oklch(0.36 0.07 155))'; }}
                onBlur={(e) => { e.target.style.borderColor = 'var(--line, #e8e8e0)'; }}
              />
              <div style={{ fontSize: 11, color: notes.length > 450 ? 'var(--severity-warning, #b45309)' : 'var(--ink-4)', marginTop: 4, textAlign: 'right' }}>
                {notes.length}/500
              </div>
            </div>

            {/* Ce que contient le dossier */}
            <div style={{
              background: 'var(--bg-warm, #f9f9f6)',
              border: '1px solid var(--line, #e8e8e0)',
              borderRadius: 'var(--radius, 8px)',
              padding: '14px 16px',
              marginBottom: 20,
            }}>
              <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--ink-1)', marginBottom: 8, textTransform: 'uppercase', letterSpacing: '0.04em' }}>
                Inclus dans votre dossier IA
              </div>
              <ul style={{ margin: 0, padding: '0 0 0 16px', listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 5 }}>
                {[
                  'Synthèse complète du bien + diagnostic investisseur',
                  'Métriques financières détaillées (cap rate, DSCR, cashFlow, COC, IRR)',
                  'Analyse de la position de marché',
                  'Stress test des taux hypothécaires',
                  'Projection sur 5-10 ans selon la stratégie choisie',
                  'Citations de données publiques (MAMH, SCHL, StatCan)',
                  'Rapport HTML brandé Vestora',
                ].map((item, i) => (
                  <li key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: 8, fontSize: 12, color: 'var(--ink-2)' }}>
                    <span style={{ color: 'oklch(0.42 0.13 150)', flexShrink: 0, marginTop: 1 }}>✓</span>
                    {item}
                  </li>
                ))}
              </ul>
            </div>

            {/* Erreur */}
            {error && (
              <div style={{
                background: 'oklch(0.97 0.03 25)', border: '1px solid oklch(0.85 0.08 25)',
                borderRadius: 8, padding: '10px 14px', marginBottom: 16,
                fontSize: 13, color: 'oklch(0.35 0.12 25)',
              }}>
                {error}
              </div>
            )}

            {/* CTA */}
            <button
              onClick={handleCheckout}
              disabled={loading}
              style={{
                width: '100%', padding: '14px 20px',
                background: loading ? 'var(--ink-3, #888)' : 'var(--accent, oklch(0.36 0.07 155))',
                color: 'var(--accent-fg, #fff)',
                border: 'none', borderRadius: 'var(--radius, 8px)',
                fontSize: 15, fontWeight: 700, cursor: loading ? 'not-allowed' : 'pointer',
                fontFamily: 'inherit',
                transition: 'opacity 0.15s, transform 0.15s',
                display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
              }}
              onMouseEnter={(e) => { if (!loading) { e.currentTarget.style.opacity = '0.88'; e.currentTarget.style.transform = 'translateY(-1px)'; } }}
              onMouseLeave={(e) => { e.currentTarget.style.opacity = '1'; e.currentTarget.style.transform = 'translateY(0)'; }}
            >
              {loading ? (
                <>
                  <span style={{ display: 'inline-block', width: 16, height: 16, border: '2px solid rgba(255,255,255,0.3)', borderTopColor: '#fff', borderRadius: '50%', animation: 'spin 0.7s linear infinite' }}/>
                  Redirection vers le paiement...
                </>
              ) : (
                <>
                  <span>Continuer vers le paiement</span>
                  <span style={{ fontFamily: 'var(--mono)', fontWeight: 600 }}>49 $CAD</span>
                </>
              )}
            </button>

            <div style={{ textAlign: 'center', fontSize: 12, color: 'var(--ink-3)', marginTop: 10, lineHeight: 1.5 }}>
              Paiement sécurisé via Stripe · Accès au rapport en quelques minutes
              <br />
              TVQ et TPS en sus pour les résidents du Québec
            </div>
          </div>
        </div>

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

  window.DossierModal = DossierModal;
})();
