(() => {
const { EntityHeader, SummaryStrip, Tabs, DataTable, Money, StatusBadge, Button, Timeline, KeyValueList, Alert } = window.AmlakPlusDesignSystem_b3aa85;

// Confirmed payments are allocated oldest-first (current app rule). Pending payments never reduce the balance.
function allocate(charges, payments) {
  const out = charges.map((c) => ({ ...c }));
  payments.filter((p) => p.status === 'confirmed').forEach((p) => {
    let left = p.amount;
    for (const c of out) { if (left <= 0) break; const need = c.amount - c.paid; if (need <= 0) continue; const take = Math.min(need, left); c.paid += take; left -= take; }
  });
  return out.map((c) => ({ ...c, remaining: c.amount - c.paid, status: c.amount - c.paid === 0 ? 'paid' : c.future ? 'future' : c.paid > 0 ? 'partial' : 'overdue' }));
}
function previewAllocation(charges, amount) {
  let left = amount; const rows = [];
  for (const c of charges) { if (left <= 0) break; const need = c.amount - c.paid; if (need <= 0) continue; const take = Math.min(need, left); rows.push({ period: c.period, take, after: need - take, future: c.future }); left -= take; }
  return { rows, unallocated: left };
}

function LeaseScreen({ payments, openPayment, openReceipt, confirmPayment, go, initialTab }) {
  const L = window.AP_DATA.lease;
  const [tab, setTab] = React.useState(initialTab || 'charges');
  const needsReview = window.leaseNeedsReview && window.leaseNeedsReview(L);
  const [fc, setFc] = React.useState(false);
  const [, setTick] = React.useState(0);
  const charges = allocate(L.charges, payments);
  const overdue = charges.filter((c) => !c.future).reduce((s, c) => s + c.remaining, 0);
  const future = charges.filter((c) => c.future).reduce((s, c) => s + c.remaining, 0);
  const pending = payments.filter((p) => p.status === 'pending').reduce((s, p) => s + p.amount, 0);
  const allPayments = [...payments].reverse().concat(L.history || []);
  return (
    <>
      <EntityHeader back={{ label: 'العودة إلى متابعات اليوم', onClick: (e) => { e.preventDefault(); go('today'); } }} kind="عقد إيجار · سكني" kindIcon="FileText"
        title={L.tenant} status={<StatusBadge status={L.status || 'active'} />} subtitle={<>{L.property} · وحدة {L.unit} · المالك: <a href="#" onClick={(e) => { e.preventDefault(); go('owner', { id: L.ownerId }); }}>{L.owner}</a></>}
        facts={[{ label: 'المدة', value: <bdi className="ap-num">{L.start} – {L.end}</bdi> }, { label: 'الإيجار السنوي', value: <Money value={L.rent} /> }, { label: 'الدفع', value: L.cycle }, { label: 'الجوال', value: <bdi className="ap-num">{L.phone}</bdi> }, { label: 'إيجار', value: L.ejar }]}
        actions={<><Button variant="secondary" icon="Phone" onClick={() => window.apOpen('contact', { tenant: L.tenant, property: L.property, unit: L.unit })}>تسجيل تواصل</Button><Button variant="secondary" icon="RotateCcw" onClick={() => window.apOpen('renew', { tenant: L.tenant, property: L.property, unit: L.unit, rent: L.rent, cycle: L.cycle })}>تجديد</Button><Button variant="ghost" icon="LogOut" onClick={() => window.apOpen('endLease', { tenant: L.tenant, property: L.property, unit: L.unit, overdue: overdue })}>إنهاء</Button><Button icon="Banknote" onClick={openPayment}>تسجيل دفعة</Button></>} />
      <SummaryStrip style={{ marginTop: 16 }} items={[
        { label: 'متأخر حتى اليوم', amount: overdue, tone: overdue ? 'danger' : 'success', note: overdue ? charges.filter((c) => !c.future && c.remaining).map((c) => c.period.split(' ')[0]).join(' · ') : 'لا متأخرات' },
        { label: 'بانتظار التحقق', amount: pending, tone: 'neutral', note: pending ? 'لا يُخصم حتى التأكيد' : 'لا توجد' },
        L.promise ? { label: 'وعد سداد', amount: L.promise, tone: 'info', note: 'حتى 23/09 — جزء من المتأخر' } : { label: 'وعد سداد', amount: 0, tone: 'neutral', note: 'لا يوجد' },
        { label: 'أقساط قادمة', amount: future, tone: 'brand', note: 'ليست دينًا بعد' }
      ]} />
      {needsReview && tab !== 'review' && <Alert tone="warning" style={{ marginTop: 14 }} actions={<Button size="sm" variant="secondary" icon="FileCheck" onClick={() => setTab('review')}>فتح مراجعة إيجار</Button>}>العقد يقترب من الانتهاء — راجع الرصيد في إيجار قبل التجديد أو الإنهاء.</Alert>}
      <Tabs style={{ marginTop: 20 }} label="أقسام العقد" value={tab} onChange={setTab} tabs={[{ id: 'charges', label: 'الاستحقاقات', count: charges.length }, { id: 'payments', label: 'الدفعات', count: allPayments.length }, { id: 'events', label: 'المتابعات والأحداث' }, { id: 'funds', label: 'التأمين والمقدم' }, { id: 'review', label: needsReview ? 'مراجعة إيجار •' : 'مراجعة إيجار' }, { id: 'info', label: 'بيانات العقد' }]} />
      <div style={{ marginTop: 16 }}>
        {tab === 'charges' && <DataTable caption="استحقاقات العقد" rows={charges} footer columns={[
          { key: 'period', header: 'الفترة', render: (c) => <><span className="ap-cell-strong">{c.period}</span><small>يستحق <bdi className="ap-num">{c.due}</bdi></small></> },
          { key: 'amount', header: 'القيمة', numeric: true, render: (c) => <Money value={c.amount} />, footer: <Money value={charges.reduce((s, c) => s + c.amount, 0)} /> },
          { key: 'paid', header: 'المسدد (مؤكد)', numeric: true, render: (c) => <Money value={c.paid} tone={c.paid ? undefined : 'muted'} /> },
          { key: 'remaining', header: 'المتبقي', numeric: true, render: (c) => <Money value={c.remaining} tone={c.remaining && !c.future ? 'danger' : 'muted'} />, footer: <Money value={overdue} tone="danger" /> },
          { key: 'status', header: 'الحالة', render: (c) => <StatusBadge size="sm" status={c.status} /> }
        ]} />}
        {tab === 'charges' && <p className="kit-scope" style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>إجمالي «المتبقي» في التذييل يشمل المتأخر فقط؛ الأقساط القادمة ({future.toLocaleString('en-US')} ر.س) لا تُحتسب.<Button size="sm" variant="ghost" icon="Pencil" onClick={() => setFc(true)}>تغيير مالي</Button></p>}
        {tab === 'funds' && window.LeaseFundsPanel && <window.LeaseFundsPanel L={L} />}
        {tab === 'payments' && <DataTable caption="دفعات العقد" rows={allPayments} columns={[
          { key: 'date', header: 'التاريخ', render: (p) => <bdi className="ap-num">{p.date}</bdi> },
          { key: 'amount', header: 'المبلغ', numeric: true, render: (p) => <Money value={p.amount} struck={p.status === 'reversed'} /> },
          { key: 'method', header: 'الطريقة وجهة الاستلام', render: (p) => <>{p.method}<small>{p.recipientLabel}</small></> },
          { key: 'status', header: 'الحالة', render: (p) => <StatusBadge size="sm" status={p.status} /> },
          { key: 'by', header: 'سجلها', render: (p) => p.by },
          { key: 'act', header: '', render: (p) => p.status === 'confirmed' ? <Button size="sm" variant="secondary" icon="Printer" onClick={() => openReceipt(p)}>السند {p.receipt}</Button> : p.status === 'pending' ? <Button size="sm" variant="secondary" icon="ShieldCheck" onClick={() => confirmPayment(p.id)}>مراجعة وتأكيد</Button> : null }
        ]} />}
        {tab === 'events' && <div className="kit-panel"><Timeline events={[...payments.slice().reverse().map((p) => ({ title: (p.status === 'confirmed' ? 'تأكدت دفعة ' : 'سُجلت دفعة ') + p.amount.toLocaleString('en-US') + ' ر.س', date: p.date, actor: p.by, tone: p.status === 'confirmed' ? 'success' : 'warning', icon: p.status === 'confirmed' ? 'ShieldCheck' : 'Hourglass', body: p.status === 'pending' ? 'بانتظار تحقق المحاسب من الاستلام.' : 'سند ' + p.receipt })), ...L.events]} /></div>}
        {tab === 'review' && window.LeaseEjarReview && <window.LeaseEjarReview L={L} payments={payments} />}
        {tab === 'info' && <div className="kit-panel"><KeyValueList items={[{ label: 'المستأجر', value: L.tenant }, { label: 'النوع', value: L.tenantType }, { label: 'رقم الهوية', value: <bdi className="ap-num">{L.nationalId}</bdi> }, { label: 'العقار', value: L.property }, { label: 'الوحدة', value: L.unit }, { label: 'دورة الدفع', value: L.cycle }]} />
          <Alert tone="neutral" style={{ marginTop: 16 }} actions={<Button size="sm" variant="secondary" icon="Pencil" onClick={() => setFc(true)}>تغيير مالي</Button>}>تعديل بيانات العقد لا يعيد كتابة الاستحقاقات أو الدفعات السابقة؛ التغييرات المالية تتم عبر مسار «تغيير مالي» مستقل يحفظ الأثر.</Alert></div>}
      </div>
      {fc && window.FinanceChangeDialog && <window.FinanceChangeDialog L={L} onClose={() => setFc(false)} onSaved={() => { setFc(false); setTick((x) => x + 1); }} />}
    </>
  );
}

Object.assign(window, { LeaseScreen, allocate, previewAllocation });

})();
