(function() {
  const { useState, useEffect } = React;

  function DashboardPage({ t }) {
    const [stats, setStats] = useState(null);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
      window.api.stats().then(d => { setStats(d); setLoading(false); }).catch(() => setLoading(false));
    }, []);

    if (loading) return <div className="loading">{t('loading')}</div>;

    return (
      <div className="page">
        <div className="page-header">
          <h1><i className="ph ph-squares-four" style={{marginRight:8,color:'#4A6079'}}></i>{t('dash_title')}</h1>
          <span className="page-sub">{t('dash_sub')}</span>
        </div>

        <div className="stats-grid">
          <StatCard icon="ph-buildings" value={stats?.stats.total_listings || 0} label={t('dash_total_listings')} color="blue" />
          <StatCard icon="ph-hourglass-high" value={stats?.stats.pending_listings || 0} label={t('dash_pending')} color="yellow" />
          <StatCard icon="ph-users-three" value={stats?.stats.total_users || 0} label={t('dash_total_users')} color="purple" />
          <StatCard icon="ph-user-focus" value={stats?.stats.pending_agents || 0} label={t('dash_pending_agents')} color="yellow" />
          <StatCard icon="ph-envelope-open" value={stats?.stats.total_leads || 0} label={t('dash_total_leads')} color="green" />
          <StatCard icon="ph-calendar-dots" value={stats?.stats.leads_this_month || 0} label={t('dash_leads_month')} color="blue" />
        </div>

        <div className="grid-2" style={{marginTop: 28}}>
          <div className="card">
            <div className="card-header">{t('dash_recent_listings')}</div>
            <div className="table-wrap">
              <table className="table">
                <thead><tr><th>{t('name')}</th><th>{t('listings_agent')}</th><th>{t('status')}</th></tr></thead>
                <tbody>{(stats?.recent_listings || []).map((l,i) => (
                  <tr key={i}><td>{l.title}</td><td>{l.agent_name}</td><td><Badge status={l.status} /></td></tr>
                ))}</tbody>
              </table>
            </div>
          </div>
          <div className="card">
            <div className="card-header">{t('dash_recent_leads')}</div>
            <div className="table-wrap">
              <table className="table">
                <thead><tr><th>{t('name')}</th><th>{t('phone')}</th><th>{t('status')}</th></tr></thead>
                <tbody>{(stats?.recent_leads || []).map((l,i) => (
                  <tr key={i}><td>{l.name}</td><td>{l.phone}</td><td><Badge status={l.status} /></td></tr>
                ))}</tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    );
  }

  window.DashboardPage = DashboardPage;
})();
