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

function TenantScreen({ tenantId, go, openLease, openPayment, openReceipt, initialTab }) {
  const D = window.AP_DATA;
  const t = D.tenants.find((x) => x.id === tenantId) || D.tenants[0];
  const first = t.name.split(' ')[0];
  const leases = D.leases.filter((l) => t.name.includes(l.tenant.split(' ')[0]) && (l.tenant.split(' ').pop() === t.name.split(' ').pop()));
  const pays = D.payments.filter((p) => t.name.includes(p.tenant.split(' ')[0]));
  const [tab, setTab] = React.useState(initialTab || 'leases');
  const ctx = { tenant: t.name, property: t.property };
  return (
    <>
      <EntityHeader back={{ label: 'العودة إلى المستأجرين', onClick: (e) => { e.preventDefault(); go('tenants'); } }} kind={'مستأجر · ' + t.type} kindIcon="User" title={t.name}
        status={t.leases ? <StatusBadge status="active" label="له عقد نشط" /> : <StatusBadge status="ended" label="غادر" />}
        subtitle={t.property}
        facts={[{ label: 'الجوال', value: num(t.phone) }, { label: 'الهوية / السجل', value: num(t.idNo) }, { label: 'العقود', value: leases.length }]}
        actions={<><Button variant="secondary" icon="Phone" onClick={() => window.apOpen('contact', ctx)}>تسجيل تواصل</Button><Button variant="secondary" icon="Pencil" onClick={() => window.apOpen('tenant')}>تعديل</Button>{t.balance > 0 && <Button icon="Banknote" onClick={openPayment}>تسجيل دفعة</Button>}</>} />
      <SummaryStrip style={{ marginTop: 16 }} items={[
        { label: 'متأخر عبر كل العقود', amount: t.balance, tone: t.balance ? 'danger' : 'success', note: t.balance ? 'حتى اليوم' : 'لا متأخرات' },
        { label: 'بانتظار التحقق', amount: pays.filter((p) => p.status === 'pending').reduce((s, p) => s + p.amount, 0), tone: 'neutral', note: 'لا يُخصم حتى التأكيد' },
        { label: 'مدفوع مؤكد — 2026', amount: pays.filter((p) => p.status === 'confirmed').reduce((s, p) => s + p.amount, 0) + (first === 'خالد' ? 3000 : 0), tone: 'brand', note: 'كل العقود' }
      ]} />
      <Tabs style={{ marginTop: 20 }} label="أقسام المستأجر" value={tab} onChange={setTab} tabs={[{ id: 'leases', label: 'العقود', count: leases.length }, { id: 'payments', label: 'الدفعات', count: pays.length }, { id: 'events', label: 'التواصل والمتابعات' }, { id: 'statement', label: 'كشف الحساب' }, { id: 'agents', label: 'الوكلاء', count: ((window.AP_DATA.tenantAgents || {})[t.id] || []).length || undefined }, { id: 'info', label: 'البيانات والمرفقات' }]} />
      <div style={{ marginTop: 16 }}>
        {tab === 'leases' && (leases.length ? <DataTable caption="عقود المستأجر" rows={leases} onRowClick={(l) => openLease(l.id)} columns={[
          { key: 'u', header: 'الوحدة', render: (l) => cellTwo(l.property, 'وحدة ' + l.unit) },
          { key: 'd', header: 'المدة', render: (l) => num(l.start + ' – ' + l.end) },
          { key: 'r', header: 'الإيجار السنوي', numeric: true, render: (l) => <><Money value={l.rent} /><small>{l.cycle}</small></> },
          { key: 'o', header: 'المتأخر', numeric: true, render: (l) => <Money value={l.overdue} tone={l.overdue ? 'danger' : 'muted'} /> },
          { key: 's', header: 'الحالة', render: (l) => <StatusBadge size="sm" status={l.status} /> },
          { key: 'a', header: '', render: (l) => <Acts><Button size="sm" variant="secondary" onClick={() => openLease(l.id)}>فتح العقد</Button></Acts> }
        ]} /> : <Alert tone="neutral">لا عقود مسجلة لهذا المستأجر بعد.</Alert>)}
        {tab === 'payments' && <DataTable caption="دفعات المستأجر" rows={pays} emptyState={<p style={{ padding: 16, margin: 0, color: 'var(--text-3)' }}>لا دفعات.</p>} columns={[
          { key: 'd', header: 'التاريخ', render: (p) => num(p.date) },
          { key: 'a', header: 'المبلغ', numeric: true, render: (p) => <Money value={p.amount} struck={p.status === 'reversed'} /> },
          { key: 'm', header: 'الطريقة', render: (p) => <>{p.method}<small>{p.to}</small></> },
          { key: 's', header: 'الحالة', render: (p) => <StatusBadge size="sm" status={p.status} /> },
          { key: 'r', header: '', render: (p) => p.receipt && p.status === 'confirmed' ? <Acts><Button size="sm" variant="secondary" icon="Printer" onClick={() => openReceipt({ ...p, recipientLabel: p.to, preview: { rows: [{ period: 'سبتمبر 2026', take: p.amount, after: 0 }] } })}>السند {p.receipt}</Button></Acts> : null }
        ]} />}
        {tab === 'events' && <div className="kit-panel"><div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8, marginBottom: 12 }}><Button size="sm" variant="secondary" icon="CalendarClock" onClick={() => window.apOpen('followup', ctx)}>تحديد متابعة</Button><Button size="sm" icon="Phone" onClick={() => window.apOpen('contact', ctx)}>تسجيل تواصل</Button></div>
          <Timeline events={first === 'خالد' ? D.lease.events : [{ title: 'تذكير بالسداد — واتساب', date: '20/09/2026', actor: 'سارة الغامدي', icon: 'MessageSquare' }, { title: 'أُضيف المستأجر', date: '02/09/2026', actor: 'أحمد الزهراني — استيراد', icon: 'Upload' }]} /></div>}
        {tab === 'agents' && window.TenantAgents && <window.TenantAgents tenant={t} />}
        {tab === 'statement' && window.TenantStatement && <window.TenantStatement tenant={t} leases={leases} />}
        {tab === 'info' && <div className="kit-settle"><div className="kit-panel"><KeyValueList items={[{ label: 'الاسم', value: t.name }, { label: 'النوع', value: t.type }, { label: 'الهوية / السجل', value: num(t.idNo) }, { label: 'الجوال', value: num(t.phone) }, { label: 'الجنسية', value: 'سعودي' }, { label: 'جهة اتصال بديلة', value: null }]} /></div>
          <div className="kit-panel"><h3 style={{ margin: '0 0 10px', fontSize: 14 }}>المرفقات</h3><ul className="kit-f-files"><li><span>صورة الهوية.jpg</span></li><li><span>عقد إيجار موثق.pdf</span></li></ul><Button size="sm" variant="secondary" icon="Upload" style={{ marginTop: 10 }} onClick={() => window.apOpen('attachments', { name: t.name })}>إضافة مرفق</Button></div></div>}
      </div>
    </>
  );
}

