(() => {
const { PageHeader, SummaryStrip, DataTable, Money, StatusBadge, Button, Select, Tabs, SegmentedControl, Icon } = window.AmlakPlusDesignSystem_b3aa85;
const { Acts, match, Toolbar, Empty, cellTwo, num } = window.APList;

function UnitsScreen({ openLease, openUnit }) {
  const D = window.AP_DATA;
  const [q, setQ] = React.useState('');
  const [st, setSt] = React.useState('');
  const [prop, setProp] = React.useState('');
  const list = D.allUnits.filter((u) => (!st || u.status === st) && (!prop || u.property === prop) && match(q, u.u, u.property, u.tenant));
  const vac = D.allUnits.filter((u) => u.status === 'vacant');
  return (
    <>
      <PageHeader title="الوحدات" description="كل الوحدات عبر العقارات. الشاغر أولًا للتسويق وإنشاء العقود." actions={<><Button variant="secondary" icon="Upload" onClick={() => window.apOpen('import', { entity: 'الوحدات' })}>استيراد</Button><Button icon="Plus" onClick={() => window.apOpen('unit')}>إضافة وحدة</Button></>} />
      <SummaryStrip items={[
        { label: 'الوحدات', value: 102, tone: 'brand', note: '6 عقارات' },
        { label: 'شاغرة', value: 9, tone: 'warning', note: 'منها ' + vac.filter((u) => u.reserved).length + ' محجوزة', onClick: () => setSt(st === 'vacant' ? '' : 'vacant'), selected: st === 'vacant' },
        { label: 'إيجار سنوي مقترح للشاغر', amount: vac.reduce((s, u) => s + u.rent, 0), tone: 'neutral', note: 'مرجعي — ليس إيرادًا' }
      ]} />
      <div style={{ marginTop: 14 }}>
        <Toolbar q={q} setQ={setQ} ph="رقم الوحدة أو العقار أو المستأجر">
          <Select value={prop} onChange={(e) => setProp(e.target.value)} placeholder="كل العقارات" options={D.properties.map((p) => p.name)} />
          <Select value={st} onChange={(e) => setSt(e.target.value)} placeholder="كل الحالات" options={[{ value: 'vacant', label: 'شاغرة' }, { value: 'occupied', label: 'مؤجرة' }]} />
        </Toolbar>
        {!list.length ? <Empty onClear={() => { setQ(''); setSt(''); setProp(''); }} /> : <DataTable caption="الوحدات" rows={list} onRowClick={(u) => openUnit(u.id)} columns={[
          { key: 'u', header: 'الوحدة', render: (u) => cellTwo(num(u.u), u.type + (u.rooms ? ' · ' + u.rooms + ' غرف' : '')) },
          { key: 'p', header: 'العقار', render: (u) => u.property },
          { key: 'r', header: 'الإيجار المقترح', numeric: true, render: (u) => <Money value={u.rent} tone="muted" /> },
          { key: 's', header: 'الحالة', render: (u) => <><StatusBadge size="sm" status={u.status} label={u.reserved ? 'محجوزة — مسودة عقد' : undefined} />{u.since && <small>منذ {u.since}</small>}</> },
          { key: 't', header: 'المستأجر', render: (u) => u.tenant || <span style={{ color: 'var(--text-3)' }}>—</span> },
          { key: 'a', header: <span className="ap-sr-only">إجراءات</span>, render: (u) => <Acts>{u.status === 'vacant' ? <Button size="sm" variant="secondary" icon="FileText" onClick={() => window.apOpen('lease', u)}>إنشاء عقد</Button> : <Button size="sm" variant="secondary" onClick={() => openLease((window.AP_DATA.leases.find((l) => l.unit === u.u && l.property === u.property) || {}).id)}>فتح العقد</Button>}<Button size="sm" variant="ghost" iconOnly icon="Pencil" label="تعديل الوحدة" onClick={() => window.apOpen('unit', u)} /></Acts> }
        ]} />}
      </div>
    </>
  );
}

function OwnersScreen({ openOwner }) {
  const D = window.AP_DATA;
  const [q, setQ] = React.useState('');
  const held = (id) => D.settlements.filter((s) => s.ownerId === id && s.status !== 'draft').reduce((a, s) => a + s.net - s.delivered, 0);
  const list = D.owners.filter((o) => match(q, o.name, o.phone));
  return (
    <>
      <PageHeader title="الملاك" description="من نملك إدارته، وكم من أمواله بحوزة المكتب الآن." actions={<Button icon="Plus" onClick={() => window.apOpen('owner')}>إضافة مالك</Button>} />
      <SummaryStrip items={[
        { label: 'الملاك', value: D.owners.length, tone: 'brand', note: 'فرد وشركة' },
        { label: 'أموال ملاك بحوزة المكتب', amount: D.owners.reduce((s, o) => s + held(o.id), 0), tone: 'warning', note: 'تصفيات معتمدة لم تُسلَّم كاملة' },
        { label: 'تصفيات بانتظار الاعتماد', value: D.settlements.filter((s) => s.status === 'awaitingApproval').length, tone: 'info', note: 'أغسطس 2026' }
      ]} />
      <div style={{ marginTop: 14 }}>
        <Toolbar q={q} setQ={setQ} ph="اسم المالك أو الجوال" />
        {!list.length ? <Empty onClear={() => setQ('')} /> : <DataTable caption="الملاك" rows={list} onRowClick={(o) => openOwner(o.id)} columns={[
          { key: 'n', header: 'المالك', render: (o) => cellTwo(o.name, o.kind) },
          { key: 'ph', header: 'الجوال', render: (o) => num(o.phone) },
          { key: 'p', header: 'العقارات', numeric: true, render: (o) => num(o.properties) },
          { key: 'u', header: 'الوحدات', numeric: true, render: (o) => num(o.units) },
          { key: 'ag', header: 'اتفاق الإدارة', wrap: true, render: (o) => o.agreement },
          { key: 'h', header: 'بحوزة المكتب', numeric: true, render: (o) => <Money value={held(o.id)} tone={held(o.id) ? 'danger' : 'muted'} /> },
          { key: 'a', header: <span className="ap-sr-only">إجراءات</span>, render: (o) => <Acts><Button size="sm" variant="secondary" onClick={() => openOwner(o.id)}>فتح الملف</Button><Button size="sm" variant="ghost" iconOnly icon="FileText" label="كشف المالك" onClick={() => window.apOpen('ownerStatement', o)} /></Acts> }
        ]} />}
      </div>
    </>
  );
}

function TenantsScreen({ openLease, openTenant }) {
  const D = window.AP_DATA;
  const [q, setQ] = React.useState('');
  const [f, setF] = React.useState('all');
  const list = D.tenants.filter((t) => (f === 'all' || (f === 'debt' ? t.balance > 0 : t.leases === 0)) && match(q, t.name, t.phone, t.property));
  return (
    <>
      <PageHeader title="المستأجرون" description="الأشخاص والمنشآت المستأجرة ورصيد كل منهم عبر عقوده." actions={<><Button variant="secondary" icon="Upload" onClick={() => window.apOpen('import', { entity: 'المستأجرون' })}>استيراد</Button><Button icon="Plus" onClick={() => window.apOpen('tenant')}>إضافة مستأجر</Button></>} />
      <div className="kit-toolbar">
        <Toolbar q={q} setQ={setQ} ph="الاسم أو الجوال أو الوحدة" />
        <SegmentedControl label="تصفية" value={f} onChange={setF} options={[{ value: 'all', label: 'الكل' }, { value: 'debt', label: 'عليهم متأخرات' }, { value: 'left', label: 'غادروا' }]} />
      </div>
      {!list.length ? <Empty onClear={() => { setQ(''); setF('all'); }} /> : <DataTable caption="المستأجرون" rows={list} onRowClick={(t) => openTenant(t.id)} columns={[
        { key: 'n', header: 'المستأجر', render: (t) => cellTwo(t.name, t.type) },
        { key: 'ph', header: 'الجوال', render: (t) => num(t.phone) },
        { key: 'id', header: 'الهوية / السجل', render: (t) => num(t.idNo) },
        { key: 'p', header: 'الوحدة الحالية', render: (t) => t.property },
        { key: 'b', header: 'المتأخر', numeric: true, render: (t) => <Money value={t.balance} tone={t.balance ? 'danger' : 'muted'} /> },
        { key: 'a', header: <span className="ap-sr-only">إجراءات</span>, render: (t) => <Acts><Button size="sm" variant="secondary" onClick={() => openTenant(t.id)}>فتح الملف</Button><Button size="sm" variant="ghost" iconOnly icon="Phone" label="تسجيل تواصل" onClick={() => window.apOpen('contact', { tenant: t.name, property: t.property })} /></Acts> }
      ]} />}
    </>
  );
}

const LST = { active: 'active', ended: 'ended', draft: 'draft' };
function LeasesScreen({ openLease, openPayment }) {
  const D = window.AP_DATA;
  const [tab, setTab] = React.useState('active');
  const [q, setQ] = React.useState('');
  const by = { active: (l) => l.status === 'active', ending: (l) => l.ending, ended: (l) => l.status === 'ended', draft: (l) => l.status === 'draft' };
  const list = D.leases.filter((l) => by[tab](l) && match(q, l.tenant, l.property, l.unit));
  return (
    <>
      <PageHeader title="العقود" description="عقود الإيجار وحالاتها. التجديد والإنهاء مساران مستقلان يحفظان الأثر." actions={<Button icon="Plus" onClick={() => window.apOpen('lease')}>إنشاء عقد</Button>} />
      <Tabs label="حالة العقود" value={tab} onChange={setTab} tabs={[{ id: 'active', label: 'نشطة', count: D.leases.filter(by.active).length }, { id: 'ending', label: 'تنتهي خلال 60 يومًا', count: D.leases.filter(by.ending).length }, { id: 'ended', label: 'منتهية', count: D.leases.filter(by.ended).length }, { id: 'draft', label: 'مسودات', count: D.leases.filter(by.draft).length }]} />
      <div style={{ marginTop: 14 }}>
        <Toolbar q={q} setQ={setQ} ph="المستأجر أو العقار أو الوحدة" />
        {!list.length ? <Empty onClear={() => setQ('')} /> : <DataTable caption="العقود" rows={list} onRowClick={(l) => openLease(l.id)} columns={[
          { key: 't', header: 'المستأجر', render: (l) => cellTwo(l.tenant, l.property + ' / ' + l.unit) },
          { key: 'd', header: 'المدة', render: (l) => <>{num(l.start + ' – ' + l.end)}{l.ending && <small style={{ color: 'var(--status-warning-fg)' }}>ينتهي قريبًا</small>}</> },
          { key: 'r', header: 'الإيجار السنوي', numeric: true, render: (l) => <><Money value={l.rent} /><small>{l.cycle}</small></> },
          { key: 'e', header: 'إيجار', render: (l) => l.ejar },
          { 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={LST[l.status]} /> },
          { key: 'a', header: <span className="ap-sr-only">إجراءات</span>, render: (l) => <Acts>
            {l.status === 'draft' ? <Button size="sm" variant="secondary" icon="Pencil" onClick={() => window.apOpen('lease', { property: l.property, u: l.unit, rent: l.rent })}>إكمال</Button>
              : l.status === 'ended' ? <Button size="sm" variant="secondary" icon="Phone" onClick={() => window.apOpen('contact', l)}>متابعة الرصيد</Button>
              : <>{l.overdue > 0 && <Button size="sm" icon="Banknote" onClick={openPayment}>دفعة</Button>}<Button size="sm" variant="ghost" iconOnly icon="RotateCcw" label="تجديد" onClick={() => window.apOpen('renew', l)} /><Button size="sm" variant="ghost" iconOnly icon="LogOut" label="إنهاء / إخلاء" onClick={() => window.apOpen('endLease', l)} /></>}
          </Acts> }
        ]} />}
      </div>
    </>
  );
}

Object.assign(window, { UnitsScreen, OwnersScreen, TenantsScreen, LeasesScreen });
})();
