// BrokerTab_Clients.jsx — Onglet "Clients" du dashboard courtier
// Conventions: NO import/export, React global, unique hook aliases (suffix C)

// Seuil "nouveau" — listings dont daysOnMarket ≤ N jours sont marqués NOUVEAU.
// À ajuster quand les scrapes seront quotidiens (sera plus court).
const CLIENT_NEW_MAX_DAYS = 14;

function isNewListingC(l) {
  const dom = l && l.daysOnMarket;
  return typeof dom === 'number' && dom >= 0 && dom <= CLIENT_NEW_MAX_DAYS;
}

function NewBadgeC() {
  return (
    <span style={{
      position: 'absolute', top: 8, left: 8, zIndex: 2,
      background: '#10b981', color: '#fff',
      fontSize: 10, fontWeight: 700, letterSpacing: '0.5px',
      padding: '3px 7px', borderRadius: 4,
      pointerEvents: 'none', boxShadow: '0 1px 3px rgba(0,0,0,0.25)',
    }}>NOUVEAU</span>
  );
}

function BrokerTabClients({ allListings, lang }) {
  const {
    useState: useSC,
    useMemo: useMC,
    useEffect: useEC,
    useCallback: useCBC,
  } = React;

  // ── Translation stub (same as Opportunites) ──────────────────────────────
  const t = {
    unit: 'unité',
    units: 'unités',
    bedrooms: 'ch.',
    bathrooms: 'sdb.',
    sqft: 'pi²',
    cap_rate: 'Taux cap.',
    cash_flow: 'Flux net',
    dscr: 'DSCR',
    Excellent: 'Excellent',
    Bon: 'Bon',
    Passable: 'Passable',
    Faible: 'Faible',
  };

  // ── localStorage helpers ─────────────────────────────────────────────────
  const LS_KEY = 'vestora_broker_clients';

  function loadClients() {
    try {
      const raw = localStorage.getItem(LS_KEY);
      if (!raw) return [];
      const parsed = JSON.parse(raw);
      return Array.isArray(parsed) ? parsed : [];
    } catch (_) {
      return [];
    }
  }

  function saveClients(list) {
    try {
      localStorage.setItem(LS_KEY, JSON.stringify(list));
    } catch (_) {
      // private browsing — silent
    }
  }

  function genId() {
    try {
      return crypto.randomUUID();
    } catch (_) {
      return String(Date.now()) + Math.random().toString(36).slice(2);
    }
  }

  // ── State ─────────────────────────────────────────────────────────────────
  const [clients, setClients] = useSC(() => loadClients());

  // view: 'list' | 'form' | 'matches'
  const [view, setView] = useSC('list');
  const [editingId, setEditingId] = useSC(null); // null = new client
  const [matchingClient, setMatchingClient] = useSC(null);
  const [copiedLink, setCopiedLink] = useSC(false);
  const [newOnlyC, setNewOnlyC] = useSC(false);

  const EMPTY_FORM = {
    name: '',
    budgetMin: '',
    budgetMax: '',
    cities: [],
    propertyType: 'all',
    profile: 'cashflow_hunter',
  };

  const [form, setForm] = useSC(EMPTY_FORM);
  const [formError, setFormError] = useSC('');

  // ── Derived data ─────────────────────────────────────────────────────────
  const allCities = useMC(() => {
    const set = new Set();
    (allListings || []).forEach((l) => { if (l.city) set.add(l.city); });
    return [...set].sort((a, b) => a.localeCompare(b, 'fr'));
  }, [allListings]);

  // ── Property type classifier (mirrors app.jsx logic) ────────────────────
  function classifyUnits(units) {
    if (!units || units <= 1) return 'unifamilial';
    if (units <= 3) return 'plex23';
    return 'plex4plus';
  }

  // ── Matches computation ───────────────────────────────────────────────────
  const matchesBase = useMC(() => {
    if (!matchingClient) return [];
    const { budgetMin, budgetMax, cities, propertyType, profile } = matchingClient;
    return (allListings || [])
      .filter((l) => {
        if (budgetMin && l.price < Number(budgetMin)) return false;
        if (budgetMax && l.price > Number(budgetMax)) return false;
        if (cities && cities.length > 0 && !cities.includes(l.city)) return false;
        if (propertyType !== 'all' && classifyUnits(l.units) !== propertyType) return false;
        return true;
      })
      .sort((a, b) => {
        const sa = a.scoresByProfile?.[profile]?.score ?? 0;
        const sb = b.scoresByProfile?.[profile]?.score ?? 0;
        return sb - sa;
      });
  }, [matchingClient, allListings]);

  const matchesForClient = useMC(() => {
    const list = newOnlyC ? matchesBase.filter(isNewListingC) : matchesBase;
    return list.slice(0, 12);
  }, [matchesBase, newOnlyC]);

  const matchesNewCount = useMC(() => matchesBase.filter(isNewListingC).length, [matchesBase]);

  // ── Persist on change ────────────────────────────────────────────────────
  useEC(() => { saveClients(clients); }, [clients]);

  // ── Actions ──────────────────────────────────────────────────────────────
  function openNew() {
    setForm(EMPTY_FORM);
    setEditingId(null);
    setFormError('');
    setView('form');
  }

  function openEdit(client) {
    setForm({
      name: client.name,
      budgetMin: client.budgetMin === 0 ? '' : client.budgetMin,
      budgetMax: client.budgetMax === 0 ? '' : client.budgetMax,
      cities: client.cities || [],
      propertyType: client.propertyType || 'all',
      profile: client.profile || 'cashflow_hunter',
    });
    setEditingId(client.id);
    setFormError('');
    setView('form');
  }

  function openMatches(client) {
    setMatchingClient(client);
    setCopiedLink(false);
    setView('matches');
  }

  function deleteClient(id) {
    if (!window.confirm('Supprimer ce client ?')) return;
    setClients((prev) => prev.filter((c) => c.id !== id));
  }

  function handleSave() {
    if (!form.name.trim()) {
      setFormError('Le nom du client est requis.');
      return;
    }
    setFormError('');
    const now = Date.now();
    if (editingId) {
      setClients((prev) =>
        prev.map((c) =>
          c.id === editingId
            ? {
                ...c,
                name: form.name.trim(),
                budgetMin: form.budgetMin === '' ? 0 : Number(form.budgetMin),
                budgetMax: form.budgetMax === '' ? 0 : Number(form.budgetMax),
                cities: form.cities,
                propertyType: form.propertyType,
                profile: form.profile,
              }
            : c
        )
      );
    } else {
      const newClient = {
        id: genId(),
        name: form.name.trim(),
        budgetMin: form.budgetMin === '' ? 0 : Number(form.budgetMin),
        budgetMax: form.budgetMax === '' ? 0 : Number(form.budgetMax),
        cities: form.cities,
        propertyType: form.propertyType,
        profile: form.profile,
        createdAt: now,
      };
      setClients((prev) => [newClient, ...prev]);
    }
    setView('list');
  }

  function handleCancel() {
    setView('list');
    setFormError('');
  }

  function toggleCity(city) {
    setForm((f) => {
      const already = f.cities.includes(city);
      return {
        ...f,
        cities: already ? f.cities.filter((c) => c !== city) : [...f.cities, city],
      };
    });
  }

  function copyShareLink() {
    if (!matchingClient) return;
    const { budgetMin, budgetMax, cities, profile } = matchingClient;
    const params = new URLSearchParams();
    if (budgetMin) params.set('budgetMin', budgetMin);
    if (budgetMax) params.set('budgetMax', budgetMax);
    if (cities && cities.length > 0) params.set('cities', cities.join(','));
    if (profile) params.set('profile', profile);
    const url = `${location.origin}/#/?${params.toString()}`;
    navigator.clipboard.writeText(url).then(() => {
      setCopiedLink(true);
      setTimeout(() => setCopiedLink(false), 2000);
    }).catch(() => {
      // fallback: do nothing silently
    });
  }

  // ── Profile label helper ─────────────────────────────────────────────────
  const PROFILE_LABELS = {
    cashflow_hunter: '💰 Flux de trésorerie',
    first_buyer:     '🏠 Premier acheteur',
    buy_and_hold:    '📈 Long terme',
    value_add:       '🔨 Value Add',
    brrrr:           '♻️ BRRRR',
    student_housing: '🎓 Étudiant',
  };

  const PROPERTY_TYPE_LABELS = {
    all:        'Tous types',
    unifamilial: 'Unifamilial',
    plex23:     'Plex 2-3',
    plex4plus:  'Plex 4+',
  };

  function clientSummary(c) {
    const parts = [];
    if (c.budgetMin || c.budgetMax) {
      const lo = c.budgetMin ? `${(c.budgetMin / 1000).toFixed(0)}k$` : '0';
      const hi = c.budgetMax ? `${(c.budgetMax / 1000).toFixed(0)}k$` : '∞';
      parts.push(`${lo} – ${hi}`);
    }
    if (c.cities && c.cities.length > 0) {
      parts.push(`${c.cities.length} ville${c.cities.length > 1 ? 's' : ''}`);
    } else {
      parts.push('toutes villes');
    }
    parts.push(PROFILE_LABELS[c.profile] || c.profile);
    return parts.join(' · ');
  }

  // ── Shared styles ─────────────────────────────────────────────────────────
  const colStyle = {
    flex: 1,
    minWidth: 0,
  };

  const cardStyle = {
    background: 'var(--bg-elev, #fff)',
    border: '1px solid var(--line, #e5e7eb)',
    borderRadius: 10,
    padding: '14px 16px',
    marginBottom: 10,
    display: 'flex',
    flexDirection: 'column',
    gap: 6,
  };

  const btnPrimary = {
    padding: '8px 18px',
    borderRadius: 8,
    background: '#3b82f6',
    color: '#fff',
    border: 'none',
    fontWeight: 600,
    fontSize: 13,
    cursor: 'pointer',
  };

  const btnSecondary = {
    padding: '8px 18px',
    borderRadius: 8,
    background: 'transparent',
    color: '#374151',
    border: '1.5px solid #d1d5db',
    fontWeight: 500,
    fontSize: 13,
    cursor: 'pointer',
  };

  const btnDanger = {
    padding: '5px 12px',
    borderRadius: 6,
    background: 'transparent',
    color: '#ef4444',
    border: '1.5px solid #fca5a5',
    fontWeight: 500,
    fontSize: 12,
    cursor: 'pointer',
  };

  const btnSmall = {
    padding: '5px 12px',
    borderRadius: 6,
    background: 'transparent',
    color: '#374151',
    border: '1.5px solid #d1d5db',
    fontWeight: 500,
    fontSize: 12,
    cursor: 'pointer',
  };

  const inputStyle = {
    width: '100%',
    padding: '8px 10px',
    borderRadius: 8,
    border: '1.5px solid #d1d5db',
    fontSize: 14,
    color: '#111827',
    background: '#fff',
    boxSizing: 'border-box',
  };

  const labelStyle = {
    fontSize: 13,
    fontWeight: 600,
    color: '#374151',
    marginBottom: 4,
    display: 'block',
  };

  const sectionStyle = {
    marginBottom: 18,
  };

  // ── Render ─────────────────────────────────────────────────────────────────
  return (
    <div
      className="broker-tab-clients"
      style={{
        display: 'flex',
        gap: 24,
        alignItems: 'flex-start',
        padding: '0 0 40px',
        flexWrap: 'wrap',
      }}
    >

      {/* ════ LEFT COLUMN — client list ════ */}
      <div style={{ ...colStyle, minWidth: 260, maxWidth: 340 }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
          <h3 style={{ margin: 0, fontSize: 15, fontWeight: 700, color: '#111827' }}>
            Recherches sauvegardées ({clients.length})
          </h3>
          <button
            style={btnPrimary}
            onClick={openNew}
          >
            + Nouveau client
          </button>
        </div>

        {clients.length === 0 ? (
          <div style={{
            textAlign: 'center',
            padding: '40px 20px',
            color: '#9ca3af',
            fontSize: 14,
            background: 'var(--bg-elev, #f9fafb)',
            borderRadius: 10,
            border: '1px dashed #d1d5db',
          }}>
            Aucune recherche client.<br />
            Crée-en une pour suivre les biens correspondant aux besoins de tes clients.
          </div>
        ) : (
          <div>
            {clients.map((client) => (
              <div key={client.id} style={cardStyle}>
                <div style={{ fontWeight: 600, fontSize: 14, color: '#111827' }}>
                  {client.name}
                </div>
                <div style={{ fontSize: 12, color: '#6b7280' }}>
                  {clientSummary(client)}
                </div>
                <div style={{ display: 'flex', gap: 6, marginTop: 4, flexWrap: 'wrap' }}>
                  <button
                    style={{ ...btnSmall, background: '#eff6ff', color: '#1d4ed8', borderColor: '#bfdbfe' }}
                    onClick={() => openMatches(client)}
                  >
                    Voir matches
                  </button>
                  <button style={btnSmall} onClick={() => openEdit(client)}>
                    Modifier
                  </button>
                  <button style={btnDanger} onClick={() => deleteClient(client.id)}>
                    Supprimer
                  </button>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* ════ RIGHT COLUMN — form or matches ════ */}
      <div style={{ ...colStyle, minWidth: 300 }}>

        {/* ── FORM ── */}
        {view === 'form' && (
          <div style={{
            background: 'var(--bg-elev, #fff)',
            border: '1px solid var(--line, #e5e7eb)',
            borderRadius: 12,
            padding: '20px 22px',
          }}>
            <h3 style={{ margin: '0 0 18px', fontSize: 15, fontWeight: 700, color: '#111827' }}>
              {editingId ? 'Modifier le client' : 'Nouveau client'}
            </h3>

            {/* Nom */}
            <div style={sectionStyle}>
              <label style={labelStyle}>Nom du client</label>
              <input
                style={inputStyle}
                type="text"
                placeholder="ex. Sophie Tremblay"
                value={form.name}
                onChange={(e) => setForm({ ...form, name: e.target.value })}
              />
            </div>

            {/* Budget */}
            <div style={sectionStyle}>
              <label style={labelStyle}>Budget</label>
              <div style={{ display: 'flex', gap: 10 }}>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 12, color: '#6b7280', marginBottom: 4 }}>Min ($)</div>
                  <input
                    style={inputStyle}
                    type="number"
                    placeholder="0"
                    min="0"
                    value={form.budgetMin}
                    onChange={(e) => setForm({ ...form, budgetMin: e.target.value })}
                  />
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 12, color: '#6b7280', marginBottom: 4 }}>Max ($)</div>
                  <input
                    style={inputStyle}
                    type="number"
                    placeholder="sans limite"
                    min="0"
                    value={form.budgetMax}
                    onChange={(e) => setForm({ ...form, budgetMax: e.target.value })}
                  />
                </div>
              </div>
            </div>

            {/* Villes */}
            <div style={sectionStyle}>
              <label style={labelStyle}>
                Villes ciblées{' '}
                <span style={{ fontWeight: 400, color: '#9ca3af' }}>(laisser vide = toutes)</span>
              </label>
              <div style={{
                maxHeight: 150,
                overflowY: 'auto',
                border: '1.5px solid #d1d5db',
                borderRadius: 8,
                padding: '8px 10px',
                display: 'grid',
                gridTemplateColumns: 'repeat(auto-fill, minmax(130px, 1fr))',
                gap: '4px 10px',
              }}>
                {allCities.map((city) => (
                  <label
                    key={city}
                    style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13, cursor: 'pointer', color: '#374151', userSelect: 'none' }}
                  >
                    <input
                      type="checkbox"
                      checked={form.cities.includes(city)}
                      onChange={() => toggleCity(city)}
                      style={{ accentColor: '#3b82f6' }}
                    />
                    {city}
                  </label>
                ))}
                {allCities.length === 0 && (
                  <span style={{ fontSize: 13, color: '#9ca3af' }}>Aucune ville disponible</span>
                )}
              </div>
              {form.cities.length > 0 && (
                <div style={{ marginTop: 6, fontSize: 12, color: '#6b7280' }}>
                  {form.cities.length} ville{form.cities.length > 1 ? 's' : ''} sélectionnée{form.cities.length > 1 ? 's' : ''}
                  {' '}&mdash;{' '}
                  <button
                    style={{ background: 'none', border: 'none', color: '#3b82f6', cursor: 'pointer', fontSize: 12, padding: 0 }}
                    onClick={() => setForm({ ...form, cities: [] })}
                  >
                    Effacer
                  </button>
                </div>
              )}
            </div>

            {/* Type de propriété */}
            <div style={sectionStyle}>
              <label style={labelStyle}>Type de propriété</label>
              <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                {Object.entries(PROPERTY_TYPE_LABELS).map(([val, lbl]) => (
                  <label
                    key={val}
                    style={{
                      display: 'flex',
                      alignItems: 'center',
                      gap: 5,
                      fontSize: 13,
                      cursor: 'pointer',
                      color: form.propertyType === val ? '#1d4ed8' : '#374151',
                      fontWeight: form.propertyType === val ? 600 : 400,
                      userSelect: 'none',
                    }}
                  >
                    <input
                      type="radio"
                      name="propertyType"
                      value={val}
                      checked={form.propertyType === val}
                      onChange={() => setForm({ ...form, propertyType: val })}
                      style={{ accentColor: '#3b82f6' }}
                    />
                    {lbl}
                  </label>
                ))}
              </div>
            </div>

            {/* Profil investisseur */}
            <div style={sectionStyle}>
              <label style={labelStyle}>Profil investisseur</label>
              <ProfileSelector
                activeProfile={form.profile}
                setActiveProfile={(v) => setForm({ ...form, profile: v })}
                lang={lang}
              />
            </div>

            {/* Error */}
            {formError && (
              <div style={{ color: '#ef4444', fontSize: 13, marginBottom: 12 }}>
                {formError}
              </div>
            )}

            {/* Actions */}
            <div style={{ display: 'flex', gap: 10, marginTop: 4 }}>
              <button style={btnPrimary} onClick={handleSave}>
                Enregistrer
              </button>
              <button style={btnSecondary} onClick={handleCancel}>
                Annuler
              </button>
            </div>
          </div>
        )}

        {/* ── MATCHES ── */}
        {view === 'matches' && matchingClient && (
          <div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 16, flexWrap: 'wrap' }}>
              <button
                style={{ ...btnSecondary, padding: '6px 14px' }}
                onClick={() => setView('list')}
              >
                ← Retour
              </button>
              <h3 style={{ margin: 0, fontSize: 15, fontWeight: 700, color: '#111827' }}>
                Top 12 matches pour <em>{matchingClient.name}</em>
              </h3>
            </div>

            <div style={{ fontSize: 13, color: '#6b7280', marginBottom: 14 }}>
              {clientSummary(matchingClient)}
            </div>

            <div style={{ display: 'flex', gap: 10, marginBottom: 18, flexWrap: 'wrap', alignItems: 'center' }}>
              <button
                style={{
                  ...btnSmall,
                  background: copiedLink ? '#d1fae5' : 'transparent',
                  color: copiedLink ? '#065f46' : '#374151',
                  borderColor: copiedLink ? '#6ee7b7' : '#d1d5db',
                }}
                onClick={copyShareLink}
              >
                {copiedLink ? '✓ Copié !' : 'Copier lien partageable'}
              </button>

              <label
                title={`Affiche uniquement les biens listés depuis ≤ ${CLIENT_NEW_MAX_DAYS} jours`}
                style={{
                  display: 'inline-flex', alignItems: 'center', gap: 6,
                  padding: '5px 12px', borderRadius: 20,
                  border: '1.5px solid', borderColor: newOnlyC ? '#10b981' : '#d1d5db',
                  background: newOnlyC ? '#ecfdf5' : '#fff',
                  color: newOnlyC ? '#065f46' : '#374151',
                  fontSize: 13, fontWeight: newOnlyC ? 600 : 400,
                  cursor: 'pointer', userSelect: 'none', whiteSpace: 'nowrap',
                }}
              >
                <input
                  type="checkbox"
                  checked={newOnlyC}
                  onChange={(e) => setNewOnlyC(e.target.checked)}
                  style={{ margin: 0, accentColor: '#10b981', cursor: 'pointer' }}
                />
                Nouveaux seulement
                <span style={{ fontSize: 11, color: newOnlyC ? '#047857' : '#9ca3af' }}>
                  ({matchesNewCount})
                </span>
              </label>
            </div>

            {matchesForClient.length === 0 ? (
              <div style={{
                textAlign: 'center',
                padding: '40px 20px',
                color: '#9ca3af',
                fontSize: 14,
                background: '#f9fafb',
                borderRadius: 10,
                border: '1px dashed #d1d5db',
              }}>
                Aucun bien correspondant aux critères de ce client.
              </div>
            ) : (
              <div style={{
                display: 'grid',
                gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))',
                gap: 16,
              }}>
                {matchesForClient.map((l) => (
                  <div key={l.id} style={{ position: 'relative' }}>
                    {isNewListingC(l) && <NewBadgeC />}
                    <ListingCard
                      listing={l}
                      t={t}
                      lang={lang}
                      activeProfile={matchingClient.profile}
                      active={false}
                      selected={false}
                      onHover={() => {}}
                      onLeave={() => {}}
                      onClick={() => {}}
                      isFav={false}
                      toggleFav={() => {}}
                    />
                  </div>
                ))}
              </div>
            )}
          </div>
        )}

        {/* ── EMPTY RIGHT (list view, no action selected) ── */}
        {view === 'list' && (
          <div style={{
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            justifyContent: 'center',
            minHeight: 200,
            color: '#9ca3af',
            fontSize: 14,
            textAlign: 'center',
            padding: 32,
          }}>
            <div style={{ fontSize: 36, marginBottom: 12 }}>👥</div>
            <div>Sélectionne un client pour voir ses matches,<br />ou crée une nouvelle recherche.</div>
          </div>
        )}
      </div>
    </div>
  );
}
