// OpexBenchmarkBadge.jsx — Badge "OpEx normalisée" cliquable
//
// Affiche un petit badge a cote des KPI (cap rate, cash-flow, NOI) quand
// les depenses d'exploitation ont ete reconstruites a partir des benchmarks
// Vestora (ville x taille x ere de construction).
//
// Convention Vestora :
//   - PAS d'import/export ES (Babel in-browser, React global)
//   - Composant expose sur window pour reutilisation depuis Drawer, AnalyzePage
//
// Props :
//   listing : objet listing (besoin de opexEstimated / opexBreakdown / opexDeclaredTotal)
//   lang    : 'fr' | 'en' (defaut 'fr')
//   compact : boolean — version compacte (juste pastille, defaut false)

(function () {
  const { useState: useS, useRef: useR, useEffect: useE } = React;

  // CSS injecte une seule fois
  const STYLE_ID = 'opex-benchmark-badge-styles';
  if (typeof document !== 'undefined' && !document.getElementById(STYLE_ID)) {
    const style = document.createElement('style');
    style.id = STYLE_ID;
    style.textContent = `
.opex-bench-badge {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 2px 7px;
  font-size: 11px;
  font-weight: 600;
  border-radius: 10px;
  background: #fef3c7;
  color: #b45309;
  border: 1px solid #fcd34d;
  cursor: help;
  vertical-align: middle;
  white-space: nowrap;
  line-height: 1.2;
}
.opex-bench-badge:hover { background: #fde68a; }
.opex-bench-badge.compact {
  padding: 1px 5px;
  font-size: 10px;
}
.opex-bench-tooltip {
  position: absolute;
  z-index: 10000;
  background: #1f2937;
  color: #f9fafb;
  font-size: 12px;
  font-weight: 400;
  padding: 12px 14px;
  border-radius: 8px;
  box-shadow: 0 10px 25px rgba(0,0,0,0.25);
  max-width: 320px;
  min-width: 240px;
  line-height: 1.5;
}
.opex-bench-tooltip h4 {
  margin: 0 0 8px 0;
  font-size: 13px;
  font-weight: 700;
  color: #fbbf24;
}
.opex-bench-tooltip table {
  width: 100%;
  border-collapse: collapse;
  margin: 6px 0;
}
.opex-bench-tooltip td {
  padding: 3px 0;
  font-size: 11px;
}
.opex-bench-tooltip td:last-child {
  text-align: right;
  font-variant-numeric: tabular-nums;
  color: #d1d5db;
}
.opex-bench-tooltip .footer {
  margin-top: 8px;
  padding-top: 8px;
  border-top: 1px solid #374151;
  font-size: 11px;
  color: #9ca3af;
}
.opex-bench-tooltip .total-row td {
  font-weight: 700;
  color: #fbbf24;
  border-top: 1px solid #374151;
  padding-top: 6px;
}
`;
    document.head.appendChild(style);
  }

  const LABEL_FR = {
    badge: 'OpEx normalisée',
    title: 'Dépenses normalisées via benchmark Vestora',
    explainer:
      'Les dépenses déclarées par le vendeur étaient absentes ou < 30 % des revenus bruts. ' +
      'Nous avons appliqué les ratios SCHL/APCHQ par ville, taille et ère de construction.',
    declared: 'OpEx déclarées',
    normalized: 'OpEx normalisées',
    breakdown: {
      taxes_municipales: 'Taxes municipales',
      taxes_scolaires: 'Taxes scolaires',
      assurances: 'Assurances',
      entretien: 'Entretien',
      gestion: 'Gestion',
      deneigement: 'Déneigement',
      energie_communs: 'Énergie communs',
      ger: 'Réserve remplacement (GER)',
    },
    impact: "Cap rate et cash-flow ajustés en conséquence.",
  };

  const LABEL_EN = {
    badge: 'Normalized OpEx',
    title: 'Expenses normalized via Vestora benchmark',
    explainer:
      'Seller-declared expenses were missing or below 30% of gross income. ' +
      'We applied CMHC/APCHQ ratios by city, size and construction era.',
    declared: 'Declared OpEx',
    normalized: 'Normalized OpEx',
    breakdown: {
      taxes_municipales: 'Municipal taxes',
      taxes_scolaires: 'School taxes',
      assurances: 'Insurance',
      entretien: 'Maintenance',
      gestion: 'Management',
      deneigement: 'Snow removal',
      energie_communs: 'Common areas energy',
      ger: 'Replacement reserve',
    },
    impact: 'Cap rate and cash-flow adjusted accordingly.',
  };

  function fmtMoney(value) {
    if (value == null || isNaN(value)) return '—';
    return Math.round(value).toLocaleString('fr-CA') + ' $';
  }

  function OpexBenchmarkBadge(props) {
    const listing = props.listing || {};
    const lang = props.lang || 'fr';
    const compact = !!props.compact;
    const L = lang === 'en' ? LABEL_EN : LABEL_FR;

    const isNormalized =
      listing.opexEstimated === true ||
      listing.opexNormalized === true ||
      (listing.metrics && listing.metrics.opexNormalized === true);

    if (!isNormalized) return null;

    const [open, setOpen] = useS(false);
    const [coords, setCoords] = useS({ top: 0, left: 0 });
    const anchorRef = useR(null);

    const breakdown =
      listing.opexBreakdown ||
      (listing.metrics && listing.metrics.opexBreakdown) ||
      null;

    const declared =
      listing.opexDeclaredTotal != null
        ? listing.opexDeclaredTotal
        : listing.metrics && listing.metrics.opexDeclaredTotal != null
        ? listing.metrics.opexDeclaredTotal
        : null;

    const totalNormalized = breakdown
      ? Object.values(breakdown).reduce((a, b) => a + (Number(b) || 0), 0)
      : null;

    useE(() => {
      if (!open || !anchorRef.current) return;
      const rect = anchorRef.current.getBoundingClientRect();
      // Positionne le tooltip sous le badge, calé à gauche.
      const left = Math.max(8, Math.min(rect.left, window.innerWidth - 340));
      const top = rect.bottom + 6;
      setCoords({ top, left });
    }, [open]);

    function handleClick(e) {
      e.stopPropagation();
      setOpen(o => !o);
    }

    useE(() => {
      if (!open) return;
      function onDocClick(e) {
        if (anchorRef.current && anchorRef.current.contains(e.target)) return;
        setOpen(false);
      }
      document.addEventListener('mousedown', onDocClick);
      return () => document.removeEventListener('mousedown', onDocClick);
    }, [open]);

    const badge = React.createElement(
      'span',
      {
        ref: anchorRef,
        className: 'opex-bench-badge' + (compact ? ' compact' : ''),
        onClick: handleClick,
        title: L.title,
        role: 'button',
        tabIndex: 0,
        onKeyDown: e => {
          if (e.key === 'Enter' || e.key === ' ') {
            e.preventDefault();
            handleClick(e);
          }
        },
      },
      '⚖️ ',
      L.badge
    );

    if (!open) return badge;

    const rows = breakdown
      ? Object.keys(L.breakdown).map(key => {
          const value = breakdown[key];
          if (value == null) return null;
          return React.createElement(
            'tr',
            { key },
            React.createElement('td', null, L.breakdown[key]),
            React.createElement('td', null, fmtMoney(value))
          );
        })
      : null;

    const tooltip = React.createElement(
      'div',
      {
        className: 'opex-bench-tooltip',
        style: { top: coords.top, left: coords.left },
        onClick: e => e.stopPropagation(),
      },
      React.createElement('h4', null, L.title),
      React.createElement('p', { style: { margin: 0, fontSize: 11 } }, L.explainer),
      rows
        ? React.createElement(
            'table',
            null,
            React.createElement('tbody', null,
              rows,
              React.createElement(
                'tr',
                { className: 'total-row' },
                React.createElement('td', null, L.normalized),
                React.createElement('td', null, fmtMoney(totalNormalized))
              )
            )
          )
        : null,
      declared != null
        ? React.createElement(
            'div',
            { className: 'footer' },
            L.declared + ' : ' + fmtMoney(declared)
          )
        : null,
      React.createElement(
        'div',
        { className: 'footer', style: { fontStyle: 'italic' } },
        L.impact
      )
    );

    return React.createElement(
      React.Fragment,
      null,
      badge,
      ReactDOM.createPortal(tooltip, document.body)
    );
  }

  window.OpexBenchmarkBadge = OpexBenchmarkBadge;
})();
