(() => {
const { PageHeader, SummaryStrip, Money, StatusBadge, Button, Dialog, Field, Select, TextInput, SegmentedControl, SearchField, Alert, SaveStatus } = window.AmlakPlusDesignSystem_b3aa85;

const GROUPS = [
  { kind: 'promise', title: 'وعود سداد مستحقة اليوم', status: 'promised', why: 'التزم المستأجر بالدفع اليوم — المبلغ غير محصل حتى يُسجل ويُتحقق منه.' },
  { kind: 'overdue', title: 'متابعات متأخرة ومدينون', status: 'overdue', why: 'موعد متابعة فات أو دين قائم بعد المغادرة.' },
  { kind: 'due', title: 'استحقاقات اليوم', status: 'due', why: 'أقساط تستحق اليوم ولم تُسجل لها دفعة.' },
  { kind: 'verify', title: 'مدفوعات بانتظار التحقق', status: 'pending', why: 'مسجلة ولم يتأكد وصولها. الصورة المرفقة وحدها ليست تأكيدًا.' }
];
const groupOf = (k) => (k === 'overdue-followup' || k === 'departed' ? 'overdue' : k);

function WorkRow({ it, onPay, onContact, onFollow, onLease }) {
  const g = groupOf(it.kind);
  const primary = g === 'verify' ? <Button size="sm" variant="secondary" icon="ShieldCheck" onClick={() => onLease(it)}>مراجعة</Button>
    : it.kind === 'departed' ? <Button size="sm" variant="secondary" icon="Phone" onClick={() => onContact(it)}>تسجيل تواصل</Button>
    : <Button size="sm" icon="Banknote" onClick={() => onPay(it)}>تسجيل دفعة</Button>;
  return (
    <li className="kit-work-row">
      <div className="kit-wr-who">
        <strong>{it.tenant}</strong>
        <span>{it.property} · وحدة {it.unit}{it.tenantType !== 'فرد' && <> · {it.tenantType}</>}</span>
      </div>
      <div className="kit-wr-amt">
        {g === 'promise' ? <><Money value={it.promised} size="md" /><span>وعد من أصل <Money value={it.amount} /> متأخرة</span></>
          : g === 'verify' ? <><Money value={it.amount} size="md" /><span>{it.channel}</span></>
          : <><Money value={it.amount} size="md" tone={g === 'overdue' ? 'danger' : undefined} /><span>{it.overdueMonths ? 'متأخرات ' + it.overdueMonths + ' أشهر' : it.kind === 'departed' ? 'رصيد بعد انتهاء العقد' : 'قسط مستحق'}</span></>}
      </div>
      <div className="kit-wr-date"><strong>{it.date}</strong><span>{it.dateNote}</span></div>
      <div className="kit-wr-next"><span className="kit-wr-label">الخطوة التالية</span>{it.next}<span className="kit-wr-owner">المسؤول: {it.owner}</span></div>
      <div className="kit-wr-actions">
        {primary}
        {it.kind !== 'departed' && <Button size="sm" variant="ghost" iconOnly icon="Phone" label="تسجيل تواصل" onClick={() => onContact(it)} />}
        <Button size="sm" variant="ghost" iconOnly icon="CalendarClock" label="تحديد متابعة" onClick={() => onFollow(it)} />
        <Button size="sm" variant="ghost" iconOnly icon="FileText" label="فتح العقد" onClick={() => onLease(it)} />
      </div>
    </li>
  );
}

function ContactDialog({ item, mode, onClose, onSaved }) {
  const [state, setState] = React.useState('idle');
  const save = () => { setState('saving'); setTimeout(() => { setState('saved'); setTimeout(() => onSaved(item, mode), 500); }, 700); };
  return (
    <Dialog title={mode === 'follow' ? 'تحديد متابعة' : 'تسجيل تواصل'} subtitle={item.tenant + ' · ' + item.property + ' / ' + item.unit} onClose={onClose} busy={state === 'saving'} width={480}
      footer={<><SaveStatus state={state} /><div style={{ display: 'flex', gap: 8 }}><Button variant="secondary" onClick={onClose} disabled={state === 'saving'}>إلغاء</Button><Button loading={state === 'saving'} onClick={save}>حفظ</Button></div></>}>
      <div style={{ display: 'grid', gap: 14 }}>
        {mode === 'contact' && <Field label="نتيجة التواصل"><Select options={['رد ووعد بالسداد', 'رد ورفض / اعترض', 'لم يرد', 'الرقم غير صحيح']} /></Field>}
        {mode === 'contact' && <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}><Field label="مبلغ الوعد" optional><TextInput ltr inputMode="decimal" placeholder="0" /></Field><Field label="تاريخ الوعد" optional><TextInput type="date" /></Field></div>}
        {mode === 'follow' && <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}><Field label="موعد المتابعة" required><TextInput type="date" defaultValue="2026-09-26" /></Field><Field label="المسؤول"><Select options={['سارة الغامدي', 'ماجد الحربي']} /></Field></div>}
        <Field label="ملاحظة" optional><TextInput multiline placeholder="ما الذي قيل أو المطلوب في المتابعة القادمة" /></Field>
      </div>
    </Dialog>
  );
}

