// BrokerTab_Opportunites.jsx — Onglet "Opportunités" du dashboard courtier
// Conventions: NO import/export, React global, unique hook aliases (suffix O)

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

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

function NewBadge() {
  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 BrokerTabOpportunites({ filteredListings, territory, setTerritory, allCities, lang, activeProfile, onSelectListing }) {
  const { useState: useStateO, useMemo: useMemoO } = React;

  const [sortKey, setSortKey] = useStateO('score');
  const [tooltipVisible, setTooltipVisible] = useStateO(false);
  const [newOnly, setNewOnly] = useStateO(false);

  // Translation stub — ListingCard needs t but we pass a minimal fallback
  const t = {
    unit: 'unité',
    units: 'unités',
    bedrooms: 'ch.',
    bathrooms: 'sdb.',
    sqft: 'pi²',
    cap_rate: 'Taux cap.',
    cash_flow: 'Flux net',
    dscr: 'DSCR',
    days_on_market: 'Jours',
    Excellent: 'Excellent',
    Bon: 'Bon',
    Passable: 'Passable',
    Faible: 'Faible',
  };

  const isAllTerritory = !territory || territory.type === 'all';
  const territoryLabel = isAllTerritory ? 'tout le Québec' : (territory.value || 'tout le Québec');

  const opportunities = useMemoO(() => {
    // 1. Filter: only "sous le marché" (+ optionnellement "nouveaux")
    const filtered = (filteredListings || []).filter((l) => {
      if (l.marketContext?.vsMarket !== 'below') return false;
      if (newOnly && !isNewListing(l)) return false;
      return true;
    });

    // 2. Sort
    const sorted = [...filtered].sort((a, b) => {
      if (sortKey === 'score') {
        const sa = a.scoresByProfile?.[activeProfile]?.score ?? a.score ?? 0;
        const sb = b.scoresByProfile?.[activeProfile]?.score ?? b.score ?? 0;
        return sb - sa;
      }
      if (sortKey === 'capRate') {
        return (b.metrics?.capRate ?? 0) - (a.metrics?.capRate ?? 0);
      }
      if (sortKey === 'prix') {
        return (a.price ?? 0) - (b.price ?? 0);
      }
      if (sortKey === 'jours') {
        return (b.daysOnMarket ?? 0) - (a.daysOnMarket ?? 0);
      }
      return 0;
    });

    // 3. Limit to top 30
    return sorted.slice(0, 30);
  }, [filteredListings, sortKey, activeProfile, newOnly]);

  const newCount = useMemoO(
    () => (filteredListings || []).filter(l => l.marketContext?.vsMarket === 'below' && isNewListing(l)).length,
    [filteredListings]
  );

  return (
    <div className="broker-tab-opportunites" style={{ padding: '0 0 32px' }}>

      {/* ── Territory selector ── */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 16, flexWrap: 'wrap' }}>
        <button
          className={`broker-territory-btn${isAllTerritory ? ' active' : ''}`}
          onClick={() => setTerritory({ type: 'all', value: null })}
          style={{
            padding: '6px 14px',
            borderRadius: 20,
            border: '1.5px solid',
            borderColor: isAllTerritory ? '#3b82f6' : '#d1d5db',
            background: isAllTerritory ? '#eff6ff' : '#fff',
            color: isAllTerritory ? '#1d4ed8' : '#374151',
            fontWeight: isAllTerritory ? 600 : 400,
            cursor: 'pointer',
            fontSize: 13,
            whiteSpace: 'nowrap',
          }}
        >
          Tout le Québec
        </button>

        <select
          value={isAllTerritory ? '' : territory.value}
          onChange={(e) => setTerritory(e.target.value ? { type: 'city', value: e.target.value } : { type: 'all', value: null })}
          style={{
            padding: '6px 10px',
            borderRadius: 8,
            border: '1.5px solid #d1d5db',
            background: '#fff',
            fontSize: 13,
            color: '#374151',
            cursor: 'pointer',
          }}
        >
          <option value="">Choisir une ville…</option>
          {(allCities || []).map((city) => (
            <option key={city} value={city}>{city}</option>
          ))}
        </select>
      </div>

      {/* ── Sort + New filter ── */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 8, flexWrap: 'wrap' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <label style={{ fontSize: 13, color: '#6b7280', whiteSpace: 'nowrap' }}>Trier par :</label>
          <select
            value={sortKey}
            onChange={(e) => setSortKey(e.target.value)}
            style={{
              padding: '5px 10px',
              borderRadius: 8,
              border: '1.5px solid #d1d5db',
              background: '#fff',
              fontSize: 13,
              color: '#374151',
              cursor: 'pointer',
            }}
          >
            <option value="score">Score</option>
            <option value="capRate">Cap rate</option>
            <option value="prix">Prix</option>
            <option value="jours">Jours sur marché</option>
          </select>
        </div>

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

      {/* ── Stats line ── */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4, fontSize: 14, color: '#374151' }}>
        <span>
          <strong>{opportunities.length}</strong>{' '}
          opportunité{opportunities.length !== 1 ? 's' : ''} détectée{opportunities.length !== 1 ? 's' : ''}{' '}
          dans <em>{territoryLabel}</em>
        </span>
        <span
          style={{
            display: 'inline-flex',
            alignItems: 'center',
            justifyContent: 'center',
            width: 16,
            height: 16,
            borderRadius: '50%',
            background: '#e5e7eb',
            color: '#6b7280',
            fontSize: 10,
            cursor: 'help',
            position: 'relative',
            userSelect: 'none',
          }}
          onMouseEnter={() => setTooltipVisible(true)}
          onMouseLeave={() => setTooltipVisible(false)}
        >
          ?
          {tooltipVisible && (
            <div style={{
              position: 'absolute',
              bottom: '120%',
              left: '50%',
              transform: 'translateX(-50%)',
              background: '#1f2937',
              color: '#f9fafb',
              fontSize: 12,
              padding: '6px 10px',
              borderRadius: 6,
              whiteSpace: 'nowrap',
              zIndex: 100,
              pointerEvents: 'none',
              boxShadow: '0 2px 8px rgba(0,0,0,0.25)',
            }}>
              Propriétés dont le prix est inférieur à la médiane du marché local (vsMarket = "sous le marché")
            </div>
          )}
        </span>
      </div>

      {/* ── Grid or empty state ── */}
      {opportunities.length === 0 ? (
        <div
          className="broker-empty-state"
          style={{
            textAlign: 'center',
            padding: '48px 24px',
            color: '#9ca3af',
            fontSize: 15,
          }}
        >
          Aucune opportunité dans ce territoire. Élargis ta recherche.
        </div>
      ) : (
        <div
          className="broker-opps-grid"
          style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))',
            gap: 16,
            marginTop: 16,
          }}
        >
          {opportunities.map((l) => (
            <div key={l.id} style={{ position: 'relative' }}>
              {isNewListing(l) && <NewBadge />}
              <ListingCard
                listing={l}
                t={t}
                lang={lang}
                activeProfile={activeProfile}
                active={false}
                selected={false}
                onHover={() => {}}
                onLeave={() => {}}
                onClick={() => onSelectListing(l.id)}
                isFav={false}
                toggleFav={() => {}}
              />
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
