// AgencyJoinPage — Acceptation invitation agence (Vague 5 PR 5.4)
// Route : #/agency/join?token=...
//
// Si user pas connecté → propose login/signup via LoginModal.
// Une fois connecté → appelle POST /agency/join puis redirige vers #/agence.

const {
  useState: useAJ,
  useEffect: useEAJ,
} = React;

function AgencyJoinPage({ user, lang }) {
  const FR = lang !== 'en';

  const [token, setToken] = useAJ('');
  const [status, setStatus] = useAJ('idle'); // idle | loading | success | error
  const [errorMsg, setErrorMsg] = useAJ('');
  const [loginOpen, setLoginOpen] = useAJ(false);

  // Parse token depuis l'URL hash : #/agency/join?token=abc...
  useEAJ(() => {
    const hash = window.location.hash || '';
    const q = hash.indexOf('?');
    if (q < 0) return;
    const params = new URLSearchParams(hash.substring(q + 1));
    const t = params.get('token') || '';
    setToken(t);
  }, []);

  async function handleAccept() {
    if (!token) return;
    setStatus('loading');
    setErrorMsg('');
    const api = window.vestora && window.vestora.agencyApi;
    if (!api) {
      setStatus('error');
      setErrorMsg(FR ? 'API agence indisponible.' : 'Agency API unavailable.');
      return;
    }
    const res = await api.acceptInvitation(token);
    if (!res.ok) {
      setStatus('error');
      setErrorMsg((res.error && res.error.message) || (FR ? 'Erreur acceptation.' : 'Accept failed.'));
      return;
    }
    setStatus('success');
    setTimeout(() => { window.location.hash = '#/agence'; }, 1200);
  }

  if (!token) {
    return (
      <div style={wrap}>
        <h1 style={h1}>{FR ? 'Invitation introuvable' : 'Invitation not found'}</h1>
        <p style={muted}>
          {FR ? "Le lien d'invitation est invalide ou incomplet." : 'The invitation link is invalid or incomplete.'}
        </p>
      </div>
    );
  }

  if (!user) {
    return (
      <div style={wrap}>
        <h1 style={h1}>{FR ? 'Connexion requise' : 'Sign in required'}</h1>
        <p style={muted}>
          {FR
            ? "Pour accepter l'invitation, connectez-vous à votre compte Vestora (ou créez-en un)."
            : 'To accept the invitation, sign in to your Vestora account (or create one).'}
        </p>
        <button
          onClick={() => setLoginOpen(true)}
          style={primaryBtn}
        >
          {FR ? 'Se connecter / Créer un compte' : 'Sign in / Sign up'}
        </button>
        {window.LoginModal ? (
          <window.LoginModal
            open={loginOpen}
            onClose={() => setLoginOpen(false)}
            lang={lang}
          />
        ) : null}
      </div>
    );
  }

  return (
    <div style={wrap}>
      <h1 style={h1}>{FR ? 'Rejoindre une agence Vestora' : 'Join a Vestora agency'}</h1>
      <p style={muted}>
        {FR
          ? 'Vous êtes sur le point de rejoindre une agence. Pendant que le siège est actif, vous bénéficiez automatiquement du plan Pro Courtier.'
          : 'You are about to join an agency. While the seat is active, you automatically get the Pro Broker plan.'}
      </p>

      {status === 'idle' && (
        <button onClick={handleAccept} style={primaryBtn}>
          {FR ? "Accepter l'invitation" : 'Accept invitation'}
        </button>
      )}
      {status === 'loading' && <p>{FR ? 'Traitement…' : 'Processing…'}</p>}
      {status === 'success' && (
        <p style={{ color: '#166534', fontWeight: 600 }}>
          {FR ? 'Invitation acceptée — redirection…' : 'Invitation accepted — redirecting…'}
        </p>
      )}
      {status === 'error' && (
        <>
          <p style={{ color: '#991b1b' }}>{errorMsg}</p>
          <button onClick={handleAccept} style={primaryBtn}>
            {FR ? 'Réessayer' : 'Retry'}
          </button>
        </>
      )}
    </div>
  );
}

const wrap = { maxWidth: 560, margin: '60px auto', padding: 24, fontFamily: '-apple-system,Segoe UI,sans-serif' };
const h1 = { fontSize: 26, marginBottom: 12 };
const muted = { color: '#475569', lineHeight: 1.55 };
const primaryBtn = {
  marginTop: 16, padding: '12px 22px', background: '#0f766e',
  color: '#fff', border: 0, borderRadius: 6, fontWeight: 600, cursor: 'pointer', fontSize: 15,
};

window.AgencyJoinPage = AgencyJoinPage;
