// AccountPage — Route #/compte
// Audit client Investisseur (2026-07-22) : « Mon compte » envoyait sur la page
// tarifs publique (fallback silencieux du Customer Portal) — aucun endroit où
// voir son plan actuel ni gérer/annuler son abonnement (« Annule en 1 clic »
// promis par la FAQ). Cette page est le hub compte :
//   - plan actuel (nom marketing + prix) + email
//   - « Gérer mon abonnement » → Customer Portal Stripe (billing.openCustomerPortal)
//     avec message d'erreur explicite si aucun abonnement Stripe actif
//   - raccourcis portefeuille / alertes / dossiers IA
// AccountChip « Mon compte » route désormais ici (plus de portal-direct).

(function () {
  'use strict';

  const { useState } = React;

  // Mapping valeur brute user.plan (JWT user_metadata OU public.users) → tier
  // marketing. Voir bug plan désync 2026-07-22 : les deux vocabulaires existent
  // dans la nature (DB : free/pro/pro_plus/agent ; meta : investisseur/…).
  function planInfo(rawPlan, FR) {
    const p = String(rawPlan || '').toLowerCase();
    switch (p) {
      case 'investisseur':
      case 'investor':
      case 'pro': // valeur DB du plan Investisseur (Plan.PRO backend)
        return { label: 'Investisseur', price: FR ? '24 $/mois' : '$24/mo', paid: true, color: 'var(--accent, #2c3e2d)' };
      case 'investisseur_pro':
      case 'pro_plus':
        return { label: 'Investisseur Pro', price: FR ? '49 $/mois' : '$49/mo', paid: true, color: 'oklch(0.40 0.10 280)' };
      case 'agent':
      case 'professional':
        return { label: FR ? 'Pro Courtier' : 'Pro Broker', price: FR ? '59 $/mois' : '$59/mo', paid: true, color: 'oklch(0.36 0.07 155)' };
      case 'agent_commercial':
      case 'pro_commercial':
      case 'pro-commercial':
        return { label: 'Pro Commercial', price: FR ? '129 $/mois' : '$129/mo', paid: true, color: 'oklch(0.36 0.07 155)' };
      case 'enterprise':
      case 'entreprise':
        return { label: FR ? 'Entreprise' : 'Enterprise', price: '', paid: true, color: 'var(--ink-1)' };
      default:
        return { label: FR ? 'Découverte' : 'Discovery', price: FR ? 'Gratuit' : 'Free', paid: false, color: 'var(--ink-3, #64748b)' };
    }
  }

  function AccountPage({ user, lang, onBack }) {
    const FR = lang !== 'en';
    const [portalLoading, setPortalLoading] = useState(false);
    const [portalError, setPortalError] = useState(null);

    // Non connecté → invite à se connecter (même pattern que PortfolioPage)
    if (!user) {
      return (
        <div style={{ maxWidth: 720, margin: '60px auto', padding: 30, textAlign: 'center' }}>
          <button className="btn btn-ghost" onClick={onBack} style={{ marginBottom: 16 }}>
            {FR ? '← Retour à la recherche' : '← Back to search'}
          </button>
          <h2 style={{ color: 'var(--ink-1)' }}>{FR ? 'Mon compte' : 'My account'}</h2>
          <p style={{ color: 'var(--ink-3)' }}>
            {FR ? 'Connectez-vous pour accéder à votre compte.' : 'Sign in to access your account.'}
          </p>
        </div>
      );
    }

    const info = planInfo(user.plan, FR);
    const trialEndsAt = user.trial_ends_at ? new Date(user.trial_ends_at) : null;
    const trialActive = trialEndsAt && trialEndsAt.getTime() > Date.now();

    const openPortal = async () => {
      setPortalError(null);
      const billing = window.vestora && window.vestora.billing;
      if (!billing || typeof billing.openCustomerPortal !== 'function') {
        setPortalError(FR ? 'Le module de facturation n’est pas disponible.' : 'Billing module unavailable.');
        return;
      }
      setPortalLoading(true);
      try {
        await billing.openCustomerPortal(); // redirige si OK
      } catch (e) {
        // Cas le plus courant : compte sans abonnement Stripe (plan provisionné
        // manuellement, trial, ou plan gratuit) → message explicite plutôt que
        // l'ancien fallback silencieux vers /tarifs.
        setPortalError(
          FR
            ? 'Aucun abonnement Stripe actif pour ce compte. Si vous pensez que c’est une erreur, écrivez-nous : contact@vestora.ca'
            : 'No active Stripe subscription on this account. If this looks wrong, contact us: contact@vestora.ca'
        );
      } finally {
        setPortalLoading(false);
      }
    };

    const card = {
      background: 'var(--bg-elev, #fff)', border: '1px solid var(--line, #e2e8f0)',
      borderRadius: 12, padding: '20px 24px', marginBottom: 16,
    };
    const shortcutStyle = {
      display: 'block', width: '100%', textAlign: 'left', padding: '12px 16px',
      background: 'var(--bg-elev, #fff)', border: '1px solid var(--line, #e2e8f0)',
      borderRadius: 10, color: 'var(--ink-1, #0f172a)', cursor: 'pointer',
      fontSize: 14, fontFamily: 'inherit', marginBottom: 8,
    };
    const go = (hash) => { if (window.navigateTo) window.navigateTo(hash); else window.location.hash = hash; };

    return (
      <div style={{ maxWidth: 720, margin: '0 auto', padding: '24px 16px 60px' }}>
        <button className="btn btn-ghost" onClick={onBack} style={{ marginBottom: 16 }}>
          {FR ? '← Retour à la recherche' : '← Back to search'}
        </button>
        <h2 style={{ color: 'var(--ink-1)', margin: '0 0 4px' }}>{FR ? 'Mon compte' : 'My account'}</h2>
        <div style={{ color: 'var(--ink-3)', fontSize: 14, marginBottom: 24 }}>{user.email}</div>

        {/* ── Plan actuel ── */}
        <div style={card}>
          <div style={{ fontSize: 12, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 8 }}>
            {FR ? 'Plan actuel' : 'Current plan'}
          </div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, flexWrap: 'wrap' }}>
            <span style={{ fontSize: 22, fontWeight: 700, color: info.color }}>{info.label}</span>
            {info.price && <span style={{ fontSize: 14, color: 'var(--ink-3)' }}>{info.price}</span>}
            {trialActive && (
              <span style={{ fontSize: 12, padding: '2px 10px', borderRadius: 99, background: 'var(--accent, #2c3e2d)', color: '#fff' }}>
                {FR
                  ? `Essai Pro actif jusqu'au ${trialEndsAt.toLocaleDateString('fr-CA', { day: 'numeric', month: 'short' })}`
                  : `Pro trial until ${trialEndsAt.toLocaleDateString('en-CA', { day: 'numeric', month: 'short' })}`}
              </span>
            )}
          </div>

          <div style={{ marginTop: 16, display: 'flex', gap: 10, flexWrap: 'wrap' }}>
            {info.paid ? (
              <button
                type="button"
                onClick={openPortal}
                disabled={portalLoading}
                style={{
                  padding: '11px 18px', borderRadius: 8, border: 'none', cursor: portalLoading ? 'wait' : 'pointer',
                  background: 'var(--brand, #2c3e2d)', color: '#fff', fontWeight: 700, fontSize: 14, fontFamily: 'inherit',
                  opacity: portalLoading ? 0.7 : 1,
                }}
              >
                {portalLoading
                  ? (FR ? 'Ouverture…' : 'Opening…')
                  : (FR ? 'Gérer mon abonnement (facturation, annulation)' : 'Manage subscription (billing, cancel)')}
              </button>
            ) : (
              <button
                type="button"
                onClick={() => go('#/tarifs')}
                style={{
                  padding: '11px 18px', borderRadius: 8, border: 'none', cursor: 'pointer',
                  background: 'var(--brand, #2c3e2d)', color: '#fff', fontWeight: 700, fontSize: 14, fontFamily: 'inherit',
                }}
              >
                {FR ? 'Voir les plans' : 'See plans'}
              </button>
            )}
            <button type="button" className="btn btn-ghost" onClick={() => go('#/tarifs')} style={{ fontSize: 13 }}>
              {FR ? 'Comparer les plans' : 'Compare plans'}
            </button>
          </div>

          {portalError && (
            <div style={{
              marginTop: 12, padding: '10px 14px', borderRadius: 8, fontSize: 13,
              background: 'color-mix(in oklab, #b45309 12%, var(--bg-elev, #fff))',
              border: '1px solid #d97706', color: 'var(--ink-1)',
            }}>
              {portalError}
            </div>
          )}
          {info.paid && (
            <div style={{ marginTop: 10, fontSize: 12, color: 'var(--ink-3)' }}>
              {FR
                ? 'Le portail Stripe permet de changer de carte, télécharger vos factures et annuler en 1 clic.'
                : 'The Stripe portal lets you update your card, download invoices and cancel in one click.'}
            </div>
          )}
        </div>

        {/* ── Raccourcis ── */}
        <div style={{ fontSize: 12, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: 0.5, margin: '20px 0 8px' }}>
          {FR ? 'Raccourcis' : 'Shortcuts'}
        </div>
        <button type="button" style={shortcutStyle} onClick={() => go('#/portefeuille')}>
          🏠 {FR ? 'Mon portefeuille' : 'My portfolio'}
        </button>
        <button type="button" style={shortcutStyle} onClick={() => go('#/alertes')}>
          🔔 {FR ? 'Mes alertes' : 'My alerts'}
        </button>
        <button type="button" style={shortcutStyle} onClick={() => go('#/mes-dossiers')}>
          📄 {FR ? 'Mes dossiers IA' : 'My AI reports'}
        </button>

        <div style={{ marginTop: 24, fontSize: 12, color: 'var(--ink-3)' }}>
          {FR ? 'Besoin d’aide ? ' : 'Need help? '}
          <a href="mailto:contact@vestora.ca" style={{ color: 'var(--ink-1)' }}>contact@vestora.ca</a>
        </div>
      </div>
    );
  }

  window.AccountPage = AccountPage;
})();
