(() => {
const { EntityHeader, Tabs, DataTable, Money, StatusBadge, Button, KeyValueList, FilterBar, Field, Select, Alert, Dialog, TextInput, Checkbox, SaveStatus } = window.AmlakPlusDesignSystem_b3aa85;

function UnitDialog({ onClose, property }) {
  const [state, setState] = React.useState('idle');
  return (
    <Dialog title="إضافة وحدة" subtitle={property.name + ' — العقار محدد تلقائيًا'} onClose={onClose} busy={state === 'saving'} width={620}
      footer={<><SaveStatus state={state} /><div style={{ display: 'flex', gap: 8 }}><Button variant="secondary" onClick={onClose}>إلغاء</Button><Button loading={state === 'saving'} onClick={() => { setState('saving'); setTimeout(() => setState('saved'), 800); }}>حفظ الوحدة</Button></div></>}>
      <div style={{ display: 'grid', gap: 14 }}>
        <div className="kit-2col"><Field label="رقم الوحدة" required><TextInput ltr placeholder="205" /></Field><Field label="النوع"><Select options={['شقة', 'محل', 'مكتب', 'فيلا']} /></Field></div>
        <div className="kit-2col">
          <Field label="التأثيث"><div style={{ display: 'flex', gap: 16, minHeight: 40, alignItems: 'center' }}><Checkbox type="radio" name="furn" label="مفروش" /><Checkbox type="radio" name="furn" label="بلاط (غير مفروش)" defaultChecked /></div></Field>
          <Field label="فئة السكن" hint="مستقلة عن التأثيث"><Select options={['عائلات', 'عزاب', 'غير محدد / لا ينطبق']} /></Field>
        </div>
        <div className="kit-2col"><Field label="الإيجار السنوي المقترح" optional hint="قيمة مرجعية — ليست دينًا ولا تحصيلًا"><TextInput ltr inputMode="decimal" placeholder="0" /></Field><Field label="رسوم الخدمات المقترحة" optional><TextInput ltr inputMode="decimal" placeholder="0" /></Field></div>
        <Field label="ملاحظات" optional><TextInput multiline /></Field>
      </div>
    </Dialog>
  );
}

function PropertyScreen({ propertyId, initialTab, go, openLease, openOwner, openPayment }) {
  const D = window.AP_DATA;
  const p = D.properties.find((x) => x.id === propertyId) || D.properties[0];
  const owner = D.owners.find((o) => o.id === p.ownerId);
  const [tab, setTab] = React.useState(initialTab || 'units');
  const [furn, setFurn] = React.useState('');
  const [adding, setAdding] = React.useState(false);
  const units = D.units.filter((u) => !furn || u.furn === furn);
  return (
    <>
      <EntityHeader back={{ label: 'العودة إلى العقارات', onClick: (e) => { e.preventDefault(); go('properties'); } }} kind={'عقار · ' + p.use} title={p.name} subtitle={p.city + ' · حي ' + p.district}
        facts={[{ label: 'المالك', value: <a href="#" onClick={(e) => { e.preventDefault(); openOwner(p.ownerId); }}>{owner.name}</a> }, { label: 'نوع الإدارة', value: p.mgmt }, { label: 'الوحدات', value: p.units + ' · ' + (p.units - p.occupied) + ' شاغرة' }]}
        actions={<><Button variant="secondary" icon="Pencil" onClick={() => window.apOpen('property', p)}>تعديل</Button><Button variant="secondary" icon="Paperclip" onClick={() => window.apOpen('attachments', p)}>المرفقات</Button><Button variant="secondary" icon="Wrench" onClick={() => window.apOpen('maintenance', { propertyId: p.id })}>طلب صيانة</Button><Button variant="secondary" icon="Wallet" onClick={() => window.apOpen('expense', { propertyId: p.id })}>مصروف</Button><Button icon="Plus" onClick={() => setAdding(true)}>إضافة وحدة</Button></>} />
      <Tabs style={{ marginTop: 18 }} label="أقسام العقار" value={tab} onChange={setTab} tabs={[{ id: 'units', label: 'الوحدات', count: p.units }, { id: 'leases', label: 'العقود والمستأجرون', count: p.occupied }, { id: 'info', label: 'بيانات العقار' }, { id: 'sheet', label: 'كشف العمارة الشهري', icon: 'ReceiptText' }]} />
      <div style={{ marginTop: 16 }}>
        {tab === 'units' && <>
          <div className="kit-toolbar"><Field label="التأثيث" style={{ width: 200 }}><Select value={furn} onChange={(e) => setFurn(e.target.value)} placeholder="الكل" options={['مفروش', 'بلاط']} /></Field><span className="kit-scope" style={{ margin: 0 }}>عرض {units.length} من {p.units} · بقية الوحدات في الصفحات التالية</span></div>
          <DataTable caption="وحدات العقار" rows={units} rowKey="u" columns={[
            { key: 'u', header: 'الوحدة', render: (u) => <><span className="ap-cell-strong">{u.u}</span><small>الدور {u.floor}</small></> },
            { key: 'type', header: 'النوع', render: (u) => u.type + ' · ' + u.rooms + ' غرف' },
            { key: 'furn', header: 'التأثيث' },
            { key: 'cat', header: 'فئة السكن' },
            { key: 'rent', header: 'الإيجار المقترح (سنوي)', numeric: true, render: (u) => <Money value={u.rent} tone="muted" /> },
            { key: 'status', header: 'الحالة', render: (u) => <StatusBadge size="sm" status={u.status} /> },
            { key: 'tenant', header: 'المستأجر', render: (u) => u.tenant ? <a href="#" onClick={(e) => { e.preventDefault(); openLease('l1'); }}>{u.tenant}</a> : <span style={{ color: 'var(--text-3)' }}>—</span> },
            { key: 'a', header: <span className="ap-sr-only">إجراءات</span>, render: (u) => u.status === 'vacant' ? <Button size="sm" variant="secondary" icon="FileText" onClick={() => window.apOpen('lease', { ...u, property: p.name })}>إنشاء عقد</Button> : <Button size="sm" variant="ghost" icon="Pencil">تعديل</Button> }
          ]} />
          <p className="kit-scope">«الإيجار المقترح» قيمة مرجعية في بيانات الوحدة وليست مستحقًا أو تحصيلًا.</p>
        </>}
        {tab === 'leases' && <DataTable caption="عقود العقار" rows={D.units.filter((u) => u.tenant)} rowKey="u" columns={[
          { key: 'tenant', header: 'المستأجر', render: (u) => <span className="ap-cell-strong">{u.tenant}</span> }, { key: 'u', header: 'الوحدة' },
          { key: 'st', header: 'حالة العقد', render: () => <StatusBadge size="sm" status="active" /> },
          { key: 'bal', header: 'المتأخر', numeric: true, render: (u) => <Money value={u.u === '204' ? 6000 : u.u === '201' ? 2000 : 0} tone={u.u === '204' || u.u === '201' ? 'danger' : 'muted'} /> },
          { key: 'a', header: '', render: () => <Button size="sm" variant="secondary" onClick={() => openLease('l1')}>فتح العقد</Button> }
        ]} />}
        {tab === 'info' && <div className="kit-panel"><KeyValueList items={[{ label: 'اسم العقار', value: p.name }, { label: 'المدينة', value: p.city }, { label: 'الحي', value: p.district }, { label: 'الاستخدام', value: p.use }, { label: 'المالك', value: owner.name }, { label: 'نوع الإدارة', value: p.mgmt }, { label: 'رقم الصك', value: null }, { label: 'العنوان الوطني', value: null }, { label: 'رابط فيديو', value: null }]} /></div>}
        {tab === 'sheet' && <BuildingSheet property={p} openPayment={openPayment} />}
      </div>
      {adding && <UnitDialog property={p} onClose={() => setAdding(false)} />}
    </>
  );
}

Object.assign(window, { PropertyScreen });

})();
