// transparency.jsx — Radical transparency: invoice viewer, comparisons, anomaly detection

// Compute per-category averages across all participating apartments
function computeCategoryAverages(state) {
  const out = {};
  const apts = state.apartments.filter(a => a.is_active);
  window.CATEGORIES.forEach(cat => {
    const participating = apts.filter(a => window.aptParticipates(a, cat).participates);
    const amounts = participating.map(a => state.charges[a.id]?.breakdown[cat.id]?.amount || 0);
    const total = amounts.reduce((s, v) => s + v, 0);
    out[cat.id] = {
      avg: amounts.length > 0 ? total / amounts.length : 0,
      max: Math.max(...amounts, 0),
      min: Math.min(...amounts, Infinity),
      participating: participating.length,
    };
  });
  return out;
}

// Mock historic data for anomaly detection (per apt per category)
function getHistoricAverage(aptId, catId) {
  // Use a deterministic hash for consistent mock values
  const seed = (aptId + catId).split('').reduce((s, c) => s + c.charCodeAt(0), 0);
  const variance = 0.9 + ((seed % 30) / 100); // 0.9 - 1.2
  return variance;
}

// Check if a value is anomalous (more than 1.6× historic average)
function isAnomaly(aptId, catId, currentAmount, categoryAvg) {
  if (currentAmount < 20) return null;
  if (!categoryAvg || categoryAvg < 5) return null; // not enough signal
  const historicMultiplier = getHistoricAverage(aptId, catId);
  const expected = categoryAvg * historicMultiplier;
  if (currentAmount > expected * 1.6) return { type: 'high', expected, ratio: currentAmount / expected };
  return null;
}

// ═════════════════════════════════════════════════════════════
// Comparison badge — shown next to amount in breakdown
// ═════════════════════════════════════════════════════════════
function ComparisonBadge({ amount, avg, small }) {
  if (!avg || avg <= 0) return null;
  const diff = ((amount - avg) / avg) * 100;
  if (Math.abs(diff) < 5) return null; // not meaningful
  const isHigh = diff > 0;
  const colorBg = isHigh ? '#FEE2E2' : '#D1FAE5';
  const colorFg = isHigh ? '#991B1B' : '#065F46';
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 3,
      padding: small ? '1px 5px' : '2px 7px',
      borderRadius: 999,
      background: colorBg, color: colorFg,
      fontSize: small ? 9.5 : 10.5, fontWeight: 700,
      fontFamily: 'var(--font-mono)',
    }}>
      {isHigh ? '↑' : '↓'} {Math.abs(diff).toFixed(0)}%
    </span>
  );
}

// ═════════════════════════════════════════════════════════════
// Anomaly alert — top of tenant home
// ═════════════════════════════════════════════════════════════
function AnomalyAlerts({ charges, aptId, lang, onExplain, averages }) {
  const avgs = averages || window.__catAverages || {};
  const alerts = [];

  if (charges?.breakdown) {
    Object.entries(charges.breakdown).forEach(([catId, entry]) => {
      const catAvg = avgs[catId]?.avg || 0;
      const a = isAnomaly(aptId, catId, entry.amount, catAvg);
      if (a) {
        alerts.push({ catId, entry, anomaly: a, catAvg });
      }
    });
  }

  if (alerts.length === 0) return null;

  return (
    <div style={{
      padding: 14, borderRadius: 12,
      background: 'linear-gradient(135deg, #FEF3C7, #FDE68A)',
      border: '1.5px solid #F59E0B',
      marginBottom: 16,
      display: 'flex', alignItems: 'flex-start', gap: 12,
    }}>
      <div style={{
        width: 36, height: 36, borderRadius: 10, flexShrink: 0,
        background: '#F59E0B', color: '#fff',
        display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 18,
      }}>⚠️</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13, fontWeight: 700, color: '#92400E', marginBottom: 4 }}>
          {lang === 'ro' ? 'Sume neobișnuite luna asta' : 'Unusual amounts this month'}
        </div>
        {alerts.map(({ catId, entry, anomaly }) => (
          <button key={catId} onClick={() => onExplain && onExplain(catId)} style={{
            display: 'block', width: '100%', textAlign: 'left',
            background: 'transparent', border: 0, padding: '4px 0',
            fontSize: 12.5, color: '#92400E', cursor: 'pointer', fontFamily: 'inherit', lineHeight: 1.5,
          }}>
            <span>{entry.category.icon} <b>{entry.category.name}</b>: {window.fmtRON(entry.amount)} — </span>
            <span style={{ textDecoration: 'underline' }}>
              {lang === 'ro'
                ? `cu ${anomaly.ratio.toFixed(1)}× peste media ta`
                : `${anomaly.ratio.toFixed(1)}× over your average`}
            </span>
          </button>
        ))}
      </div>
    </div>
  );
}

