// AccountChip — avatar/initiale + dropdown ou bouton "Se connecter"
// Intégré dans le Header via window.AccountChip

const { useState: useAC, useEffect: useEAC, useRef: useRAC, useMemo: useMAC } = React;

/**
 * Calcule les infos du trial à partir de trial_ends_at (ISO string ou null).
 * @returns {{ active: boolean, daysLeft: number, expiresSoon: boolean } | null}
 */
function _getTrialInfo(trialEndsAt) {
  if (!trialEndsAt) return null;
  var ends = new Date(trialEndsAt);
  var now = new Date();
  var msLeft = ends - now;
  if (msLeft <= 0) return null;
  var daysLeft = Math.ceil(msLeft / (1000 * 60 * 60 * 24));
  return { active: true, daysLeft: daysLeft, expiresSoon: daysLeft <= 2 };
}

function AccountChip({ lang, onOpenLogin }) {
  const FR = lang !== 'en';
  const [user, setUser] = useAC(() => {
    const auth = window.vestora && window.vestora.auth;
    return auth ? auth.getUser() : null;
  });
  const [dropdownOpen, setDropdownOpen] = useAC(false);
  const [trialModalDismissed, setTrialModalDismissed] = useAC(false);
  const wrapRef = useRAC(null);

  const trialInfo = useMAC(() => user ? _getTrialInfo(user.trial_ends_at) : null, [user]);

  // S'abonner aux changements d'auth
  useEAC(() => {
    const auth = window.vestora && window.vestora.auth;
    if (!auth) return;
    const unsubscribe = auth.onAuthStateChange((updatedUser) => {
      setUser(updatedUser);
    });
    return unsubscribe;
  }, []);

  // Fermer le dropdown en cliquant dehors
  useEAC(() => {
    const onClick = (e) => {
      if (wrapRef.current && !wrapRef.current.contains(e.target)) {
        setDropdownOpen(false);
      }
    };
    document.addEventListener('mousedown', onClick);
    return () => document.removeEventListener('mousedown', onClick);
  }, []);

  const handleSignOut = async () => {
    const auth = window.vestora && window.vestora.auth;
    if (!auth) return;
    setDropdownOpen(false);
    await auth.signOut();
    setUser(null);
  };

  // Initiale de l'email pour l'avatar
  const initiale = user && user.email ? user.email[0].toUpperCase() : '?';
  const emailTrunc = user && user.email
    ? (user.email.length > 22 ? user.email.slice(0, 19) + '…' : user.email)
    : '';

  // Libellé du plan
  const PLAN_LABELS = {
    discovery:   FR ? 'Découverte' : 'Discovery',
    investisseur: FR ? 'Investisseur' : 'Investor',
    pro:         'Pro',
    enterprise:  FR ? 'Entreprise' : 'Enterprise',
  };
  const planLabel = user ? (PLAN_LABELS[user.plan] || user.plan) : '';
  const trialBadge = trialInfo && trialInfo.active
    ? (FR
        ? `Trial Pro — ${trialInfo.daysLeft}j restant${trialInfo.daysLeft > 1 ? 's' : ''}`
        : `Pro Trial — ${trialInfo.daysLeft}d left`)
    : null;

  if (!user) {
    // Non connecté → bouton "Se connecter"
    return (
      <button
        className="btn-ghost btn"
        onClick={() => onOpenLogin && onOpenLogin()}
        type="button"
        style={{ whiteSpace: 'nowrap' }}
      >
        {FR ? 'Se connecter' : 'Sign in'}
      </button>
    );
  }

  // Connecté → avatar + dropdown
  return (
    <div ref={wrapRef} style={{ position: 'relative' }}>
      {/* Modal trial expirant dans ≤ 2 jours */}
      {trialInfo && trialInfo.expiresSoon && !trialModalDismissed && (
        <div style={{
          position: 'fixed', inset: 0, zIndex: 10001,
          background: 'rgba(0,0,0,0.45)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <div style={{
            background: 'var(--color-surface, #fff)',
            borderRadius: 14, padding: '32px 28px', maxWidth: 400, width: '90%',
            boxShadow: '0 16px 48px rgba(0,0,0,0.22)',
            fontFamily: 'var(--font-body)',
            textAlign: 'center',
          }}>
            <div style={{ fontSize: 36, marginBottom: 12 }}>⏳</div>
            <div style={{ fontSize: 18, fontWeight: 700, marginBottom: 8, color: 'var(--color-text, #1a1a1a)' }}>
              {FR
                ? `Votre trial Pro expire dans ${trialInfo.daysLeft} jour${trialInfo.daysLeft > 1 ? 's' : ''}`
                : `Your Pro trial expires in ${trialInfo.daysLeft} day${trialInfo.daysLeft > 1 ? 's' : ''}`}
            </div>
            <div style={{ fontSize: 14, color: 'var(--color-muted, #666)', marginBottom: 24, lineHeight: 1.6 }}>
              {FR
                ? 'Continuez à profiter des analyses Pro, fiscalité QC, PDF export et alertes multi-critères.'
                : 'Keep Pro analyses, QC taxation, PDF export and multi-criteria alerts.'}
            </div>
            <button
              type="button"
              onClick={() => {
                setTrialModalDismissed(true);
                window.navigateTo && window.navigateTo('#/tarifs');
              }}
              style={{
                width: '100%', padding: '13px 16px', borderRadius: 8, border: 'none',
                background: 'var(--brand, #2c3e2d)', color: '#fff',
                fontWeight: 700, fontSize: 15, cursor: 'pointer',
                fontFamily: 'inherit', marginBottom: 10,
              }}
            >
              {FR ? 'Continuer en Pro — 59$/mo' : 'Continue with Pro — $59/mo'}
            </button>
            <button
              type="button"
              onClick={() => setTrialModalDismissed(true)}
              style={{
                background: 'none', border: 'none', color: 'var(--color-muted, #999)',
                fontSize: 13, cursor: 'pointer', fontFamily: 'inherit',
              }}
            >
              {FR ? 'Plus tard' : 'Maybe later'}
            </button>
          </div>
        </div>
      )}
      <button
        type="button"
        onClick={() => setDropdownOpen(o => !o)}
        title={user.email}
        style={{
          display: 'inline-flex', alignItems: 'center', gap: 8,
          padding: '5px 10px 5px 5px',
          border: '1.5px solid var(--color-border, #ddd)',
          borderRadius: 20,
          background: 'transparent',
          cursor: 'pointer',
          fontFamily: 'var(--font-body)',
          fontSize: 13, fontWeight: 600,
          color: 'var(--color-text, #1a1a1a)',
        }}
      >
        {/* Avatar initiale */}
        <span style={{
          width: 26, height: 26, borderRadius: '50%',
          background: 'var(--brand, #2c3e2d)', color: '#fff',
          display: 'inline-flex', alignItems: 'center',
          justifyContent: 'center', fontSize: 12, fontWeight: 700,
          flexShrink: 0,
        }}>
          {initiale}
        </span>
        <span style={{ maxWidth: 120, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
          {emailTrunc}
        </span>
        <svg width="10" height="10" viewBox="0 0 10 10" fill="none" stroke="currentColor" strokeWidth="1.5">
          <path d="M2 3.5l3 3 3-3"/>
        </svg>
      </button>

      {dropdownOpen && (
        <div style={{
          position: 'absolute', top: 'calc(100% + 6px)', right: 0,
          minWidth: 200,
          background: 'var(--color-surface, #fff)',
          border: '1.5px solid var(--color-border, #ddd)',
          borderRadius: 10, boxShadow: '0 8px 24px rgba(0,0,0,0.12)',
          zIndex: 9999, overflow: 'hidden',
          fontFamily: 'var(--font-body)',
        }}>
          {/* Info utilisateur */}
          <div style={{
            padding: '12px 16px', borderBottom: '1px solid var(--color-border, #ddd)',
          }}>
            <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--color-text, #1a1a1a)', wordBreak: 'break-all' }}>
              {user.email}
            </div>
            {planLabel && (
              <div style={{
                marginTop: 4, fontSize: 11, fontWeight: 600,
                color: 'var(--brand, #2c3e2d)',
                textTransform: 'uppercase', letterSpacing: '0.06em',
              }}>
                {planLabel}
              </div>
            )}
            {trialBadge && (
              <div style={{
                marginTop: 4, fontSize: 11, fontWeight: 600,
                background: 'oklch(0.52 0.13 150 / 0.15)',
                color: 'oklch(0.36 0.13 150)',
                borderRadius: 6, padding: '2px 6px', display: 'inline-block',
              }}>
                {trialBadge}
              </div>
            )}
          </div>

          {/* Actions */}
          <div style={{ padding: '4px 0' }}>
            <button
              type="button"
              style={{
                display: 'block', width: '100%', textAlign: 'left',
                padding: '10px 16px', background: 'none', border: 'none',
                fontSize: 14, cursor: 'pointer',
                color: 'var(--color-text, #1a1a1a)',
                fontFamily: 'var(--font-body)',
              }}
              onMouseEnter={(e) => e.currentTarget.style.background = 'var(--color-hover, #f5f5f5)'}
              onMouseLeave={(e) => e.currentTarget.style.background = 'none'}
              onClick={() => { setDropdownOpen(false); /* future: page compte */ }}
            >
              {FR ? 'Mon compte' : 'My account'}
            </button>
            <button
              type="button"
              style={{
                display: 'block', width: '100%', textAlign: 'left',
                padding: '10px 16px', background: 'none', border: 'none',
                fontSize: 14, cursor: 'pointer',
                color: 'var(--color-danger, #c0392b)',
                fontFamily: 'var(--font-body)',
              }}
              onMouseEnter={(e) => e.currentTarget.style.background = 'var(--color-hover, #f5f5f5)'}
              onMouseLeave={(e) => e.currentTarget.style.background = 'none'}
              onClick={handleSignOut}
            >
              {FR ? 'Déconnexion' : 'Sign out'}
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { AccountChip });