function TodayScreen({ openLease, openPayment, go }) {
  const D = window.AP_DATA;
  const [filter, setFilter] = React.useState('all');
  const [mine, setMine] = React.useState('all');
  const [q, setQ] = React.useState('');
  const [dlg, setDlg] = React.useState(null);
  const [notice, setNotice] = React.useState('');
  const items = D.today_items.filter((i) => (mine === 'all' || i.owner === 'سارة') && (!q || (i.tenant + i.property + i.unit).includes(q)));
  const sum = (g, f = 'amount') => D.today_items.filter((i) => groupOf(i.kind) === g).reduce((s, i) => s + (i[f] || 0), 0);
  const overdueTotal = D.today_items.filter((i) => ['overdue-followup', 'departed', 'promise'].includes(i.kind)).reduce((s, i) => s + i.amount, 0);
  const pick = (k) => () => setFilter(filter === k ? 'all' : k);
  return (
    <>
      <PageHeader title="متابعات اليوم" description={'الثلاثاء ' + D.today + ' · ما يحتاج إجراءً اليوم مرتبًا حسب الأولوية.'}
        actions={<><Button variant="secondary" icon="History" onClick={() => go('followlog')}>سجل المتابعات</Button><Button variant="secondary" icon="ReceiptText" onClick={() => openLease('l1')}>البحث عن عقد</Button><Button icon="Banknote" onClick={() => openPayment(D.today_items[0])}>تسجيل دفعة</Button></>} />
      <SummaryStrip items={[
        { key: 'overdue', label: 'متأخرات قائمة', amount: overdueTotal, tone: 'danger', note: '3 مستأجرين · حتى اليوم', onClick: pick('overdue'), selected: filter === 'overdue' },
        { key: 'due', label: 'مستحق اليوم', amount: sum('due'), tone: 'warning', note: 'قسطان · لا يشمل القادم', onClick: pick('due'), selected: filter === 'due' },
        { key: 'promise', label: 'وعود سداد اليوم', amount: sum('promise', 'promised'), tone: 'info', note: 'التزام — ليس تحصيلًا', onClick: pick('promise'), selected: filter === 'promise' },
        { key: 'verify', label: 'بانتظار التحقق', amount: sum('verify'), tone: 'neutral', note: 'دفعتان · واحدة لحساب المالك', onClick: pick('verify'), selected: filter === 'verify' }
      ]} />
      <p className="kit-scope">الوعد جزء من المتأخرات وليس مبلغًا إضافيًا. الإجماليات لهذه المنشأة فقط.</p>
      {notice && <Alert tone="success" onDismiss={() => setNotice('')} style={{ marginBottom: 12 }}>{notice}</Alert>}
      <div className="kit-toolbar">
        <SearchField value={q} onChange={setQ} placeholder="ابحث باسم المستأجر أو العقار أو الوحدة" style={{ flex: '1 1 260px', maxWidth: 420 }} />
        <SegmentedControl label="المسؤول" value={mine} onChange={setMine} options={[{ value: 'all', label: 'كل الفريق' }, { value: 'me', label: 'مهامي' }]} />
      </div>
      {GROUPS.filter((g) => filter === 'all' || filter === g.kind).flatMap((g) => {
        const rows = items.filter((i) => groupOf(i.kind) === g.kind);
        const req = g.kind === 'verify' && filter === 'all' && window.TodayRequests ? [<window.TodayRequests key="req" />] : [];
        if (!rows.length) return req;
        return [...req, (
          <section key={g.kind} className="kit-group" aria-labelledby={'g-' + g.kind}>
            <header><h2 id={'g-' + g.kind}><StatusBadge status={g.status} label={g.title} /><span className="kit-count">{rows.length}</span></h2><p>{g.why}</p></header>
            <ul>{rows.map((it) => <WorkRow key={it.id} it={it} onPay={openPayment} onContact={(i) => setDlg({ item: i, mode: 'contact' })} onFollow={(i) => setDlg({ item: i, mode: 'follow' })} onLease={() => openLease(it.leaseId)} />)}</ul>
          </section>
        )];
      })}
      {dlg && <ContactDialog {...dlg} onClose={() => setDlg(null)} onSaved={(i, m) => { setDlg(null); setNotice((m === 'follow' ? 'حُدد موعد متابعة لـ' : 'سُجل التواصل مع ') + i.tenant + '.'); }} />}
    </>
  );
}

Object.assign(window, { TodayScreen });

})();