// ═════════════════════════════════════════════════════════════
// Invoice viewer modal — click on any line opens this
// ═════════════════════════════════════════════════════════════
function InvoiceViewer({ open, onClose, entry, expenses, state, apt, lang }) {
  if (!open || !entry) return null;
  const cat = entry.category;
  // Find expenses in this category
  const catExpenses = expenses.filter(e => e.category_id === cat.id);

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 95,
      background: 'rgba(28, 22, 12, 0.55)', backdropFilter: 'blur(8px)',
      display: 'flex', alignItems: 'flex-end', justifyContent: 'center',
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        width: 'min(440px, 100%)', background: 'var(--surface)',
        borderRadius: '24px 24px 0 0', padding: 24,
        boxShadow: '0 -12px 40px rgba(28, 22, 12, 0.25)',
        maxHeight: '92vh', overflowY: 'auto',
      }}>
        <div style={{ width: 40, height: 4, background: 'var(--border)', borderRadius: 999, margin: '0 auto 16px' }} />

        {/* Header */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 18 }}>
          <div style={{
            width: 46, height: 46, borderRadius: 12,
            background: cat.color + '22', color: cat.color,
            display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 22,
          }}>{cat.icon}</div>
          <div style={{ flex: 1 }}>
            <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 17, fontWeight: 600, color: 'var(--ink)', margin: 0 }}>{cat.name}</h3>
            <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 2 }}>
              {lang === 'ro' ? 'Sumă pe apartamentul tău' : 'Your apartment share'}: <b style={{ color: 'var(--primary)', fontFamily: 'var(--font-mono)' }}>{window.fmtRON(entry.amount)}</b>
            </div>
          </div>
        </div>

        {/* Formula */}
        <div style={{
          padding: 14, borderRadius: 12,
          background: 'var(--primary-light)',
          marginBottom: 16,
        }}>
          <div style={{ fontSize: 11, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600, marginBottom: 6 }}>
            {lang === 'ro' ? 'Cum s-a calculat' : 'How calculated'}
          </div>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 13, color: 'var(--ink)', lineHeight: 1.5 }}>
            {entry.formula}
          </div>
          <div style={{ marginTop: 8, fontSize: 12, color: 'var(--ink-2)', lineHeight: 1.5 }}>
            ℹ {cat.why}
          </div>
        </div>

        {/* Source invoices */}
        <div style={{ fontSize: 11, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600, marginBottom: 8 }}>
          {lang === 'ro' ? `${catExpenses.length} factur${catExpenses.length === 1 ? 'ă' : 'i'} sursă` : `${catExpenses.length} source invoice${catExpenses.length === 1 ? '' : 's'}`}
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {catExpenses.map(exp => (
            <InvoiceCard key={exp.id} exp={exp} lang={lang} />
          ))}
        </div>

        {/* Comparison */}
        <div style={{ marginTop: 16, padding: 14, borderRadius: 12, background: 'var(--surface-2)' }}>
          <div style={{ fontSize: 11, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600, marginBottom: 8 }}>
            {lang === 'ro' ? 'Compari cu vecinii' : 'Compare with neighbors'}
          </div>
          <NeighborComparison catId={cat.id} aptId={apt.id} state={state} lang={lang} />
        </div>

        <Button variant="secondary" full onClick={onClose} style={{ marginTop: 14 }}>
          {lang === 'ro' ? 'Închide' : 'Close'}
        </Button>
      </div>
    </div>
  );
}

function InvoiceCard({ exp, lang }) {
  return (
    <div style={{
      padding: '12px 14px', borderRadius: 12,
      background: 'var(--surface-2)', border: '1px solid var(--border)',
    }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
        <div style={{
          width: 44, height: 56, borderRadius: 6, flexShrink: 0,
          background: 'linear-gradient(160deg, #fff, #f5f0e6)',
          border: '1px solid var(--border)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 22, color: 'var(--muted)',
          boxShadow: '0 1px 2px rgba(28, 22, 12, 0.06)',
        }}>📄</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink)', lineHeight: 1.3 }}>{exp.description}</div>
          <div style={{ fontSize: 11.5, color: 'var(--muted)', marginTop: 4 }}>
            {exp.supplier} · {lang === 'ro' ? 'Factura' : 'Invoice'} {exp.invoice_number}
          </div>
          <div style={{ marginTop: 6, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 14, fontWeight: 700, color: 'var(--primary)' }}>
              {window.fmtRON(exp.amount)}
            </span>
            <button style={{
              padding: '4px 10px', borderRadius: 6,
              background: 'transparent', border: '1px solid var(--border)', color: 'var(--ink-2)',
              fontSize: 11, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit',
              display: 'inline-flex', alignItems: 'center', gap: 4,
            }}>
              <Icon name="download" size={11} />
              {lang === 'ro' ? 'PDF' : 'PDF'}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

function NeighborComparison({ catId, aptId, state, lang }) {
  const myAmount = state.charges[aptId]?.breakdown[catId]?.amount || 0;
  const cat = window.CATEGORIES.find(c => c.id === catId);
  const all = state.apartments
    .filter(a => a.is_active && window.aptParticipates(a, cat).participates)
    .map(a => ({
      apt: a,
      amount: state.charges[a.id]?.breakdown[catId]?.amount || 0,
    }))
    .sort((a, b) => a.amount - b.amount);

  const max = Math.max(...all.map(x => x.amount), 1);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
      {all.map(({ apt: a, amount }) => {
        const isMe = a.id === aptId;
        const pct = (amount / max) * 100;
        return (
          <div key={a.id} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 11 }}>
            <span style={{
              width: 22, fontFamily: 'var(--font-mono)', fontWeight: isMe ? 700 : 500,
              color: isMe ? 'var(--primary)' : 'var(--muted)',
              textAlign: 'right',
            }}>{a.number}</span>
            <div style={{ flex: 1, height: 14, position: 'relative' }}>
              <div style={{
                position: 'absolute', left: 0, top: 0, bottom: 0,
                width: `${pct}%`, minWidth: 4,
                background: isMe ? 'var(--primary)' : 'var(--neutral-bg)',
                borderRadius: 4,
              }} />
            </div>
            <span style={{
              width: 60, textAlign: 'right',
              fontFamily: 'var(--font-mono)', fontWeight: isMe ? 700 : 500,
              color: isMe ? 'var(--ink)' : 'var(--muted)',
            }}>
              {window.fmtRON(amount)}
            </span>
          </div>
        );
      })}
    </div>
  );
}

Object.assign(window, {
  computeCategoryAverages, isAnomaly,
  ComparisonBadge, AnomalyAlerts, InvoiceViewer,
});
