// ComparePage — comparateur côte-à-côte jusqu'à 4 biens
// Sprint 2 PR5 : full paywall si tier < investisseur

const { useState: useStateCP, useMemo: useMemoCP, useEffect: useEffectCP } = React;

function ComparePage({ compareIds, onRemove, onClear, onBack, lang, t, activeProfile }) {
  const listings = useMemoCP(() => {
    const all = window.LISTINGS || [];
    return compareIds.map(id => all.find(l => String(l.id) === String(id))).filter(Boolean);
  }, [compareIds]);

  // Gating tier — page réservée au plan Investisseur+
  const [userTier, setUserTier] = useStateCP('decouverte');
  const [paywallDismissed, setPaywallDismissed] = useStateCP(false);

  useEffectCP(() => {
    const tg = window.vestora?.tierGate;
    if (tg && typeof tg.getCurrentTier === 'function') {
      tg.getCurrentTier().then(t => setUserTier(t));
    }
  }, []);

  const comparePageLocked = window.vestora?.tierGate
    ? !window.vestora?.tierGate.canAccess('compare_page', userTier)
    : false;

  const fmt = window.fmt;

  // ── helpers ──────────────────────────────────────────────────────────────────
  function profileScore(listing) {
    return listing.scoresByProfile?.[activeProfile]?.score ?? listing.score;
  }

  const fr = lang === 'fr';

  // ── Paywall — full page gate (Sprint 2 PR5) ───────────────────────────────────
  if (comparePageLocked) {
    return (
      <div style={{
        position: 'relative', minHeight: '100vh',
        background: 'var(--bg, #fafaf9)', overflow: 'hidden',
        fontFamily: 'var(--font-body)',
      }}>
        {/* Preview floutée du header */}
        <div style={{
          filter: 'blur(4px)', pointerEvents: 'none', userSelect: 'none',
          opacity: 0.45, padding: '14px 24px', borderBottom: '1px solid var(--border)',
          background: 'var(--surface, #fff)',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        }}>
          <h1 style={{ margin: 0, fontSize: 18, fontFamily: 'var(--font-head)', fontWeight: 500 }}>
            {fr ? 'Comparaison côte-à-côte' : 'Side-by-side comparison'}
          </h1>
          <div style={{ display: 'flex', gap: 24, fontSize: 13, color: 'var(--ink-3)' }}>
            <span>Prix</span><span>Cap rate</span><span>Cash flow</span><span>IRR</span>
          </div>
        </div>
        {/* Fake rows floutées */}
        <div style={{ filter: 'blur(5px)', pointerEvents: 'none', userSelect: 'none', opacity: 0.35, padding: 24 }}>
          {[1,2,3,4,5].map(i => (
            <div key={i} style={{
              height: 44, background: i % 2 === 0 ? 'var(--surface-2, #f8f8f7)' : 'transparent',
              borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center',
              gap: 24, padding: '0 14px',
            }}>
              <div style={{ width: 180, height: 12, borderRadius: 6, background: 'var(--ink-4, #ccc)' }}/>
              {[1,2,3,4].map(j => <div key={j} style={{ flex: 1, height: 12, borderRadius: 6, background: 'var(--ink-4, #ccc)' }}/>)}
            </div>
          ))}
        </div>
        {/* PaywallModal centré — auto-ouvert, onClose renvoie à l'accueil */}
        {window.PaywallModal && (
          <window.PaywallModal
            open={!paywallDismissed}
            onClose={() => { setPaywallDismissed(true); onBack(); }}
            feature="compare_page"
            featureLabel="Comparateur 4 biens côte-à-côte"
            requiredTier="investisseur"
            currentTier={userTier}
            reason="tier_too_low"
          />
        )}
        {/* Fallback si PaywallModal non chargé */}
        {!window.PaywallModal && (
          <div style={{
            position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column',
            alignItems: 'center', justifyContent: 'center', gap: 16, zIndex: 100,
          }}>
            <div style={{ fontSize: 32 }}>🔒</div>
            <p style={{ textAlign: 'center', maxWidth: 360, color: 'var(--ink-2)' }}>
              {fr ? 'Le comparateur est réservé au plan Investisseur.' : 'Compare page requires an Investor plan.'}
            </p>
            <button onClick={() => window.location.hash = '#/tarifs'}
              style={{ padding: '10px 24px', borderRadius: 8, background: 'var(--brand)', color: '#fff', border: 'none', cursor: 'pointer' }}>
              {fr ? 'Voir les plans' : 'See plans'}
            </button>
            <button onClick={onBack} style={{ fontSize: 13, color: 'var(--ink-3)', background: 'none', border: 'none', cursor: 'pointer' }}>
              {fr ? 'Retour' : 'Back'}
            </button>
          </div>
        )}
      </div>
    );
  }

  // ── Empty state ───────────────────────────────────────────────────────────────
  if (listings.length === 0) {
    return (
      <div style={{
        minHeight: '80vh', display: 'flex', flexDirection: 'column',
        alignItems: 'center', justifyContent: 'center', gap: 16,
        fontFamily: 'var(--font-body)', color: 'var(--ink-2)', textAlign: 'center', padding: 32
      }}>
        <div style={{ fontSize: 48 }}>🔍</div>
        <h2 style={{ color: 'var(--ink-1)', margin: 0, fontFamily: 'var(--font-head)', fontWeight: 500, fontSize: 24 }}>
          {fr ? 'Aucun bien à comparer' : 'No listings to compare'}
        </h2>
        <p style={{ maxWidth: 380, margin: 0, lineHeight: 1.6, color: 'var(--ink-3)' }}>
          {fr
            ? "Ajoute jusqu'à 4 biens depuis leur fiche pour les comparer côte-à-côte."
            : 'Add up to 4 listings from their detail panel to compare them side by side.'}
        </p>
        <button onClick={onBack} style={{
          marginTop: 8, padding: '10px 24px', borderRadius: 8,
          background: 'var(--brand)', color: '#fff', border: 'none',
          cursor: 'pointer', fontWeight: 600, fontSize: 14
        }}>
          {fr ? '← Retour aux annonces' : '← Back to listings'}
        </button>
      </div>
    );
  }

  const n = listings.length;

  // ── Per-row best/worst highlighting ──────────────────────────────────────────
  function highlight(values, higherIsBetter) {
    const nums = values.map((v, i) => v == null ? null : { v, i });
    const valid = nums.filter(x => x !== null);
    if (valid.length < 2) return values.map(() => null);
    const best = higherIsBetter
      ? valid.reduce((a, b) => b.v > a.v ? b : a)
      : valid.reduce((a, b) => b.v < a.v ? b : a);
    const worst = higherIsBetter
      ? valid.reduce((a, b) => b.v < a.v ? b : a)
      : valid.reduce((a, b) => b.v > a.v ? b : a);
    return values.map((v, i) => {
      if (v == null) return null;
      if (i === best.i && best.v !== worst.v) return 'best';
      if (i === worst.i && best.v !== worst.v) return 'worst';
      return null;
    });
  }

  const cellStyle = (hl) => ({
    background: hl === 'best' ? 'rgba(34,197,94,0.12)' : hl === 'worst' ? 'rgba(239,68,68,0.08)' : 'transparent',
    color: hl === 'best' ? 'var(--score-excellent)' : hl === 'worst' ? 'var(--score-avoid)' : 'inherit',
    fontWeight: hl ? 600 : 400,
    padding: '10px 12px',
    textAlign: 'center',
    fontSize: 14,
    borderBottom: '1px solid var(--border)',
    transition: 'background 0.15s',
  });

  const labelCellStyle = {
    padding: '10px 14px',
    fontSize: 12,
    fontWeight: 600,
    color: 'var(--ink-3)',
    textTransform: 'uppercase',
    letterSpacing: '0.04em',
    background: 'var(--surface-2, #f8f8f7)',
    borderBottom: '1px solid var(--border)',
    whiteSpace: 'nowrap',
    position: 'sticky',
    left: 0,
    zIndex: 2,
  };

  const gridStyle = {
    display: 'grid',
    gridTemplateColumns: `180px repeat(${n}, 1fr)`,
    width: '100%',
  };

  // ── Row definitions ───────────────────────────────────────────────────────────
  const rows = [
    {
      key: 'price',
      label: fr ? 'Prix demandé' : 'Asking price',
      values: listings.map(l => l.price),
      render: (l) => fmt.money(l.price, fr ? 'fr-CA' : 'en-CA'),
      higherIsBetter: false,
    },
    {
      key: 'score',
      label: fr ? 'Score investisseur' : 'Investor score',
      values: listings.map(l => profileScore(l)),
      render: (l) => {
        const s = profileScore(l);
        const color = window.scoreColor(s);
        return React.createElement('span', { style: { color, fontWeight: 700 } }, s + '/100');
      },
      higherIsBetter: true,
    },
    {
      key: 'capRate',
      label: 'Cap rate',
      values: listings.map(l => l.metrics?.capRate ?? null),
      render: (l) => l.metrics?.capRate != null ? fmt.pct(l.metrics.capRate) : '—',
      higherIsBetter: true,
    },
    {
      key: 'cashFlow',
      label: fr ? 'Cash flow annuel' : 'Annual cash flow',
      values: listings.map(l => l.metrics?.cashFlow ?? null),
      render: (l) => {
        const cf = l.metrics?.cashFlow;
        if (cf == null) return '—';
        return (cf > 0 ? '+' : '') + fmt.moneyShort(cf);
      },
      higherIsBetter: true,
    },
    {
      key: 'dscr',
      label: 'DSCR',
      values: listings.map(l => l.metrics?.dscr ?? null),
      render: (l) => l.metrics?.dscr != null ? l.metrics.dscr.toFixed(2) : '—',
      higherIsBetter: true,
    },
    {
      key: 'irr',
      label: fr ? 'IRR 10 ans (est.)' : 'IRR 10yr (est.)',
      values: listings.map(l => l.metrics?.irr ?? null),
      render: (l) => l.metrics?.irr != null ? fmt.pct(l.metrics.irr) : '—',
      higherIsBetter: true,
    },
    {
      key: 'downPayment',
      label: fr ? 'Mise de fonds req.' : 'Down payment req.',
      values: listings.map(l => l.price ? l.price * (window.DEFAULT_ASSUMPTIONS?.downPaymentPct ?? 0.20) : null),
      render: (l) => {
        const dp = l.price * (window.DEFAULT_ASSUMPTIONS?.downPaymentPct ?? 0.20);
        return fmt.moneyShort(dp);
      },
      higherIsBetter: false,
    },
    {
      key: 'units',
      label: fr ? 'Logements' : 'Units',
      values: listings.map(l => l.units ?? null),
      render: (l) => l.units ?? '—',
      higherIsBetter: true,
    },
    {
      key: 'rooms',
      label: fr ? 'Ch. / SDB / Superficie' : 'Bed / Bath / Area',
      values: null, // neutral — no highlight
      render: (l) => {
        const parts = [];
        if (l.bedrooms > 0) parts.push(l.bedrooms + ' ch.');
        if (l.bathrooms > 0) parts.push(l.bathrooms + ' sdb');
        if (l.grossArea > 0) parts.push(fmt.num(l.grossArea) + ' pi²');
        return parts.length ? parts.join(' · ') : '—';
      },
    },
    {
      key: 'yearBuilt',
      label: fr ? 'Année construction' : 'Year built',
      values: listings.map(l => l.yearBuilt > 0 ? l.yearBuilt : null),
      render: (l) => l.yearBuilt > 0 ? l.yearBuilt : '—',
      higherIsBetter: true,
    },
    {
      key: 'municipalAssessment',
      label: fr ? 'Évaluation munic.' : 'Municipal assess.',
      values: listings.map(l => l.municipalAssessment ?? null),
      render: (l) => l.municipalAssessment ? fmt.moneyShort(l.municipalAssessment) : '—',
      higherIsBetter: true,
    },
  ];

  const altImages = (l) => [
    'linear-gradient(135deg, ' + l.images[0] + ', ' + l.images[2] + ')',
    'linear-gradient(160deg, ' + l.images[1] + ', ' + l.images[0] + ')',
  ];

  // ── Render ────────────────────────────────────────────────────────────────────
  return (
    <div style={{ fontFamily: 'var(--font-body)', minHeight: '100vh', background: 'var(--bg, #fafaf9)' }}>
      {/* Header */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '14px 24px', borderBottom: '1px solid var(--border)',
        background: 'var(--surface, #fff)', position: 'sticky', top: 0, zIndex: 10,
        boxShadow: '0 1px 4px rgba(0,0,0,0.06)'
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <button onClick={onBack} style={{
            padding: '7px 14px', borderRadius: 7, border: '1px solid var(--border)',
            background: 'transparent', cursor: 'pointer', fontSize: 13, color: 'var(--ink-2)',
            display: 'flex', alignItems: 'center', gap: 6
          }}>
            ← {fr ? 'Retour' : 'Back'}
          </button>
          <h1 style={{
            margin: 0, fontSize: 18, fontFamily: 'var(--font-head)',
            fontWeight: 500, color: 'var(--ink-1)'
          }}>
            {fr ? 'Comparaison (' + n + ')' : 'Compare (' + n + ')'}
          </h1>
        </div>
        <button onClick={onClear} style={{
          padding: '7px 14px', borderRadius: 7, border: '1px solid #fca5a5',
          background: 'rgba(239,68,68,0.06)', cursor: 'pointer', fontSize: 13,
          color: '#dc2626', fontWeight: 500
        }}>
          {fr ? 'Vider la comparaison' : 'Clear all'}
        </button>
      </div>

      {/* Compare table */}
      <div style={{ overflowX: 'auto', padding: '24px 16px' }}>
        <div style={gridStyle}>

          {/* Header row: empty label + listing cards */}
          <div style={{ ...labelCellStyle, background: 'transparent', borderBottom: '2px solid var(--border)' }} />
          {listings.map((l, ci) => (
            <div key={l.id} style={{
              padding: '0 12px 12px',
              borderBottom: '2px solid var(--brand, #2c3e2d)',
              position: 'relative',
              textAlign: 'center',
            }}>
              <button
                onClick={() => onRemove(l.id)}
                aria-label={fr ? 'Retirer' : 'Remove'}
                style={{
                  position: 'absolute', top: 0, right: 4,
                  width: 22, height: 22, borderRadius: '50%',
                  border: '1px solid var(--border)', background: 'var(--surface, #fff)',
                  cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontSize: 11, color: 'var(--ink-3)', lineHeight: 1, zIndex: 1,
                }}
              >✕</button>

              {/* Photo placeholder */}
              <div style={{
                width: '100%', aspectRatio: '4/3', borderRadius: 8,
                background: altImages(l)[0], marginBottom: 10, minWidth: 120,
                position: 'relative', overflow: 'hidden',
              }}>
                <div style={{
                  position: 'absolute', inset: 0,
                  backgroundImage: 'repeating-linear-gradient(45deg, transparent, transparent 4px, rgba(255,255,255,0.04) 4px, rgba(255,255,255,0.04) 8px)'
                }}/>
                <div style={{
                  position: 'absolute', bottom: 6, left: 6,
                  fontSize: 9, color: 'rgba(255,255,255,0.7)',
                  letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 600
                }}>{l.type}</div>
              </div>

              <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink-1)', lineHeight: 1.3, marginBottom: 2 }}>
                {l.address}
              </div>
              <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>
                {[l.neighborhood, l.city].filter(Boolean).join(', ')}
              </div>
            </div>
          ))}

          {/* Data rows */}
          {rows.map(row => {
            const hls = row.values
              ? highlight(row.values, row.higherIsBetter)
              : listings.map(() => null);
            return (
              <React.Fragment key={row.key}>
                <div style={labelCellStyle}>{row.label}</div>
                {listings.map((l, ci) => (
                  <div key={l.id} style={cellStyle(hls[ci])}>
                    {row.render(l)}
                  </div>
                ))}
              </React.Fragment>
            );
          })}

        </div>

        {/* Legend */}
        <div style={{
          marginTop: 24, display: 'flex', gap: 16, justifyContent: 'center',
          fontSize: 12, color: 'var(--ink-3)'
        }}>
          <span style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
            <span style={{ width: 12, height: 12, borderRadius: 3, background: 'rgba(34,197,94,0.2)', display: 'inline-block' }}/>
            {fr ? 'Meilleure valeur' : 'Best value'}
          </span>
          <span style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
            <span style={{ width: 12, height: 12, borderRadius: 3, background: 'rgba(239,68,68,0.12)', display: 'inline-block' }}/>
            {fr ? 'Moins favorable' : 'Least favorable'}
          </span>
        </div>
      </div>
    </div>
  );
}

window.ComparePage = ComparePage;
