(() => {
const { Dialog, Field, MoneyInput, Select, TextInput, SegmentedControl, Button, Money, KeyValueList, Alert, Checkbox, Icon, StatusBadge } = window.AmlakPlusDesignSystem_b3aa85;

const ev = (x, ...a) => (typeof x === 'function' ? x(...a) : x);
const optLabel = (o, val) => { const f = (o || []).find((x) => (typeof x === 'string' ? x : x.value) === val); return f ? (typeof f === 'string' ? f : f.label) : val; };
const fmt = (n) => Number(n || 0).toLocaleString('en-US', { maximumFractionDigits: 2 });

window.apOpen = (id, ctx) => window.dispatchEvent(new CustomEvent('ap-open', { detail: { id, ctx: ctx || {} } }));

function FilePick({ value, onChange, accept }) {
  const ref = React.useRef();
  return <div className="kit-file"><input ref={ref} type="file" accept={accept} hidden onChange={(e) => onChange(e.target.files[0] ? e.target.files[0].name : '')} />
    <Button variant="secondary" icon="Upload" onClick={() => ref.current.click()}>{value ? 'تغيير الملف' : 'اختيار ملف'}</Button>
    {value ? <span className="kit-file__name"><Icon name="Paperclip" size={14} /><bdi>{value}</bdi><button type="button" aria-label="إزالة" onClick={() => onChange('')}><Icon name="X" size={14} /></button></span> : <span className="kit-file__hint">أو اسحب الملف هنا</span>}</div>;
}

function Schedule({ v }) {
  const n = { 'شهري': 12, 'ربع سنوي': 4, 'نصف سنوي': 2, 'سنوي': 1 }[v.cycle] || 12;
  const rent = Number(v.rent) || 0;
  if (!rent) return <p className="kit-scope" style={{ margin: 0 }}>أدخل الإيجار لمعاينة جدول الاستحقاقات.</p>;
  const [y, m] = (v.start || '2026-10-01').split('-').map(Number);
  const step = 12 / n;
  const rows = Array.from({ length: Math.min(n, 4) }, (_, i) => { const mm = (m - 1 + i * step) % 12 + 1; const yy = y + Math.floor((m - 1 + i * step) / 12); return '01/' + String(mm).padStart(2, '0') + '/' + yy; });
  return <div className="kit-alloc"><h3>معاينة الاستحقاقات · {n} دفعات</h3>
    {rows.map((d, i) => <div key={d}><span>الدفعة {i + 1} <small>· {d}</small></span><Money value={rent / n} /></div>)}
    {n > 4 && <div><small>و{n - 4} دفعات أخرى</small><span></span></div>}
    <div className="kit-alloc__total"><span>الإجمالي السنوي</span><Money value={rent + (Number(v.services) || 0)} size="md" /></div></div>;
}

function FormDialog({ id, ctx, onClose }) {
  const spec = window.AP_FORMS[id];
  const fields = spec.fields;
  const init = {}; fields.forEach((f) => { if (f.k) init[f.k] = f.def !== undefined ? ev(f.def, ctx) : f.t === 'check' ? false : ''; });
  const [v, setV] = React.useState(init);
  const [step, setStep] = React.useState('form');
  const [busy, setBusy] = React.useState(false);
  const [tried, setTried] = React.useState(false);
  const set = (k) => (x) => setV((s) => ({ ...s, [k]: x && x.target ? (x.target.type === 'checkbox' ? x.target.checked : x.target.value) : x }));
  const visible = fields.filter((f) => !f.when || f.when(v, ctx));
  const missing = visible.filter((f) => f.k && f.req && !String(v[f.k] || '').trim()).map((f) => f.k);
  const blocked = visible.some((f) => f.t === 'note' && f.tone === 'danger');
  const title = ev(spec.title, ctx), subtitle = ev(spec.sub, ctx);
  const next = () => { setTried(true); if (missing.length || blocked) return; if (spec.review && step === 'form') { setStep('review'); return; } save(); };
  const save = () => { setBusy(true); setTimeout(() => { setBusy(false); setStep('done'); ctx.onSaved && ctx.onSaved(v); }, 800); };

  const display = (f) => {
    const val = v[f.k];
    if (f.t === 'check') return val ? 'نعم' : 'لا';
    if (val === '' || val == null) return null;
    if (f.t === 'money') return <Money value={Number(val)} />;
    if (f.t === 'date') return <bdi className="ap-num">{val.split('-').reverse().join('/')}</bdi>;
    if (f.t === 'select' || f.t === 'radio') return optLabel(ev(f.o, ctx), val);
    if (f.t === 'ltr') return <bdi className="ap-ltr">{val}</bdi>;
    return val;
  };
  const summaryItems = visible.filter((f) => f.k && f.t !== 'area').map((f) => ({ label: ev(f.l, v), value: display(f) })).filter((x) => x.value !== null);

  const renderField = (f, i) => {
    const cls = 'kit-f' + (f.half ? '' : ' is-full');
    const err = tried && missing.includes(f.k) ? 'هذا الحقل مطلوب' : null;
    const label = ev(f.l, v);
    switch (f.t) {
      case 'section': return <h3 key={i} className="kit-f-section is-full">{f.text}</h3>;
      case 'note': return <Alert key={i} tone={f.tone} className="is-full" style={{ gridColumn: '1/-1' }}>{f.text}</Alert>;
      case 'summary': return <div key={i} className="kit-f-summary is-full">{f.rows(ctx).map(([k, val, t]) => <div key={k}><span>{k}</span>{t === 'money' ? <Money value={val} size="md" /> : <b>{val}</b>}</div>)}</div>;
      case 'schedule': return <div key={i} className="is-full"><Schedule v={v} /></div>;
      case 'diff': { const d = (Number(v.counted) || 0) - (ctx.cash || 0); return <div key={i} className="is-full">{d === 0 ? <Alert tone="success">المعدود يطابق رصيد النظام.</Alert> : <Alert tone="danger">فرق <Money value={d} showSign /> عن رصيد النظام — يلزم تفسير.</Alert>}</div>; }
      case 'files': return <ul key={i} className="kit-f-files is-full">{f.list.map((x) => <li key={x}><Icon name="Paperclip" size={14} /><span>{x}</span><Button size="sm" variant="ghost" iconOnly icon="Download" label="تنزيل" /></li>)}</ul>;
      case 'check': return <div key={i} className={cls}><Checkbox label={label} hint={f.hint} checked={!!v[f.k]} onChange={set(f.k)} /></div>;
      case 'radio': return <fieldset key={i} className={cls + ' kit-f-radio'}><legend>{label}</legend>{ev(f.o, ctx).map((o) => <label key={o.value} className={'kit-choice' + (v[f.k] === o.value ? ' is-on' : '')}><input type="radio" name={id + f.k} value={o.value} checked={v[f.k] === o.value} onChange={set(f.k)} /><span><b>{o.label}</b>{o.hint && <small>{o.hint}</small>}</span></label>)}</fieldset>;
    }
    let control;
    if (f.t === 'money') control = <MoneyInput value={v[f.k]} onChange={set(f.k)} />;
    else if (f.t === 'select') control = <Select value={v[f.k]} onChange={set(f.k)} placeholder={f.placeholder || (f.req ? 'اختر' : undefined)} options={ev(f.o, ctx)} />;
    else if (f.t === 'seg') control = <div><SegmentedControl label={label} value={v[f.k]} onChange={set(f.k)} options={ev(f.o, ctx).map((o) => ({ value: o, label: o }))} /></div>;
    else if (f.t === 'area') control = <TextInput multiline rows={3} value={v[f.k]} onChange={set(f.k)} placeholder={f.ph} />;
    else if (f.t === 'file') control = <FilePick value={v[f.k]} onChange={set(f.k)} accept={f.accept} />;
    else control = <TextInput ltr={f.t === 'ltr'} type={f.t === 'date' ? 'date' : undefined} inputMode={f.t === 'number' ? 'decimal' : undefined} value={v[f.k]} onChange={set(f.k)} placeholder={f.ph} />;
    return <Field key={i} className={cls} label={label} required={f.req} optional={f.opt} hint={f.hint} error={err}>{control}</Field>;
  };

  if (step === 'done') {
    const d = spec.done, tone = ev(d.tone, v) || 'success';
    return (
      <Dialog title={ev(d.title, v)} subtitle={subtitle || title} onClose={onClose} width={560}
        footer={<><Button variant="ghost" onClick={onClose}>إغلاق</Button><div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          {(d.next || []).map((n) => <Button key={n.label} variant={spec.doc ? 'secondary' : 'primary'} onClick={() => { onClose(); setTimeout(() => n.pay ? window.apPay && window.apPay() : window.apOpen(n.form, n.ctx || ctx), 50); }}>{n.label}</Button>)}
          {spec.doc && <Button icon="Printer" onClick={() => { onClose(); window.apDoc && window.apDoc(spec.doc, { ...ctx, ...v, title: title }); }}>معاينة وطباعة</Button>}
        </div></>}>
        <div className="kit-result"><span className={'kit-result__icon' + (tone === 'success' ? ' is-done' : '')}><Icon name={tone === 'success' ? 'CircleCheck' : 'TriangleAlert'} size={26} /></span>
          <div><strong style={{ fontSize: 16 }}>{ev(d.title, v)}</strong><p style={{ margin: '4px 0 0', fontSize: 13, color: 'var(--text-2)' }}>{ev(d.text, v)}</p></div></div>
        {summaryItems.length > 0 && <KeyValueList layout="rows" style={{ marginTop: 16 }} items={summaryItems.slice(0, 6)} />}
      </Dialog>
    );
  }
  const submitLabel = ev(spec.submit, ctx) || 'حفظ';
  return (
    <Dialog title={step === 'review' ? 'مراجعة قبل الحفظ' : title} subtitle={step === 'review' ? title : subtitle} onClose={onClose} busy={busy} width={spec.width || 620}
      footer={step === 'review'
        ? <><Button variant="secondary" icon="ChevronRight" onClick={() => setStep('form')} disabled={busy}>تعديل</Button><Button variant={spec.danger ? 'danger' : 'primary'} icon="Check" loading={busy} onClick={save}>{busy ? 'جارٍ الحفظ' : submitLabel}</Button></>
        : <><Button variant="secondary" onClick={onClose} disabled={busy}>إلغاء</Button><div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>{tried && missing.length > 0 && <span className="kit-f-missing">{missing.length} حقول مطلوبة</span>}<Button variant={spec.danger && !spec.review ? 'danger' : 'primary'} iconEnd={spec.review ? 'ChevronLeft' : undefined} icon={spec.review ? undefined : 'Check'} loading={busy} onClick={next}>{spec.review ? 'مراجعة' : busy ? 'جارٍ الحفظ' : submitLabel}</Button></div></>}>
      {step === 'review' ? <div style={{ display: 'grid', gap: 14 }}><KeyValueList layout="rows" items={summaryItems} />
        {spec.danger ? <Alert tone="danger">هذا الإجراء يُسجل باسمك ولا يُحذف؛ التصحيح يتم بإجراء معاكس.</Alert> : <Alert tone="neutral">راجع القيم. يُحفظ السجل باسمك ووقته ويظهر في سجل الأحداث.</Alert>}</div>
      : <div className="kit-form">{spec.intro && <Alert tone={spec.intro.tone} style={{ gridColumn: '1/-1' }}>{spec.intro.text}</Alert>}{visible.map(renderField)}</div>}
    </Dialog>
  );
}

// Generic printable document (A4) for statements, settlements and reports.
function DocView({ kind, ctx, onClose }) {
  const D = window.AP_DATA;
  let title = ctx.title, meta = [], cols = [], rows = [], foot = null, note = '';
  if (kind === 'ownerStatement' || kind === 'settlement') {
    const o = D.owners.find((x) => x.id === (ctx.owner || ctx.id)) || D.owners[0];
    title = kind === 'settlement' ? 'تصفية مالك — ' + (ctx.period || 'سبتمبر 2026') : 'كشف حساب مالك';
    meta = [['المالك', o.name], ['الفترة', kind === 'settlement' ? ctx.period || 'سبتمبر 2026' : (ctx.from || '').split('-').reverse().join('/') + ' – ' + (ctx.to || '').split('-').reverse().join('/')], ['الحالة', kind === 'settlement' ? 'مسودة — غير معتمدة' : 'للاطلاع']];
    cols = ['البند', 'المصدر', 'مدين', 'دائن'];
    rows = [['تحصيل المكتب — نقد وتحويل (مؤكد)', '14 سندًا', '', 48250], ['صيانة مكيف — وحدة 201', 'مصروف x1 · موافق', 850, ''], ['تنظيف الدرج', 'مصروف x2 · ضمن الاتفاق', 400, ''], ['أتعاب الإدارة 2.5٪', 'اتفاق g1', 1206.25, ''], ['تسليم سابق', '—', 0, '']];
    foot = ['صافي المستحق بحوزة المكتب', '', '', 45793.75];
    note = ctx.direct !== false ? 'تحويلات مباشرة للمالك خلال الفترة: 6,666.66 ر.س — للعلم، لم تدخل صندوق المكتب ولا تُحتسب أعلاه.' : '';
  } else {
    meta = [['الفترة', (ctx.from || '').split('-').reverse().join('/') + ' – ' + (ctx.to || '').split('-').reverse().join('/')], ['التجميع', ctx.group || '—'], ['المنشأة', D.org]];
    cols = ['العقار', 'الوحدات', 'مؤكد', 'بانتظار التحقق', 'متأخر'];
    rows = D.properties.map((p, i) => [p.name, p.units, [48250, 36400, 61800, 36400, 44000, 30000][i], [0, 0, 0, 5700, 0, 0][i], [9000, 3000, 13500, 0, 2200, 0][i]]);
    foot = ['الإجمالي', 102, 256850, 5700, 27700];
    note = 'بانتظار التحقق معروض منفصلًا ولا يدخل في «مؤكد».';
  }
  const { ApdDoc, ApdTable, ApdNote } = window;
  const isNum = (j) => rows.some((r) => typeof r[j] === 'number');
  const tcols = cols.map((l, j) => ({ l, n: j > 0 && isNum(j) }));
  const draft = kind === 'settlement';
  return (
    <ApdDoc onClose={onClose} kind={kind === 'settlement' ? 'تصفية' : kind === 'ownerStatement' ? 'كشف حساب' : 'تقرير تشغيلي'} title={title}
      ids={[['صدر', D.today], ['بواسطة', D.user.name]]} meta={meta.concat(meta.some(([k]) => k === 'المنشأة') ? [] : [['الجهة المصدرة', D.org]])}
      status={draft ? { tone: 'warn', text: 'مسودة — غير معتمدة' } : null} stamp={draft ? { tone: 'muted', text: 'مسودة' } : null}
      sign={draft ? null : ['أعده', 'اعتمده', 'الختم']}
      actions={<Button variant="onbrand" icon="Download">PDF</Button>}>
      <ApdTable cols={tcols} rows={rows} foot={foot} />
      {note && <ApdNote>{note}</ApdNote>}
    </ApdDoc>
  );
}

function FormHost() {
  const [stack, setStack] = React.useState(null);
  const [doc, setDoc] = React.useState(null);
  React.useEffect(() => {
    const h = (e) => setStack({ ...e.detail, key: Date.now() });
    window.addEventListener('ap-open', h);
    window.apDoc = (kind, ctx) => setDoc({ kind, ctx });
    return () => window.removeEventListener('ap-open', h);
  }, []);
  return <>{stack && window.AP_FORMS[stack.id] && <FormDialog key={stack.key} id={stack.id} ctx={stack.ctx} onClose={() => setStack(null)} />}{doc && <DocView {...doc} onClose={() => setDoc(null)} />}</>;
}

Object.assign(window, { FormHost, FormDialog, DocView });
})();
