// AgencyPage — Dashboard agence multi-seat (Vague 5 PR 5.4)
// Route : #/agence
//
// Pour les owners Pro Courtier : creation/gestion agence, invitations, KPIs
// agreges, leaderboard interne. Pour les members : vue lecture seule de
// l'agence + leaderboard.
//
// Convention Vestora : React global, exposé sur window.AgencyPage.

const {
  useState: useAG,
  useEffect: useEAG,
  useMemo: useMAG,
} = React;

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

  const [loading, setLoading] = useAG(true);
  const [agency, setAgency] = useAG(null);
  const [seats, setSeats] = useAG([]);
  const [kpis, setKpis] = useAG(null);
  const [toast, setToast] = useAG(null);

  // Form creation / invite
  const [creating, setCreating] = useAG(false);
  const [agencyName, setAgencyName] = useAG('');
  const [inviteEmail, setInviteEmail] = useAG('');
  const [inviting, setInviting] = useAG(false);

  function showToast(type, msg) {
    setToast({ type: type, msg: msg });
    setTimeout(() => setToast(null), 4000);
  }

  async function loadAll() {
    setLoading(true);
    const api = window.vestora && window.vestora.agencyApi;
    if (!api) {
      setLoading(false);
      return;
    }
    const res = await api.getMyAgency();
    if (!res.ok) {
      setLoading(false);
      return;
    }
    const ag = res.data;
    setAgency(ag);
    if (ag && ag.id) {
      const [seatsRes, kpisRes] = await Promise.all([
        api.listSeats(ag.id),
        api.getKpis(ag.id),
      ]);
      if (seatsRes.ok && seatsRes.data) setSeats(seatsRes.data.seats || []);
      if (kpisRes.ok) setKpis(kpisRes.data);
    }
    setLoading(false);
  }

  useEAG(() => { loadAll(); }, []);

  const isOwner = useMAG(() => {
    return !!(agency && user && agency.owner_user_id === user.id);
  }, [agency, user]);

  async function handleCreate(e) {
    e && e.preventDefault();
    if (!agencyName.trim()) return;
    setCreating(true);
    const res = await window.vestora.agencyApi.createAgency(agencyName.trim());
    setCreating(false);
    if (!res.ok) {
      showToast('error', (res.error && res.error.message) || (FR ? "Erreur création" : "Create failed"));
      return;
    }
    showToast('success', FR ? 'Agence créée' : 'Agency created');
    setAgencyName('');
    await loadAll();
  }

  async function handleInvite(e) {
    e && e.preventDefault();
    if (!agency || !inviteEmail.trim()) return;
    setInviting(true);
    const res = await window.vestora.agencyApi.inviteSeat(agency.id, inviteEmail.trim());
    setInviting(false);
    if (!res.ok) {
      showToast('error', (res.error && res.error.message) || (FR ? "Erreur invitation" : "Invite failed"));
      return;
    }
    showToast('success', FR ? 'Invitation envoyée' : 'Invitation sent');
    setInviteEmail('');
    await loadAll();
  }

  async function handleRevoke(seatId) {
    if (!agency) return;
    if (!window.confirm(FR ? 'Révoquer ce siège ?' : 'Revoke this seat?')) return;
    const res = await window.vestora.agencyApi.revokeSeat(agency.id, seatId);
    if (!res.ok) {
      showToast('error', (res.error && res.error.message) || 'Erreur');
      return;
    }
    showToast('success', FR ? 'Siège révoqué' : 'Seat revoked');
    await loadAll();
  }

  // ── Render ──────────────────────────────────────────────────────────────

  if (loading) {
    return (
      <div style={{ padding: 40, textAlign: 'center', color: '#64748b' }}>
        {FR ? 'Chargement…' : 'Loading…'}
      </div>
    );
  }

  // Pas d'agency : owner peut en créer une.
  if (!agency) {
    return (
      <div style={{ maxWidth: 720, margin: '40px auto', padding: 24, fontFamily: '-apple-system,Segoe UI,sans-serif' }}>
        <h1 style={{ fontSize: 28, marginBottom: 8 }}>
          {FR ? 'Pack agence — 89$/mois pour 2 sièges' : 'Agency pack — $89/month for 2 seats'}
        </h1>
        <p style={{ color: '#475569', lineHeight: 1.55 }}>
          {FR
            ? "Vous êtes courtier + adjoint ? Au lieu de payer 2×59$ = 118$/mois, prenez le pack agence 89$/mois pour 2 sièges. Économie ~29$/mois."
            : "Broker + assistant duo? Instead of 2×$59 = $118/mo, pick the agency pack at $89/mo for 2 seats. ~$29/mo savings."}
        </p>

        <form onSubmit={handleCreate} style={{ marginTop: 24, background: '#f8fafc', padding: 20, borderRadius: 8 }}>
          <label style={{ display: 'block', fontWeight: 600, marginBottom: 6 }}>
            {FR ? "Nom de l'agence" : 'Agency name'}
          </label>
          <input
            type="text"
            value={agencyName}
            onChange={(e) => setAgencyName(e.target.value)}
            placeholder={FR ? "Ex. Royal LePage Trois-Rivières" : "e.g. Royal LePage TR"}
            style={{ width: '100%', padding: '10px 12px', border: '1px solid #cbd5e1', borderRadius: 6, fontSize: 15 }}
          />
          <button
            type="submit"
            disabled={creating || !agencyName.trim()}
            style={{
              marginTop: 16, padding: '10px 20px', background: '#0f766e',
              color: '#fff', border: 0, borderRadius: 6, fontWeight: 600,
              cursor: creating ? 'wait' : 'pointer',
            }}
          >
            {creating ? '…' : (FR ? "Créer l'agence" : 'Create agency')}
          </button>
        </form>

        {toast && (
          <div style={{
            marginTop: 16, padding: 12, borderRadius: 6,
            background: toast.type === 'success' ? '#dcfce7' : '#fee2e2',
            color: toast.type === 'success' ? '#166534' : '#991b1b',
          }}>{toast.msg}</div>
        )}
      </div>
    );
  }

  const seatsUsed = agency.seats_used || seats.filter(s => s.status !== 'revoked').length;

  return (
    <div style={{ maxWidth: 1080, margin: '24px auto', padding: 24, fontFamily: '-apple-system,Segoe UI,sans-serif' }}>
      <header style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', borderBottom: '1px solid #e2e8f0', paddingBottom: 16, marginBottom: 24 }}>
        <div>
          <h1 style={{ fontSize: 26, margin: 0 }}>{agency.name}</h1>
          <p style={{ color: '#64748b', marginTop: 4 }}>
            {FR ? `Sièges utilisés : ${seatsUsed} / ${agency.max_seats}` : `Seats used: ${seatsUsed} / ${agency.max_seats}`}
            {isOwner ? <span style={{ marginLeft: 12, background: '#dbeafe', color: '#1e40af', padding: '2px 8px', borderRadius: 4, fontSize: 12 }}>{FR ? 'Propriétaire' : 'Owner'}</span> : null}
          </p>
        </div>
      </header>

      {/* KPIs cumulés */}
      {kpis ? (
        <section style={{ marginBottom: 32 }}>
          <h2 style={{ fontSize: 18, marginBottom: 12 }}>{FR ? 'KPIs agence' : 'Agency KPIs'}</h2>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(180px,1fr))', gap: 12 }}>
            <KpiCard label={FR ? 'GCI total YTD' : 'GCI YTD'} value={formatMoney(kpis.gci_ytd_total)} />
            <KpiCard label={FR ? 'Ventes YTD' : 'Sold YTD'} value={String(kpis.sold_ytd_count_total)} />
            <KpiCard label={FR ? 'Mandats actifs' : 'Active mandates'} value={String(kpis.active_mandates_count_total)} />
            <KpiCard label={FR ? 'Valeur active' : 'Active value'} value={formatMoney(kpis.active_mandates_value_total)} />
            <KpiCard label={FR ? 'DOM moyen' : 'Avg DOM'} value={kpis.avg_dom_agency != null ? `${kpis.avg_dom_agency} j` : '—'} />
            <KpiCard label={FR ? 'Ratio vendu/listed' : 'Sold/listed ratio'} value={kpis.avg_ratio_sold_vs_listed != null ? `${kpis.avg_ratio_sold_vs_listed}%` : '—'} />
          </div>
        </section>
      ) : null}

      {/* Leaderboard interne */}
      {kpis && kpis.seats && kpis.seats.length > 0 ? (
        <section style={{ marginBottom: 32 }}>
          <h2 style={{ fontSize: 18, marginBottom: 12 }}>{FR ? 'Leaderboard interne' : 'Internal leaderboard'}</h2>
          <table style={{ width: '100%', borderCollapse: 'collapse', background: '#fff' }}>
            <thead>
              <tr style={{ textAlign: 'left', background: '#f1f5f9' }}>
                <th style={th}>#</th>
                <th style={th}>{FR ? 'Courtier' : 'Broker'}</th>
                <th style={th}>{FR ? 'GCI YTD' : 'GCI YTD'}</th>
                <th style={th}>{FR ? 'Ventes YTD' : 'Sold YTD'}</th>
                <th style={th}>{FR ? 'Actifs' : 'Active'}</th>
                <th style={th}>{FR ? 'DOM moyen' : 'Avg DOM'}</th>
              </tr>
            </thead>
            <tbody>
              {kpis.seats.map((s, i) => (
                <tr key={s.user_id} style={{ borderBottom: '1px solid #e2e8f0' }}>
                  <td style={td}>{i + 1}</td>
                  <td style={td}>{s.email}</td>
                  <td style={td}>{formatMoney(s.gci_ytd)}</td>
                  <td style={td}>{s.sold_ytd_count}</td>
                  <td style={td}>{s.active_mandates_count}</td>
                  <td style={td}>{s.avg_dom_my_mandates != null ? `${s.avg_dom_my_mandates} j` : '—'}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </section>
      ) : null}

      {/* Liste des sièges */}
      <section style={{ marginBottom: 32 }}>
        <h2 style={{ fontSize: 18, marginBottom: 12 }}>{FR ? 'Sièges' : 'Seats'}</h2>
        <table style={{ width: '100%', borderCollapse: 'collapse', background: '#fff' }}>
          <thead>
            <tr style={{ textAlign: 'left', background: '#f1f5f9' }}>
              <th style={th}>{FR ? 'Membre' : 'Member'}</th>
              <th style={th}>{FR ? 'Rôle' : 'Role'}</th>
              <th style={th}>{FR ? 'Statut' : 'Status'}</th>
              <th style={th}>{FR ? 'Depuis' : 'Since'}</th>
              {isOwner ? <th style={th}></th> : null}
            </tr>
          </thead>
          <tbody>
            {seats.map(s => (
              <tr key={s.id} style={{ borderBottom: '1px solid #e2e8f0' }}>
                <td style={td}>{s.invitation_email || `user #${s.user_id}`}</td>
                <td style={td}>{s.role}</td>
                <td style={td}>
                  <StatusBadge status={s.status} FR={FR} />
                </td>
                <td style={td}>{s.joined_at ? new Date(s.joined_at).toLocaleDateString() : '—'}</td>
                {isOwner ? (
                  <td style={td}>
                    {s.role !== 'owner' && s.status !== 'revoked' ? (
                      <button
                        onClick={() => handleRevoke(s.id)}
                        style={{ background: '#fee2e2', color: '#991b1b', border: 0, padding: '6px 12px', borderRadius: 4, cursor: 'pointer' }}
                      >
                        {FR ? 'Révoquer' : 'Revoke'}
                      </button>
                    ) : null}
                  </td>
                ) : null}
              </tr>
            ))}
          </tbody>
        </table>
      </section>

      {/* Invite (owner only) */}
      {isOwner && seatsUsed < agency.max_seats ? (
        <section style={{ background: '#f8fafc', padding: 20, borderRadius: 8 }}>
          <h3 style={{ fontSize: 16, marginTop: 0 }}>{FR ? 'Inviter un membre' : 'Invite a member'}</h3>
          <form onSubmit={handleInvite} style={{ display: 'flex', gap: 8 }}>
            <input
              type="email"
              value={inviteEmail}
              onChange={(e) => setInviteEmail(e.target.value)}
              placeholder="adjoint@royallepage.ca"
              style={{ flex: 1, padding: '10px 12px', border: '1px solid #cbd5e1', borderRadius: 6 }}
              required
            />
            <button
              type="submit"
              disabled={inviting || !inviteEmail.trim()}
              style={{
                padding: '10px 20px', background: '#0f766e',
                color: '#fff', border: 0, borderRadius: 6, fontWeight: 600,
                cursor: inviting ? 'wait' : 'pointer',
              }}
            >
              {inviting ? '…' : (FR ? 'Envoyer invitation' : 'Send invite')}
            </button>
          </form>
          <p style={{ color: '#64748b', fontSize: 13, marginTop: 8 }}>
            {FR ? "Le lien d'invitation expire après 14 jours." : 'Invitation link expires after 14 days.'}
          </p>
        </section>
      ) : null}

      {toast && (
        <div style={{
          position: 'fixed', bottom: 24, right: 24, padding: 14, borderRadius: 6,
          background: toast.type === 'success' ? '#dcfce7' : '#fee2e2',
          color: toast.type === 'success' ? '#166534' : '#991b1b',
          boxShadow: '0 4px 12px rgba(0,0,0,0.1)',
        }}>{toast.msg}</div>
      )}
    </div>
  );
}

const th = { padding: '10px 12px', fontSize: 13, fontWeight: 600, color: '#475569', borderBottom: '1px solid #e2e8f0' };
const td = { padding: '10px 12px', fontSize: 14, color: '#0f172a' };

function KpiCard({ label, value }) {
  return (
    <div style={{ background: '#fff', border: '1px solid #e2e8f0', borderRadius: 8, padding: 16 }}>
      <div style={{ fontSize: 12, color: '#64748b', textTransform: 'uppercase', letterSpacing: 0.4 }}>{label}</div>
      <div style={{ fontSize: 22, fontWeight: 700, marginTop: 6, color: '#0f172a' }}>{value}</div>
    </div>
  );
}

function StatusBadge({ status, FR }) {
  const map = {
    active: { bg: '#dcfce7', fg: '#166534', label: FR ? 'Actif' : 'Active' },
    pending: { bg: '#fef3c7', fg: '#92400e', label: FR ? 'En attente' : 'Pending' },
    revoked: { bg: '#fee2e2', fg: '#991b1b', label: FR ? 'Révoqué' : 'Revoked' },
  };
  const s = map[status] || map.pending;
  return (
    <span style={{ background: s.bg, color: s.fg, padding: '2px 8px', borderRadius: 4, fontSize: 12, fontWeight: 600 }}>
      {s.label}
    </span>
  );
}

function formatMoney(n) {
  if (n == null) return '—';
  return '$' + Math.round(n).toLocaleString('fr-CA');
}

window.AgencyPage = AgencyPage;