function UnitScreen({ unitId, go, openLease, openProperty }) {
  const D = window.AP_DATA;
  const u = D.allUnits.find((x) => x.id === unitId) || D.allUnits[0];
  const p = D.properties.find((x) => x.name === u.property) || D.properties[0];
  const lease = D.leases.find((l) => l.unit === u.u && l.property === u.property && l.status === 'active');
  const history = D.leases.filter((l) => l.unit === u.u && l.property === u.property);
  const maint = D.maintenance.filter((m) => m.unit === u.u && m.property === u.property);
  const exp = D.expenses.filter((x) => x.unit === u.u && x.property === u.property);
  const [tab, setTab] = React.useState('lease');
  return (
    <>
      <EntityHeader back={{ label: 'العودة إلى الوحدات', onClick: (e) => { e.preventDefault(); go('units'); } }} kind={'وحدة · ' + u.type} kindIcon="DoorOpen" title={'وحدة ' + u.u}
        status={<StatusBadge status={u.status} label={u.reserved ? 'محجوزة — مسودة عقد' : undefined} />}
        subtitle={<><a href="#" onClick={(e) => { e.preventDefault(); openProperty(p.id); }}>{u.property}</a> · {p.city} · {p.district}</>}
        facts={[{ label: 'الغرف', value: u.rooms || '—' }, { label: 'الإيجار المقترح', value: <Money value={u.rent} /> }, u.status === 'vacant' ? { label: 'شاغرة منذ', value: num(u.since) } : { label: 'المستأجر', value: u.tenant }]}
        actions={<><Button variant="secondary" icon="Pencil" onClick={() => window.apOpen('unit', u)}>تعديل</Button><Button variant="secondary" icon="Wrench" onClick={() => window.apOpen('maintenance', { propertyId: p.id })}>طلب صيانة</Button>{u.status === 'vacant' ? <Button icon="FileText" onClick={() => window.apOpen('lease', u)}>إنشاء عقد</Button> : <Button onClick={() => openLease(lease ? lease.id : 'l1')}>فتح العقد</Button>}</>} />
      {u.status === 'vacant' && <Alert tone="warning" style={{ marginTop: 16 }}>الوحدة شاغرة منذ {u.since}. الإيجار المفقود المقدر حتى اليوم يظهر في تقرير الإشغال — ليس دينًا على أحد.</Alert>}
      <Tabs style={{ marginTop: 18 }} label="أقسام الوحدة" value={tab} onChange={setTab} tabs={[{ id: 'lease', label: 'العقد والسجل', count: history.length }, { id: 'maint', label: 'الصيانة', count: maint.length }, { id: 'exp', label: 'المصروفات', count: exp.length }, { id: 'info', label: 'البيانات' }]} />
      <div style={{ marginTop: 16 }}>
        {tab === 'lease' && (history.length ? <DataTable caption="سجل الإيجار" rows={history} onRowClick={(l) => openLease(l.id)} columns={[
          { key: 't', header: 'المستأجر', render: (l) => l.tenant },
          { key: 'd', header: 'المدة', render: (l) => num(l.start + ' – ' + l.end) },
          { key: 'r', header: 'الإيجار', numeric: true, render: (l) => <Money value={l.rent} /> },
          { key: 'o', header: 'المتأخر', numeric: true, render: (l) => <Money value={l.overdue} tone={l.overdue ? 'danger' : 'muted'} /> },
          { key: 's', header: 'الحالة', render: (l) => <StatusBadge size="sm" status={l.status} /> }
        ]} /> : <Alert tone="neutral" actions={<Button size="sm" icon="FileText" onClick={() => window.apOpen('lease', u)}>إنشاء عقد</Button>}>لا يوجد سجل إيجار لهذه الوحدة في النظام.</Alert>)}
        {tab === 'maint' && (maint.length ? <DataTable caption="صيانة الوحدة" rows={maint} columns={[
          { key: 'id', header: 'الطلب', render: (m) => cellTwo(<bdi className="ap-ltr">{m.id}</bdi>, m.date) },
          { key: 't', header: 'المشكلة', wrap: true, render: (m) => m.title },
          { key: 'c', header: 'التكلفة', numeric: true, render: (m) => <Money value={m.cost || m.estimate} /> },
          { key: 's', header: 'الحالة', render: (m) => <StatusBadge size="sm" status={m.status} /> }
        ]} /> : <Alert tone="neutral">لا طلبات صيانة لهذه الوحدة.</Alert>)}
        {tab === 'exp' && (exp.length ? <DataTable caption="مصروفات الوحدة" rows={exp} columns={[
          { key: 'd', header: 'التاريخ', render: (x) => num(x.date) }, { key: 'x', header: 'البيان', render: (x) => x.desc }, { key: 'a', header: 'المبلغ', numeric: true, render: (x) => <Money value={x.amount} /> }, { key: 'f', header: 'التمويل', render: (x) => x.from }
        ]} /> : <Alert tone="neutral">لا مصروفات مسجلة على هذه الوحدة.</Alert>)}
        {tab === 'info' && <div className="kit-panel"><KeyValueList items={[{ label: 'رقم الوحدة', value: num(u.u) }, { label: 'العقار', value: u.property }, { label: 'النوع', value: u.type }, { label: 'الغرف', value: u.rooms || null }, { label: 'الإيجار السنوي المقترح', value: <Money value={u.rent} /> }, { label: 'عداد الكهرباء', value: <bdi className="ap-ltr">1002 4471 88</bdi> }, { label: 'عداد المياه', value: null }]} /></div>}
      </div>
    </>
  );
}

Object.assign(window, { TenantScreen, UnitScreen });
})();
