// BrokerDashboard — Tableau de bord courtier (plan Pro+)
// Suffixe alias : BD (BrokerDashboard)

const {
  useState: useBD,
  useMemo: useMBD,
  useEffect: useEBD,
} = React;

function BrokerDashboard({ user, lang, t, activeProfile, setActiveProfile }) {
  const FR = lang !== 'en';

  // ── Gating / tier ────────────────────────────────────────────────────────────
  const [tier, setTier] = useBD(null); // null = chargement

  useEBD(() => {
    const tg = window.vestora && window.vestora.tierGate;
    if (tg && typeof tg.getCurrentTier === 'function') {
      tg.getCurrentTier().then(t => setTier(t));
    } else {
      setTier('decouverte'); // fallback sécurisé
    }
  }, []);

  // ── Onglet actif — persisté localStorage ─────────────────────────────────────
  const [activeTab, setActiveTab] = useBD(() => {
    try {
      return localStorage.getItem('vestora_broker_tab') || 'marche';
    } catch (e) {
      return 'marche';
    }
  });

  const switchTab = (tab) => {
    setActiveTab(tab);
    try { localStorage.setItem('vestora_broker_tab', tab); } catch (e) {}
  };

  // ── Territoire ────────────────────────────────────────────────────────────────
  const [territory, setTerritory] = useBD({ type: 'all', value: null });

  // ── Listing sélectionné (pour le Drawer) ─────────────────────────────────────
  const [selectedListingId, setSelectedListingId] = useBD(null);

  // ── Dérivés mémoïsés ─────────────────────────────────────────────────────────
  const allCities = useMBD(() => {
    const listings = window.LISTINGS || [];
    const cities = new Set();
    listings.forEach(l => { if (l.city) cities.add(l.city); });
    return [...cities].sort((a, b) => a.localeCompare(b, 'fr'));
  }, []);

  const filteredListings = useMBD(() => {
    const listings = window.LISTINGS || [];
    if (territory.type === 'all' || !territory.value) return listings;
    const val = territory.value.toLowerCase();
    return listings.filter(l => (l.city || '').toLowerCase() === val);
  }, [territory]);

  const selectedListing = useMBD(() => {
    if (!selectedListingId) return null;
    return (window.LISTINGS || []).find(l => String(l.id) === String(selectedListingId)) || null;
  }, [selectedListingId]);

  // ── Chargement ────────────────────────────────────────────────────────────────
  if (tier === null) {
    return (
      <div className="broker-spinner-wrap" aria-label={FR ? 'Chargement…' : 'Loading…'}>
        <div className="broker-spinner" />
      </div>
    );
  }

  // ── Gating : non autorisé ─────────────────────────────────────────────────────
  if (tier !== 'pro' && tier !== 'entreprise') {
    return (
      <div style={{ position: 'relative', minHeight: '100vh', background: 'var(--bg)', overflow: 'hidden' }}>
        {/* Arrière-plan flouté */}
        <div style={{
          filter: 'blur(6px)', pointerEvents: 'none', userSelect: 'none',
          opacity: 0.35, padding: '16px 24px',
        }}>
          <div className="broker-tabs">
            {['Marché', 'Opportunités', 'Clients', 'Analyse rapide'].map(label => (
              <button key={label} className="broker-tab-btn">{label}</button>
            ))}
          </div>
          <div className="broker-content">
            {[1,2,3].map(i => (
              <div key={i} style={{
                height: 80, marginBottom: 16, borderRadius: 8,
                background: 'var(--line-soft, #e8e8e4)'
              }}/>
            ))}
          </div>
        </div>
        {/* Paywall */}
        {window.PaywallModal && (
          <window.PaywallModal
            open={true}
            onClose={() => window.navigateTo('#/landing')}
            requiredTier="pro"
            featureLabel="Dashboard courtier"
          />
        )}
        {!window.PaywallModal && (
          <div style={{
            position: 'absolute', inset: 0,
            display: 'flex', flexDirection: 'column',
            alignItems: 'center', justifyContent: 'center',
            gap: 16, zIndex: 100,
          }}>
            <div style={{ fontSize: 36 }}>🔒</div>
            <p style={{ textAlign: 'center', maxWidth: 360, color: 'var(--ink-2)', lineHeight: 1.6 }}>
              {FR
                ? 'Le dashboard courtier est réservé au plan Pro.'
                : 'Broker dashboard requires a Pro plan.'}
            </p>
            <button
              onClick={() => window.navigateTo('#/tarifs')}
              style={{
                padding: '10px 24px', borderRadius: 8,
                background: 'var(--accent)', color: 'var(--accent-fg)',
                border: 'none', cursor: 'pointer', fontWeight: 600, fontSize: 14,
              }}
            >
              {FR ? 'Voir les plans' : 'See plans'}
            </button>
          </div>
        )}
      </div>
    );
  }

  // ── Empty state listings ──────────────────────────────────────────────────────
  const hasListings = window.LISTINGS && window.LISTINGS.length > 0;

  // ── Labels des onglets ────────────────────────────────────────────────────────
  const tabs = [
    { id: 'marche',       label: FR ? 'Marché'          : 'Market'      },
    { id: 'opportunites', label: FR ? 'Opportunités'    : 'Opportunities'},
    { id: 'clients',      label: FR ? 'Clients'         : 'Clients'     },
    { id: 'rapide',       label: FR ? 'Analyse rapide'  : 'Quick analysis'},
  ];

  return (
    <div className="broker-root">

      {/* ── Header simplifié (retour + titre + user) ──────────────────────────── */}
      <div className="broker-header">
        <div className="broker-header-left">
          <button
            className="broker-back-btn"
            onClick={() => window.navigateTo('#/')}
            aria-label={FR ? 'Retour' : 'Back'}
          >
            <svg width="14" height="14" viewBox="0 0 14 14" stroke="currentColor" strokeWidth="1.8" fill="none">
              <path d="M9 2L3 7l6 5"/>
            </svg>
            {FR ? 'Retour' : 'Back'}
          </button>
          <span className="broker-header-title">
            {FR ? 'Dashboard Courtier' : 'Broker Dashboard'}
          </span>
        </div>
        <div className="broker-header-right">
          {user && (
            <span className="broker-user-chip">
              {user.email || (FR ? 'Courtier' : 'Broker')}
            </span>
          )}
          <span className="broker-tier-badge">Pro</span>
        </div>
      </div>

      {/* ── Barre d'onglets sticky ────────────────────────────────────────────── */}
      <div className="broker-tabs" role="tablist" aria-label={FR ? 'Sections du dashboard' : 'Dashboard sections'}>
        {tabs.map(tab => (
          <button
            key={tab.id}
            className={'broker-tab-btn' + (activeTab === tab.id ? ' broker-tab-btn--active' : '')}
            role="tab"
            aria-selected={activeTab === tab.id}
            onClick={() => switchTab(tab.id)}
          >
            {tab.label}
          </button>
        ))}
      </div>

      {/* ── Contenu principal ─────────────────────────────────────────────────── */}
      <div className="broker-content" role="tabpanel">
        {!hasListings ? (
          <div className="broker-empty-state">
            <div className="broker-empty-icon">📭</div>
            <h2 className="broker-section-title">
              {FR ? 'Aucune annonce disponible' : 'No listings available'}
            </h2>
            <p>
              {FR
                ? 'Les données de marché apparaîtront ici une fois les annonces chargées.'
                : 'Market data will appear here once listings are loaded.'}
            </p>
          </div>
        ) : (
          <>
            {activeTab === 'marche' && (
              <BrokerTabMarche
                filteredListings={filteredListings}
                territory={territory}
                setTerritory={setTerritory}
                allCities={allCities}
                lang={lang}
                activeProfile={activeProfile}
              />
            )}
            {activeTab === 'opportunites' && (
              <BrokerTabOpportunites
                filteredListings={filteredListings}
                territory={territory}
                setTerritory={setTerritory}
                allCities={allCities}
                lang={lang}
                activeProfile={activeProfile}
                onSelectListing={setSelectedListingId}
              />
            )}
            {activeTab === 'clients' && (
              <BrokerTabClients
                allListings={window.LISTINGS}
                lang={lang}
              />
            )}
            {activeTab === 'rapide' && (
              <BrokerTabRapide
                allListings={window.LISTINGS}
                lang={lang}
              />
            )}
          </>
        )}
      </div>

      {/* ── Drawer listing ───────────────────────────────────────────────────── */}
      {window.Drawer && (
        <window.Drawer
          listing={selectedListing}
          open={!!selectedListing}
          onClose={() => setSelectedListingId(null)}
          lang={lang}
          t={t}
          activeProfile={activeProfile}
          currentUser={user}
        />
      )}
    </div>
  );
}

// Expose en global (pattern du projet — pas d'export)
window.BrokerDashboard = BrokerDashboard;
