// Clients_Kanban.jsx — Board kanban 7 colonnes + bandeau "Actions du jour".
// Extrait de BrokerTab_Clients.jsx (Vague 2 PR 2.4 + Vague 4 PR 4.2).
//
// Conventions : NO import/export, React global, unique hook aliases (suffix K).
//
// L'algorithme et le rendu sont strictement identiques au monolithe original :
// regroupement par stage, tri par lastActivityAt desc, bandeau dueClients,
// changement de stage via <select> (le "drag-and-drop" historique se fait via
// ce select).

function ClientsKanban({
  clients,
  onChangeStage,
  onOpenDetail,
}) {
  const u = window.vestoraBrokerClients || {};
  const STAGE_COLS = u.STAGE_COLS || [];
  const formatRelativeDate = u.formatRelativeDate || (() => '');
  const nextActionStatus = u.nextActionStatus || (() => null);

  const grouped = STAGE_COLS.reduce((acc, s) => { acc[s.key] = []; return acc; }, {});
  clients.forEach((c) => {
    const key = c.stage && grouped[c.stage] ? c.stage : 'prospect';
    grouped[key].push(c);
  });
  Object.keys(grouped).forEach((k) => {
    grouped[k].sort((a, b) => (b.lastActivityAt || 0) - (a.lastActivityAt || 0));
  });

  // Vague 4 PR 4.2 — "Actions du jour" : clients avec next_action_at <= now+24h
  const dueClients = clients
    .filter((c) => c.nextActionAt && c.nextActionAt <= Date.now() + 24 * 3600 * 1000)
    .sort((a, b) => (a.nextActionAt || 0) - (b.nextActionAt || 0));

  return (
    <div style={{ width: '100%' }}>
      {dueClients.length > 0 && (
        <div style={{
          background: '#fef3c7', border: '1px solid #fbbf24',
          borderRadius: 10, padding: '10px 14px', marginBottom: 12,
        }}>
          <div style={{ fontSize: 13, fontWeight: 700, color: '#92400e', marginBottom: 6 }}>
            Actions du jour ({dueClients.length})
          </div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            {dueClients.map((c) => {
              const st = nextActionStatus(c);
              return (
                <button
                  key={c.id}
                  type="button"
                  onClick={() => onOpenDetail(c)}
                  style={{
                    fontSize: 11, padding: '3px 10px', borderRadius: 12,
                    background: (st && st.bg) || '#fff5f5',
                    color: (st && st.color) || '#7c2d12',
                    border: '1px solid ' + ((st && st.color) || '#fecaca') + '60',
                    cursor: 'pointer',
                  }}
                  title={c.nextActionNote || ''}
                >
                  {c.name}{c.nextActionNote ? ' — ' + c.nextActionNote : ''}
                </button>
              );
            })}
          </div>
        </div>
      )}
      <div style={{ display: 'flex', gap: 12, overflowX: 'auto', paddingBottom: 8 }}>
        {STAGE_COLS.map((col) => (
          <div
            key={col.key}
            style={{
              minWidth: 240,
              flex: '0 0 240px',
              background: col.bg,
              border: '1px solid ' + col.color + '40',
              borderRadius: 10,
              display: 'flex',
              flexDirection: 'column',
              maxHeight: '70vh',
            }}
          >
            {/* Sticky header */}
            <div style={{
              position: 'sticky', top: 0,
              background: col.bg,
              padding: '10px 12px',
              borderBottom: '1px solid ' + col.color + '40',
              borderRadius: '10px 10px 0 0',
              zIndex: 1,
            }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <span style={{ fontWeight: 700, fontSize: 13, color: col.color }}>
                  {col.label}
                </span>
                <span style={{
                  background: col.color, color: '#fff',
                  fontSize: 11, fontWeight: 700, borderRadius: 10,
                  padding: '1px 7px', minWidth: 18, textAlign: 'center',
                }}>{grouped[col.key].length}</span>
              </div>
            </div>
            {/* Cards */}
            <div style={{ overflowY: 'auto', padding: 8, display: 'flex', flexDirection: 'column', gap: 8 }}>
              {grouped[col.key].length === 0 ? (
                <div style={{ color: '#9ca3af', fontSize: 12, textAlign: 'center', padding: '20px 8px' }}>
                  Aucun client
                </div>
              ) : grouped[col.key].map((c) => {
                const cityLabel = (c.cities && c.cities.length > 0)
                  ? (c.cities[0] + (c.cities.length > 1 ? ' +' + (c.cities.length - 1) : ''))
                  : 'toutes villes';
                const budgetLabel = (c.budgetMin || c.budgetMax)
                  ? `${c.budgetMin ? (c.budgetMin / 1000).toFixed(0) + 'k' : '0'} – ${c.budgetMax ? (c.budgetMax / 1000).toFixed(0) + 'k$' : '∞'}`
                  : '—';
                return (
                  <div
                    key={c.id}
                    onClick={() => onOpenDetail(c)}
                    style={{
                      background: '#fff',
                      border: '1px solid #e5e7eb',
                      borderLeft: '3px solid ' + col.color,
                      borderRadius: 8,
                      padding: '10px 12px',
                      cursor: 'pointer',
                      boxShadow: '0 1px 2px rgba(0,0,0,0.04)',
                    }}
                  >
                    <div style={{ fontWeight: 600, fontSize: 13, color: '#111827', marginBottom: 4, display: 'flex', alignItems: 'center', gap: 6 }}>
                      <span>{c.name}</span>
                      {(() => {
                        const st = nextActionStatus(c);
                        if (!st) return null;
                        return (
                          <span style={{
                            fontSize: 9, fontWeight: 700,
                            background: st.bg, color: st.color,
                            padding: '1px 6px', borderRadius: 8,
                          }} title={c.nextActionNote || st.label}>{st.label}</span>
                        );
                      })()}
                    </div>
                    <div style={{ fontSize: 11, color: '#6b7280', marginBottom: 2 }}>
                      <span dangerouslySetInnerHTML={{ __html: window.vestoraIcons.dollarSign({ size: 14 }) }}></span> {budgetLabel}
                    </div>
                    <div style={{ fontSize: 11, color: '#6b7280', marginBottom: 6 }}>
                      <span dangerouslySetInnerHTML={{ __html: window.vestoraIcons.mapPin({ size: 14 }) }}></span> {cityLabel}
                    </div>
                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 6 }}>
                      <span style={{ fontSize: 10, color: '#9ca3af' }}>
                        {formatRelativeDate(c.lastActivityAt) || '—'}
                      </span>
                      <select
                        value={c.stage || 'prospect'}
                        onClick={(e) => e.stopPropagation()}
                        onChange={(e) => onChangeStage(c.id, e.target.value)}
                        style={{
                          fontSize: 11, padding: '2px 4px', borderRadius: 4,
                          border: '1px solid #d1d5db', background: '#fff',
                          cursor: 'pointer', color: '#374151',
                        }}
                      >
                        {STAGE_COLS.map((s) => (
                          <option key={s.key} value={s.key}>{s.label}</option>
                        ))}
                      </select>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

if (typeof window !== 'undefined') {
  window.ClientsKanban = ClientsKanban;
}
