// ═══════════════════════════════════════════════════════════════════
// KINGDOMID COMMAND — KingdomReach Index
// Shows all clients — click one to manage their SMS
// ═══════════════════════════════════════════════════════════════════

import { useEffect, useState } from 'react';
import { useNavigate }         from 'react-router-dom';
import { apiGet }              from '../lib/firebase';
import { MessageSquare, ArrowRight, Phone } from 'lucide-react';

interface Client {
  id:                  string;
  business_name:       string;
  niche:               string;
  subdomain:           string;
  status:              string;
  subscription_plan:   string;
  twilio_phone_number: string | null;
  went_live_at:        string | null;
}

const NICHE_LABELS: Record<string, string> = {
  christian_counseling: 'Christian Counseling',
  senior_care:          'Senior Care',
  medical_pediatric:    'Medical / Pediatric',
  chiropractic_pt:      'Chiropractic / PT',
  christian_school:     'Christian School',
  veterinary:           'Veterinary',
  funeral_home:         'Funeral Home',
  family_law:           'Family Law',
  home_services:        'Home Services',
  church_ministry:      'Church / Ministry',
  other:                'Other',
};

export default function KingdomReachIndexPage() {
  const navigate              = useNavigate();
  const [clients, setClients] = useState<Client[]>([]);
  const [loading, setLoading] = useState(true);
  const [error,   setError]   = useState('');

  useEffect(() => { loadClients(); }, []);

  const loadClients = async () => {
    try {
      const res = await apiGet<{ clients: Client[] }>('/api/onboarding/clients');
      setClients(res.clients || []);
    } catch (err: any) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  if (loading) return (
    <div style={{ padding: 48, textAlign: 'center' }}>
      <div className="spinner" style={{ margin: '0 auto 12px' }} />
      <p className="text-muted">Loading clients...</p>
    </div>
  );

  return (
    <div className="page-content">
      <div style={{ maxWidth: 800, margin: '0 auto' }}>

        <div className="flex-between mb-20">
          <div>
            <h1 style={{ fontSize: '2rem', marginBottom: 4 }}>KingdomReach</h1>
            <p className="text-muted">Select a client to manage their SMS automations and conversations</p>
          </div>
        </div>

        {error && (
          <div className="alert alert-error mb-16">{error}</div>
        )}

        {clients.length === 0 ? (
          <div className="empty-state">
            <MessageSquare />
            <h3>No clients yet</h3>
            <p>Onboard your first client to activate KingdomReach</p>
          </div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {clients.map(client => (
              <div
                key={client.id}
                onClick={() => navigate(`/clients/${client.id}/reach`)}
                className="card"
                style={{ cursor: 'pointer', transition: 'box-shadow 0.15s' }}
                onMouseEnter={e => (e.currentTarget.style.boxShadow = '0 4px 16px rgba(13,27,62,0.12)')}
                onMouseLeave={e => (e.currentTarget.style.boxShadow = '')}
              >
                <div className="card-body" style={{ padding: '16px 20px' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>

                    {/* Avatar */}
                    <div style={{
                      width:           44,
                      height:          44,
                      borderRadius:    '50%',
                      background:      'linear-gradient(135deg, var(--navy), var(--navy-light))',
                      display:         'flex',
                      alignItems:      'center',
                      justifyContent:  'center',
                      fontSize:        '1.1rem',
                      fontWeight:      700,
                      color:           'var(--gold)',
                      flexShrink:      0,
                      fontFamily:      'var(--font-display)',
                    }}>
                      {client.business_name[0]}
                    </div>

                    {/* Info */}
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontWeight: 700, fontSize: 15, color: 'var(--navy)', marginBottom: 3 }}>
                        {client.business_name}
                      </div>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
                        <span style={{ fontSize: 16, color: 'var(--gray-500)' }}>
                          {NICHE_LABELS[client.niche] || client.niche}
                        </span>
                        {client.twilio_phone_number && (
                          <span style={{ display: 'flex', alignItems: 'center', gap: 4, fontSize: 16, color: 'var(--gray-400)' }}>
                            <Phone size={11} />{client.twilio_phone_number}
                          </span>
                        )}
                        <span style={{
                          fontSize: 16,
                          fontWeight:   700,
                          padding:      '2px 8px',
                          borderRadius: 20,
                          textTransform:'capitalize',
                          background:   client.status === 'active' ? 'var(--success-bg)' : 'var(--warning-bg)',
                          color:        client.status === 'active' ? 'var(--success)' : 'var(--warning)',
                        }}>
                          {client.status}
                        </span>
                        <span style={{
                          fontSize: 16,
                          fontWeight:   700,
                          padding:      '2px 8px',
                          borderRadius: 20,
                          background:   'var(--tan)',
                          color:        'var(--gray-500)',
                          textTransform:'capitalize',
                        }}>
                          {client.subscription_plan}
                        </span>
                      </div>
                    </div>

                    {/* Arrow */}
                    <div style={{ display: 'flex', alignItems: 'center', gap: 6, color: 'var(--gold)', fontWeight: 600, fontSize: 15, flexShrink: 0 }}>
                      <MessageSquare size={15} />
                      Manage SMS
                      <ArrowRight size={15} />
                    </div>

                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
