// FavoritesPage — Route #/favoris
// Liste des biens favoris (♥) : résolus contre window.LISTINGS, avec le
// statut de sync cloud (Investisseur+ = multi-appareils via /api/v1/favorites,
// Découverte = local à cet appareil).
// Source des ids : lib favorites.js (cache localStorage + sync cloud).

(function () {
  'use strict';

  const { useState: useFPS, useEffect: useFPE, useMemo: useFPM } = React;

  function fmtMoney(v) {
    if (v == null || !Number.isFinite(Number(v))) return '—';
    return Math.round(Number(v)).toLocaleString('fr-CA') + ' $';
  }

  function FavoritesPage({ lang, onBack, currentUser }) {
    const FR = lang !== 'en';
    const [favIds, setFavIds] = useFPS(() =>
      window.vestoraFavorites ? window.vestoraFavorites.getIds() : new Set()
    );
    const [tier, setTier] = useFPS('decouverte');

    // Suit la lib favoris (toggle ici ou ailleurs, pull cloud).
    useFPE(() => {
      if (!window.vestoraFavorites) return;
      return window.vestoraFavorites.onChange((ids) => setFavIds(ids));
    }, []);

    useFPE(() => {
      const tg = window.vestora && window.vestora.tierGate;
      if (!tg) return;
      tg.getCurrentTier().then((t) => setTier(t)).catch(() => {});
    }, [currentUser]);

    // SEO
    useFPE(() => {
      const prev = document.title;
      document.title = FR ? 'Mes favoris — Vestora' : 'My favorites — Vestora';
      window.scrollTo(0, 0);
      return () => { document.title = prev; };
    }, []);

    const cloudSynced = tier !== 'decouverte';

    // Résolution ids -> listings (les délistés n'existent plus dans data.js).
    const { found, missing } = useFPM(() => {
      const ls = window.LISTINGS || [];
      const byId = new Map(ls.map((l) => [String(l.id), l]));
      const found = [];
      const missing = [];
      favIds.forEach((id) => {
        const l = byId.get(String(id));
        if (l) found.push(l); else missing.push(id);
      });
      // Tri par score décroissant (même défaut que l'écran principal).
      found.sort((a, b) => (b.score || 0) - (a.score || 0));
      return { found, missing };
    }, [favIds]);

    const removeFav = (id) => {
      if (window.vestoraFavorites) window.vestoraFavorites.toggle(id);
    };

    return (
      <div className="alerts-page">
        {/* Header (réutilise les styles alerts-page) */}
        <div className="alerts-page-header">
          <button className="btn btn-ghost" onClick={onBack}>← {FR ? 'Retour' : 'Back'}</button>
          <div className="alerts-page-hero">
            <h1 className="alerts-page-title">{FR ? 'Mes favoris' : 'My favorites'}</h1>
            <p className="alerts-page-subtitle">
              {FR
                ? 'Les biens que vous suivez, triés par score.'
                : 'The listings you track, sorted by score.'}
            </p>
          </div>
        </div>

        {/* Statut sync */}
        <div className="alerts-banner">
          <div style={{
            background: 'var(--bg-warm, #f9f9f6)',
            border: '1px solid var(--line, #e8e8e0)',
            borderRadius: 10,
            padding: '10px 14px',
            fontSize: 13,
            color: 'var(--ink-2, #666)',
            maxWidth: 680,
            display: 'flex', alignItems: 'center', gap: 8,
          }}>
            <span>{cloudSynced ? '☁️' : '💾'}</span>
            <span>
              {cloudSynced
                ? (FR
                  ? 'Favoris synchronisés sur tous vos appareils (cloud).'
                  : 'Favorites synced across your devices (cloud).')
                : (FR
                  ? 'Favoris sauvegardés sur cet appareil. La sync multi-appareils est incluse dès le plan Investisseur.'
                  : 'Favorites saved on this device. Multi-device sync is included from the Investor plan.')}
            </span>
          </div>
        </div>

        <div className="alerts-list-container">
          {found.length === 0 && missing.length === 0 ? (
            <div className="alerts-empty">
              <div className="alerts-empty-icon" style={{ fontSize: 42 }}>♥</div>
              <p className="alerts-empty-title">{FR ? 'Aucun favori' : 'No favorites yet'}</p>
              <p className="alerts-empty-sub">
                {FR
                  ? 'Cliquez le cœur sur une fiche pour la suivre ici.'
                  : 'Click the heart on a listing to track it here.'}
              </p>
              <button
                className="btn"
                onClick={() => window.navigateTo('#/')}
                style={{
                  marginTop: 16, padding: '10px 22px',
                  background: 'var(--accent, oklch(0.36 0.07 155))',
                  color: '#fff', border: 'none', borderRadius: 8,
                  fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit', fontSize: 14,
                }}
              >
                {FR ? 'Explorer les annonces' : 'Browse listings'}
              </button>
            </div>
          ) : (
            <div className="alerts-list">
              {found.map((l) => (
                <div key={l.id} className="alert-card">
                  <div className="alert-card-body">
                    <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12, flex: 1, minWidth: 0 }}>
                      {/* Score badge */}
                      <div style={{
                        flexShrink: 0, minWidth: 40, textAlign: 'center',
                        background: 'var(--accent-soft, oklch(0.36 0.07 155 / 0.12))',
                        color: 'var(--accent-ink, oklch(0.30 0.07 155))',
                        borderRadius: 8, padding: '6px 8px',
                        fontWeight: 700, fontSize: 15,
                      }}>
                        {Math.round(l.score || 0)}
                      </div>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div className="alert-card-name" style={{ cursor: 'pointer' }}
                          onClick={() => window.navigateTo('#/analyze/' + encodeURIComponent(l.id))}>
                          {l.address || l.city}
                        </div>
                        <div className="alert-card-meta">
                          <span>{l.city}</span>
                          <span className="alert-card-dot">·</span>
                          <span>{fmtMoney(l.price)}</span>
                          {l.units > 0 && (
                            <>
                              <span className="alert-card-dot">·</span>
                              <span>{l.units} {FR ? 'logement' : 'unit'}{l.units > 1 ? 's' : ''}</span>
                            </>
                          )}
                        </div>
                      </div>
                    </div>
                    <div className="alert-card-actions">
                      <button
                        className="alert-action-btn"
                        onClick={() => window.navigateTo('#/analyze/' + encodeURIComponent(l.id))}
                      >
                        {FR ? 'Analyser' : 'Analyze'}
                      </button>
                      <button
                        className="alert-action-btn alert-action-btn--danger"
                        onClick={() => removeFav(l.id)}
                        title={FR ? 'Retirer des favoris' : 'Remove from favorites'}
                      >
                        ♥ {FR ? 'Retirer' : 'Remove'}
                      </button>
                    </div>
                  </div>
                </div>
              ))}

              {/* Favoris dont l'annonce n'est plus en ligne */}
              {missing.length > 0 && (
                <div style={{
                  marginTop: 12, fontSize: 12.5, color: 'var(--ink-3, #999)',
                  padding: '10px 14px',
                  border: '1px dashed var(--line, #e8e8e0)', borderRadius: 10,
                }}>
                  {FR
                    ? `${missing.length} favori${missing.length > 1 ? 's' : ''} dont l'annonce a été retirée du marché.`
                    : `${missing.length} favorite${missing.length > 1 ? 's' : ''} whose listing left the market.`}
                  {' '}
                  <button
                    onClick={() => missing.forEach((id) => removeFav(id))}
                    style={{
                      background: 'none', border: 'none', padding: 0,
                      color: 'var(--ink-3, #999)', textDecoration: 'underline',
                      cursor: 'pointer', fontSize: 12.5, fontFamily: 'inherit',
                    }}
                  >
                    {FR ? 'Nettoyer' : 'Clean up'}
                  </button>
                </div>
              )}
            </div>
          )}
        </div>
      </div>
    );
  }

  window.FavoritesPage = FavoritesPage;
})();
