/**
 * BillingTab.jsx — Tenant Faturalama Paneli
 * Plan bilgisi, cari ay kullanım, fatura geçmişi
 */
const { useState, useEffect, useCallback } = React;

window.BillingTab = function BillingTab() {
  const [summary, setSummary] = useState(null);
  const [invoices, setInvoices] = useState([]);
  const [loading, setLoading] = useState(true);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const [sumRes, invRes] = await Promise.all([
        authFetch('/api/billing/summary'),
        authFetch('/api/billing/invoices'),
      ]);
      if (sumRes.ok) setSummary(await sumRes.json());
      if (invRes.ok) setInvoices(await invRes.json());
    } catch (e) { console.error('Billing load error:', e); }
    setLoading(false);
  }, []);

  useEffect(() => { load(); }, [load]);

  if (loading) return React.createElement('div', { className: 'billing-loading' }, 'Yükleniyor...');

  const plan = summary?.plan;
  const usage = summary?.current_usage;

  const fmtMoney = (v) =>new Intl.NumberFormat('tr-TR', { style: 'currency', currency: 'TRY' }).format(v || 0);
  const fmtNum = (v) =>new Intl.NumberFormat('tr-TR').format(v || 0);
  const monthNames = ['', 'Ocak', 'Şubat', 'Mart', 'Nisan', 'Mayıs', 'Haziran', 'Temmuz', 'Ağustos', 'Eylül', 'Ekim', 'Kasım', 'Aralık'];

  const minutePct = usage && usage.included_minutes > 0
    ? Math.min(100, (usage.total_minutes / usage.included_minutes) * 100) : 0;
  const callPct = usage && usage.included_calls > 0
    ? Math.min(100, (usage.total_calls / usage.included_calls) * 100) : 0;

  const barColor = (pct) =>pct >= 90 ? 'var(--red)' : pct >= 75 ? 'var(--amber)' : 'var(--blue)';

  const statusBadge = (status) => {
    const map = { draft: '#6b7490', issued: 'var(--amber)', paid: 'var(--green)', cancelled: 'var(--red)' };
    const labelMap = { draft: 'Taslak', issued: 'Kesildi', paid: 'Ödendi', cancelled: 'İptal' };
    return React.createElement('span', {
      className: 'billing-status-badge',
      style: { background: map[status] || '#6b7490' }
    }, labelMap[status] || status);
  };

  return React.createElement('div', { className: 'billing-container' },
    // Plan Card
    React.createElement('div', { className: 'billing-plan-card' },
      React.createElement('div', { className: 'billing-plan-header' },
        React.createElement('div', null,
          React.createElement('h3', { className: 'billing-plan-name' }, plan ? plan.name : 'Plan Atanmamış'),
          plan && React.createElement('div', { className: 'billing-plan-price' },
            fmtMoney(plan.monthly_price),
            React.createElement('span', { className: 'billing-plan-period' }, ' / ay')
          )
        ),
        plan && React.createElement('div', { className: 'billing-plan-badge' }, 'Aktif Plan')
      ),
      plan && React.createElement('div', { className: 'billing-plan-includes' },
        React.createElement('div', { className: 'billing-plan-include-item' },
          React.createElement('span', { className: 'billing-plan-include-val' }, fmtNum(plan.included_minutes)),
          React.createElement('span', { className: 'billing-plan-include-label' }, 'Dahil Dakika')
        ),
        React.createElement('div', { className: 'billing-plan-include-item' },
          React.createElement('span', { className: 'billing-plan-include-val' }, fmtNum(plan.included_calls)),
          React.createElement('span', { className: 'billing-plan-include-label' }, 'Dahil Çağrı')
        ),
        React.createElement('div', { className: 'billing-plan-include-item' },
          React.createElement('span', { className: 'billing-plan-include-val' }, fmtMoney(plan.per_minute_rate)),
          React.createElement('span', { className: 'billing-plan-include-label' }, 'Aşım / dk')
        ),
        React.createElement('div', { className: 'billing-plan-include-item' },
          React.createElement('span', { className: 'billing-plan-include-val' }, fmtMoney(plan.per_call_rate)),
          React.createElement('span', { className: 'billing-plan-include-label' }, 'Aşım / çağrı')
        )
      )
    ),

    // Current Usage
    usage && React.createElement('div', { className: 'billing-usage-section' },
      React.createElement('h3', { className: 'billing-section-title' },
        monthNames[usage.month] + ' ' + usage.year + ' — Cari Kullanım'
      ),
      React.createElement('div', { className: 'billing-usage-grid' },
        // Minutes
        React.createElement('div', { className: 'billing-usage-card' },
          React.createElement('div', { className: 'billing-usage-card-header' },
            React.createElement('span', null, 'Dakika Kullanımı'),
            React.createElement('span', { className: 'billing-usage-val' },
              fmtNum(Math.round(usage.total_minutes)) + ' / ' + fmtNum(usage.included_minutes)
            )
          ),
          React.createElement('div', { className: 'usage-bar' },
            React.createElement('div', {
              className: 'usage-bar-fill',
              style: { width: minutePct + '%', background: barColor(minutePct) }
            })
          ),
          usage.overage_minutes > 0 && React.createElement('div', { className: 'billing-overage-text' },
            fmtNum(Math.round(usage.overage_minutes)) + ' dakika aşım'
          )
        ),
        // Calls
        React.createElement('div', { className: 'billing-usage-card' },
          React.createElement('div', { className: 'billing-usage-card-header' },
            React.createElement('span', null, 'Çağrı Kullanımı'),
            React.createElement('span', { className: 'billing-usage-val' },
              fmtNum(usage.total_calls) + ' / ' + fmtNum(usage.included_calls)
            )
          ),
          React.createElement('div', { className: 'usage-bar' },
            React.createElement('div', {
              className: 'usage-bar-fill',
              style: { width: callPct + '%', background: barColor(callPct) }
            })
          ),
          usage.overage_calls > 0 && React.createElement('div', { className: 'billing-overage-text' },
            fmtNum(usage.overage_calls) + ' çağrı aşım'
          )
        )
      ),
      usage.estimated_overage_cost > 0 && React.createElement('div', { className: 'billing-overage-cost' },
        'Tahmini aşım maliyeti: ',
        React.createElement('strong', null, fmtMoney(usage.estimated_overage_cost))
      )
    ),

    // Invoices
    React.createElement('div', { className: 'billing-invoices-section' },
      React.createElement('h3', { className: 'billing-section-title' }, 'Fatura Geçmişi'),
      invoices.length === 0
        ? React.createElement('div', { className: 'billing-empty' }, 'Henüz fatura bulunmuyor.')
        : React.createElement('table', { className: 'sa-table' },
            React.createElement('thead', null,
              React.createElement('tr', null,
                React.createElement('th', null, 'Fatura No'),
                React.createElement('th', null, 'Dönem'),
                React.createElement('th', null, 'Plan'),
                React.createElement('th', null, 'Tutar'),
                React.createElement('th', null, 'Aşım'),
                React.createElement('th', null, 'Toplam'),
                React.createElement('th', null, 'Durum')
              )
            ),
            React.createElement('tbody', null,
              invoices.map(inv =>
                React.createElement('tr', { key: inv.id },
                  React.createElement('td', { style: { fontFamily: 'var(--mono)', fontSize: 13 } }, inv.invoice_number),
                  React.createElement('td', null, monthNames[inv.month] + ' ' + inv.year),
                  React.createElement('td', null, inv.plan_name),
                  React.createElement('td', null, fmtMoney(inv.base_amount)),
                  React.createElement('td', null, inv.overage_amount > 0 ? fmtMoney(inv.overage_amount) : '—'),
                  React.createElement('td', { style: { fontWeight:600 } }, fmtMoney(inv.total_amount)),
                  React.createElement('td', null, statusBadge(inv.status))
                )
              )
            )
          )
    )
  );
};
