// ═══════════════════════════════════════════════════════════════
//  Payment Request — bundle activities, sign flow, treasurer link
// ═══════════════════════════════════════════════════════════════

const { useState: uSPR, useEffect: uEPR, useRef: uRPR, useMemo: uMPR } = React;

// ───────────────────────────────────────────────
//  Helper — check activity fully ready to bundle
// ───────────────────────────────────────────────
window.isActivityReadyForBundle = function(a) {
  return a.executionApproval === 'approved'
      && a.auditStatus === 'approved'
      && !a.paymentRequestId;
};

// ───────────────────────────────────────────────
//  Payment Request page — list + create + sign
// ───────────────────────────────────────────────
window.PaymentRequestsPage = function PaymentRequestsPage() {
  const { state, currentUser, createPaymentRequest, updatePaymentRequest, upsertActivity,
          coordSignPaymentRequest, generateTreasurerToken, sendToAudit } = window.useApp();
  const { navigate } = window.useRouter();
  const toast = window.useToast();
  const [tab, setTab] = uSPR('needs-audit');
  const [createOpen, setCreateOpen] = uSPR(false);
  const [openRequestId, setOpenRequestId] = uSPR(null);
  const [auditSelected, setAuditSelected] = uSPR(new Set());

  // Scope to user
  let scope = [...state.activities];
  if (currentUser.role === 'local') scope = scope.filter(a => a.authorityId === currentUser.authorityId);
  if (currentUser.role === 'national') {
    const myAuths = state.authorities.filter(x => x.nationalCoordinatorId === currentUser.id).map(x => x.id);
    scope = scope.filter(a => myAuths.includes(a.authorityId));
  }

  // Activities ready to SEND TO AUDIT (execution approved, no audit yet)
  const readyForAudit = scope.filter(a =>
    a.executionApproval === 'approved' &&
    a.totalActualBudget &&
    !a.auditStatus &&
    !a.paymentApproval
  );
  // Activities AT AUDIT (pending eshed review)
  const atAudit = scope.filter(a => a.auditStatus === 'pending');
  // Activities ready to bundle into a new request (audit-approved, not yet in any request)
  const readyToBundle = scope.filter(a => window.isActivityReadyForBundle(a));
  const allRequests = (state.paymentRequests || []).filter(r => {
    if (currentUser.role === 'local') return r.authorityId === currentUser.authorityId;
    if (currentUser.role === 'national') {
      const myAuths = state.authorities.filter(x => x.nationalCoordinatorId === currentUser.id).map(x => x.id);
      return myAuths.includes(r.authorityId);
    }
    return true;
  });

  const byStatus = {
    draft: allRequests.filter(r => r.status === 'draft'),
    awaitingTreasurer: allRequests.filter(r => r.status === 'awaiting-treasurer'),
    fullySigned: allRequests.filter(r => r.status === 'fully-signed' || r.status === 'submitted'),
  };

  const openRequest = allRequests.find(r => r.id === openRequestId);

  return (
    <div className="animate-fade-in">
      <window.PageHeader
        title="דרישות תשלום"
        subtitle="צעד 1: שליחה לבקרת אשד · צעד 2: אשד מאשרת · צעד 3: חבילה · צעד 4: חתימה · צעד 5: גזבר · צעד 6: הורדה"
        actions={
          currentUser.role === 'local' && readyToBundle.length > 0 && (
            <window.Button variant="primary" icon={<window.Icon.Plus size={16}/>} onClick={() => setCreateOpen(true)}>
              יצירת חבילה חדשה · {readyToBundle.length} זמינות
            </window.Button>
          )
        }
      />

      {/* Quick stats */}
      <div className="grid grid-cols-2 lg:grid-cols-5 gap-3 mb-5">
        <window.StatCard icon="Send"        label="שליחה לבקרה"          value={<window.AnimatedNumber value={readyForAudit.length}/>}        sublabel="אחרי ביצוע" accent="#f59e0b"/>
        <window.StatCard icon="Shield"      label="בבקרת אשד"           value={<window.AnimatedNumber value={atAudit.length}/>}             sublabel="ממתין לאישור" accent="#8b5cf6"/>
        <window.StatCard icon="Check"       label="זמין לחבילה"          value={<window.AnimatedNumber value={readyToBundle.length}/>}       sublabel="מאושר ע״י אשד" accent="#06b6d4"/>
        <window.StatCard icon="Edit"        label="בחתימות"             value={<window.AnimatedNumber value={byStatus.draft.length + byStatus.awaitingTreasurer.length}/>} sublabel="טיוטות + גזבר" accent="#ec4899"/>
        <window.StatCard icon="CheckCircle" label="חתומות"              value={<window.AnimatedNumber value={byStatus.fullySigned.length}/>} sublabel="מוכנות להגשה" accent="#10b981"/>
      </div>

      {/* Tabs */}
      <div className="surface mb-5 p-2 overflow-x-auto">
        <window.Tabs tabs={[
          { value: 'needs-audit',  label: '1. שליחה לבקרה', count: readyForAudit.length },
          { value: 'at-audit',     label: '2. בבקרת אשד',   count: atAudit.length },
          { value: 'ready',        label: '3. לחבילה',       count: readyToBundle.length },
          { value: 'draft',        label: '4. טיוטות',       count: byStatus.draft.length },
          { value: 'awaiting',     label: '5. גזבר',         count: byStatus.awaitingTreasurer.length },
          { value: 'signed',       label: '6. חתומות',       count: byStatus.fullySigned.length }
        ]} value={tab} onChange={setTab}/>
      </div>

      {/* Tab: Needs audit — has execution approval, needs to be sent */}
      {tab === 'needs-audit' && (
        <div className="surface">
          {readyForAudit.length === 0 ? (
            <window.EmptyState icon="Send" title="אין פעילויות הממתינות לשליחה לבקרה"
              description={`פעילויות מופיעות כאן אחרי אישור ביצוע + העלאת חשבוניות ותיעוד מהשטח.`}/>
          ) : (
            <>
              <div className="p-4 bg-amber-50 border-b border-amber-100 flex items-center justify-between gap-3 flex-wrap">
                <div className="flex items-center gap-2">
                  <button onClick={() => setAuditSelected(auditSelected.size === readyForAudit.length ? new Set() : new Set(readyForAudit.map(a => a.id)))}
                    className={`custom-check ${auditSelected.size === readyForAudit.length ? 'checked' : ''}`}>
                    {auditSelected.size === readyForAudit.length && <window.Icon.Check size={12} className="text-white"/>}
                  </button>
                  <span className="text-sm font-semibold">
                    {auditSelected.size > 0 ? `${auditSelected.size} פעילויות נבחרו` : 'בחר פעילויות לשליחה לבקרת אשד'}
                  </span>
                </div>
                <window.Button variant="primary" size="sm" icon={<window.Icon.Shield size={14}/>} disabled={auditSelected.size === 0}
                  onClick={() => {
                    // Verify each has invoices + field docs (or explanation)
                    const missing = Array.from(auditSelected).map(id => state.activities.find(a => a.id === id))
                      .filter(a => {
                        const hasInvoices = (a.paymentEvidence || []).length > 0;
                        const hasFieldDocs = (a.fieldDocumentation || []).length > 0 || (a.noDocumentationReason || '').trim().length > 10;
                        return !hasInvoices || !hasFieldDocs;
                      });
                    if (missing.length > 0) {
                      toast.push({ type: 'error', title: 'חסרים קבצים',
                        message: `${missing.length} פעילויות חסרות חשבוניות או תיעוד מהשטח/הסבר` });
                      return;
                    }
                    sendToAudit(Array.from(auditSelected));
                    toast.push({ type: 'success', title: 'נשלח לבקרת אשד', message: `${auditSelected.size} פעילויות ממתינות לאישור` });
                    setAuditSelected(new Set());
                    setTab('at-audit');
                  }}>שלח לבקרת אשד</window.Button>
              </div>
              <table className="data-table">
                <thead><tr>
                  <th style={{ width: 40 }}></th><th>פעילות</th><th>ספק</th><th>יחידות</th><th>סכום</th><th>חשבוניות</th><th>תיעוד</th>
                </tr></thead>
                <tbody>
                  {readyForAudit.map(a => {
                    const on = auditSelected.has(a.id);
                    const hasInvoices = (a.paymentEvidence || []).length > 0;
                    const hasFieldDocs = (a.fieldDocumentation || []).length > 0 || (a.noDocumentationReason || '').length > 10;
                    return (
                      <tr key={a.id} onClick={() => setAuditSelected(prev => { const s = new Set(prev); if (s.has(a.id)) s.delete(a.id); else s.add(a.id); return s; })}
                        className={`cursor-pointer ${on ? 'bg-amber-50' : ''}`}>
                        <td><div className={`custom-check ${on ? 'checked' : ''}`}>{on && <window.Icon.Check size={12} className="text-white"/>}</div></td>
                        <td>
                          <div className="flex items-center gap-2">
                            <span className="text-[10px] font-bold px-1.5 py-0.5 rounded bg-slate-100">{a.activityCode}</span>
                            <span className="font-semibold text-sm">{a.activityName}</span>
                          </div>
                        </td>
                        <td className="text-sm">{a.supplierName || '—'}</td>
                        <td className="text-sm">{a.completedUnits}/{a.units}</td>
                        <td><span className="font-bold ltr-num text-brand-700">{window.formatMoney(a.totalActualBudget)}</span></td>
                        <td>
                          {hasInvoices ? (
                            <span className="text-xs text-emerald-600">✓ {(a.paymentEvidence || []).length}</span>
                          ) : (
                            <button
                              onClick={e => { e.stopPropagation(); navigate('activity-detail', { id: a.id }); }}
                              className="text-xs text-red-600 font-bold hover:text-red-800 hover:underline flex items-center gap-1 focus-visible:ring-2 focus-visible:ring-red-500 rounded px-1"
                              title="לחץ לעבור לדף הפעילות ולהעלות חשבוניות"
                            >
                              ✗ חסר <window.Icon.ChevronLeft size={10}/>
                            </button>
                          )}
                        </td>
                        <td>
                          {hasFieldDocs ? (
                            <span className="text-xs text-emerald-600">✓ קיים</span>
                          ) : (
                            <button
                              onClick={e => { e.stopPropagation(); navigate('activity-detail', { id: a.id }); }}
                              className="text-xs text-red-600 font-bold hover:text-red-800 hover:underline flex items-center gap-1 focus-visible:ring-2 focus-visible:ring-red-500 rounded px-1"
                              title="לחץ לעבור לדף הפעילות ולהעלות תיעוד/הסבר"
                            >
                              ✗ חסר <window.Icon.ChevronLeft size={10}/>
                            </button>
                          )}
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </>
          )}
        </div>
      )}

      {/* Tab: At audit — waiting for Eshed */}
      {tab === 'at-audit' && (
        <div className="surface">
          {atAudit.length === 0 ? (
            <window.EmptyState icon="Shield" title="אין פעילויות בבקרה" description="לאחר שליחה, הפעילויות ייבחנו ע״י חברת אשד"/>
          ) : (
            <table className="data-table">
              <thead><tr><th>פעילות</th><th>ספק</th><th>סכום</th><th>נשלח בתאריך</th><th>סטטוס</th></tr></thead>
              <tbody>
                {atAudit.map(a => (
                  <tr key={a.id}>
                    <td><strong className="text-sm">{a.activityCode} · {a.activityName}</strong></td>
                    <td className="text-sm">{a.supplierName || '—'}</td>
                    <td><span className="font-bold ltr-num text-brand-700">{window.formatMoney(a.totalActualBudget)}</span></td>
                    <td className="text-sm">{window.formatDate(a.auditSentAt)}</td>
                    <td><span className="text-xs font-semibold text-violet-700 bg-violet-100 px-2 py-1 rounded-full inline-flex items-center gap-1">
                      <window.Icon.Clock size={11}/> בבקרה · אשד
                    </span></td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
      )}

      {/* Content */}
      {tab === 'ready' && (
        <div className="surface">
          {readyToBundle.length === 0 ? (
            <window.EmptyState icon="Receipt" title="אין פעילויות מוכנות לחבילה"
              description={`פעילויות מופיעות כאן רק אחרי שאשד אישרה אותן. אחרי הבחירה, תוכל לארגן אותן בחבילת דרישת תשלום ולחתום.`}/>
          ) : (
            <table className="data-table">
              <thead><tr>
                <th>פעילות</th><th>רשות</th><th>רבעון</th><th>ספק</th><th>סכום</th><th>אישור אשד</th>
              </tr></thead>
              <tbody>
                {readyToBundle.map(a => {
                  const auth = state.authorities.find(x => x.id === a.authorityId);
                  return (
                    <tr key={a.id} onClick={() => navigate('activity-detail', { id: a.id })} className="cursor-pointer">
                      <td>
                        <div className="flex items-center gap-2">
                          <span className="text-[10px] font-bold px-1.5 py-0.5 rounded bg-slate-100">{a.activityCode}</span>
                          <span className="font-semibold text-sm">{a.activityName}</span>
                        </div>
                      </td>
                      <td><window.AuthorityChip authority={auth} size="xs"/></td>
                      <td className="text-sm">{a.quarter}</td>
                      <td className="text-sm">{a.supplierName || '—'}</td>
                      <td><span className="font-bold ltr-num text-brand-700">{window.formatMoney(a.totalActualBudget)}</span></td>
                      <td>
                        <span className="text-xs font-semibold text-emerald-700 inline-flex items-center gap-1 bg-emerald-50 px-2 py-0.5 rounded">
                          <window.Icon.CheckCircle size={11}/>אושר
                        </span>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          )}
          {currentUser.role === 'local' && readyToBundle.length > 0 && (
            <div className="p-4 bg-emerald-50 border-t border-emerald-100 text-center">
              <window.Button variant="success" icon={<window.Icon.Plus size={16}/>} onClick={() => setCreateOpen(true)}>
                יצירת חבילת תשלום חדשה
              </window.Button>
            </div>
          )}
        </div>
      )}

      {(tab === 'draft' || tab === 'awaiting' || tab === 'signed') && (
        <div className="space-y-3">
          {(() => {
            const list = tab === 'draft' ? byStatus.draft : tab === 'awaiting' ? byStatus.awaitingTreasurer : byStatus.fullySigned;
            if (list.length === 0) return <window.EmptyState icon="Receipt" title="אין חבילות בקטגוריה זו"/>;
            return list.map(req => <window.PaymentRequestCard key={req.id} request={req} onOpen={() => setOpenRequestId(req.id)}/>);
          })()}
        </div>
      )}

      {/* Modals */}
      {createOpen && <window.CreatePaymentRequestModal activities={readyToBundle} onClose={() => setCreateOpen(false)}/>}
      {openRequest && <window.PaymentRequestDetailModal request={openRequest} onClose={() => setOpenRequestId(null)}/>}
    </div>
  );
};

// ───────────────────────────────────────────────
//  Card for each payment request in lists
// ───────────────────────────────────────────────
window.PaymentRequestCard = function PaymentRequestCard({ request, onOpen }) {
  const { state } = window.useApp();
  const auth = state.authorities.find(a => a.id === request.authorityId);
  const activities = state.activities.filter(a => request.activityIds?.includes(a.id));
  const total = activities.reduce((s, a) => s + (a.totalActualBudget || 0), 0);

  const statusMeta = {
    'draft': { label: 'טיוטה', color: '#f59e0b', bg: 'bg-amber-100', text: 'text-amber-800' },
    'awaiting-treasurer': { label: 'ממתין לחתימת גזבר', color: '#06b6d4', bg: 'bg-cyan-100', text: 'text-cyan-800' },
    'fully-signed': { label: 'חתום ומוכן', color: '#10b981', bg: 'bg-emerald-100', text: 'text-emerald-800' },
    'submitted': { label: 'הוגש למשרד', color: '#059669', bg: 'bg-green-100', text: 'text-green-800' }
  }[request.status] || { label: request.status, color: '#64748b', bg: 'bg-slate-100', text: 'text-slate-700' };

  return (
    <button onClick={onOpen} className="surface p-5 w-full text-right card-hover animate-fade-in">
      <div className="flex items-start justify-between gap-4">
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2 flex-wrap mb-2">
            <span className="font-display font-bold text-base">#{request.reqNum}</span>
            <span className={`text-[11px] font-semibold px-2 py-0.5 rounded-full ${statusMeta.bg} ${statusMeta.text}`}>
              {statusMeta.label}
            </span>
            <window.AuthorityChip authority={auth} size="xs"/>
            <span className="text-[11px] text-slate-500">· רבעון {request.quarter}/{request.year}</span>
          </div>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-3 text-xs mt-3">
            <div><span className="text-slate-500">פעילויות:</span> <strong>{activities.length}</strong></div>
            <div><span className="text-slate-500">סכום:</span> <strong className="ltr-num text-brand-700">{window.formatMoney(total)}</strong></div>
            <div><span className="text-slate-500">נוצר:</span> <strong>{window.formatDate(request.createdAt)}</strong></div>
            <div><span className="text-slate-500">רכז:</span> <strong>{request.coordSignedAt ? '✓ חתום' : '—'}</strong></div>
          </div>
        </div>
        <window.Icon.ChevronLeft size={18} className="text-slate-400 mt-2"/>
      </div>
    </button>
  );
};

// ───────────────────────────────────────────────
//  Create Payment Request Modal
// ───────────────────────────────────────────────
window.CreatePaymentRequestModal = function CreatePaymentRequestModal({ activities, onClose }) {
  const { state, currentUser, createPaymentRequest, upsertActivity } = window.useApp();
  const toast = window.useToast();
  const { navigate } = window.useRouter();

  const byQuarter = uMPR(() => {
    const m = {};
    activities.forEach(a => {
      if (!m[a.quarter]) m[a.quarter] = [];
      m[a.quarter].push(a);
    });
    return m;
  }, [activities]);

  const quarters = Object.keys(byQuarter).sort();
  const [selectedQuarter, setSelectedQuarter] = uSPR(quarters[0] || '');
  const [selected, setSelected] = uSPR(new Set());

  uEPR(() => {
    // Select all in the first quarter by default
    if (selectedQuarter && byQuarter[selectedQuarter]) {
      setSelected(new Set(byQuarter[selectedQuarter].map(a => a.id)));
    }
  }, [selectedQuarter]);

  const qActs = byQuarter[selectedQuarter] || [];
  const selectedActs = qActs.filter(a => selected.has(a.id));
  const total = selectedActs.reduce((s, a) => s + (a.totalActualBudget || 0), 0);

  const toggle = (id) => {
    setSelected(prev => {
      const s = new Set(prev);
      if (s.has(id)) s.delete(id); else s.add(id);
      return s;
    });
  };

  const submit = () => {
    if (!selectedActs.length) { toast.push({ type: 'error', message: 'יש לבחור לפחות פעילות אחת' }); return; }
    const authorityId = selectedActs[0].authorityId;
    const [q, y] = selectedQuarter.match(/Q(\d)\s*-\s*(\d{4})/)?.slice(1) || ['1', '2026'];

    const reqId = createPaymentRequest({
      authorityId,
      quarter: q, year: y,
      activityIds: selectedActs.map(a => a.id),
      totalAmount: total
    });

    // Tag activities with request id
    selectedActs.forEach(a => upsertActivity({ ...a, paymentRequestId: reqId }));

    toast.push({ type: 'success', title: 'חבילה נוצרה', message: `${selectedActs.length} פעילויות · ${window.formatMoney(total)}` });
    onClose();
  };

  return (
    <window.Modal open={true} onClose={onClose} title="יצירת חבילת דרישת תשלום" size="lg"
      footer={
        <>
          <window.Button variant="outline" onClick={onClose}>ביטול</window.Button>
          <window.Button variant="success" icon={<window.Icon.Plus size={16}/>} onClick={submit}
            disabled={selectedActs.length === 0}>
            צור חבילה · {selectedActs.length} פעילויות · <span className="ltr-num">{window.formatMoney(total)}</span>
          </window.Button>
        </>
      }>
      <p className="text-sm text-slate-600 mb-4">
        בחר רבעון ופעילויות להכללה בחבילה. הפעילויות ישויכו לחבילה הזו בלבד ולא יהיו זמינות לחבילה אחרת.
      </p>

      <window.Field label="רבעון" required>
        <div className="flex gap-2 flex-wrap">
          {quarters.map(q => (
            <button key={q} onClick={() => setSelectedQuarter(q)}
              className={`px-3 py-1.5 rounded-lg text-sm font-semibold transition-all ${selectedQuarter === q ? 'bg-brand-600 text-white' : 'bg-slate-100 text-slate-600 hover:bg-slate-200'}`}>
              {q} ({byQuarter[q].length})
            </button>
          ))}
        </div>
      </window.Field>

      <div className="mt-4">
        <div className="flex items-center justify-between mb-2">
          <label className="text-xs font-semibold text-slate-600">פעילויות ברבעון {selectedQuarter}</label>
          <button onClick={() => setSelected(selected.size === qActs.length ? new Set() : new Set(qActs.map(a => a.id)))}
            className="text-xs text-brand-700 hover:underline">
            {selected.size === qActs.length ? 'בטל הכל' : 'בחר הכל'}
          </button>
        </div>
        <div className="border border-slate-200 rounded-lg divide-y divide-slate-100 max-h-72 overflow-y-auto">
          {qActs.map(a => {
            const auth = state.authorities.find(x => x.id === a.authorityId);
            const on = selected.has(a.id);
            return (
              <button key={a.id} onClick={() => toggle(a.id)}
                className={`w-full p-3 flex items-center gap-3 text-right transition-colors ${on ? 'bg-brand-50' : 'hover:bg-slate-50'}`}>
                <div className={`custom-check ${on ? 'checked' : ''}`}>
                  {on && <window.Icon.Check size={12} className="text-white"/>}
                </div>
                <div className="flex-1 min-w-0">
                  <div className="text-sm font-semibold truncate">{a.activityCode} · {a.activityName}</div>
                  <div className="text-[11px] text-slate-500">{a.supplierName || '—'} · {a.completedUnits}/{a.units} יחידות</div>
                </div>
                <div className="font-bold text-sm text-brand-700 ltr-num">{window.formatMoney(a.totalActualBudget)}</div>
              </button>
            );
          })}
        </div>
        {selected.size > 0 && (
          <div className="mt-3 p-3 rounded-lg bg-emerald-50 border border-emerald-200 flex items-center justify-between">
            <span className="text-sm font-semibold text-emerald-900">סה"כ נבחרו</span>
            <span className="font-display font-black text-lg text-emerald-700 ltr-num">{window.formatMoney(total)}</span>
          </div>
        )}
      </div>
    </window.Modal>
  );
};

// ───────────────────────────────────────────────
//  Payment Request Detail Modal (sign, link, download)
// ───────────────────────────────────────────────
window.PaymentRequestDetailModal = function PaymentRequestDetailModal({ request, onClose }) {
  const { state, currentUser, coordSignPaymentRequest, generateTreasurerToken, updatePaymentRequest } = window.useApp();
  const toast = window.useToast();
  const auth = state.authorities.find(a => a.id === request.authorityId);
  const activities = state.activities.filter(a => request.activityIds?.includes(a.id));
  const total = activities.reduce((s, a) => s + (a.totalActualBudget || 0), 0);

  const [showTokenLink, setShowTokenLink] = uSPR(null);
  const [signOpen, setSignOpen] = uSPR(false);
  const [coordSignature, setCoordSignature] = uSPR(null);

  const submitCoordSign = () => {
    if (!coordSignature) { toast.push({ type: 'error', message: 'נא לחתום ידנית על גבי השדה' }); return; }
    coordSignPaymentRequest(request.id, coordSignature);
    setSignOpen(false);
    setCoordSignature(null);
    toast.push({ type: 'success', title: 'חתימת הרכז נוספה', message: 'כעת ניתן לשלוח קישור לגזבר לחתימה' });
  };

  const generateLink = () => {
    const token = generateTreasurerToken(request.id);
    const link = `${location.origin}/?sign=${token}`;
    setShowTokenLink(link);
    if (auth?.treasurerEmail) {
      toast.push({ type: 'info', title: 'קישור חתימה נוצר',
        message: `שלח ב-email ל-${auth.treasurerEmail}. תקף 24 שעות.` });
    } else {
      toast.push({ type: 'warning', title: 'קישור נוצר',
        message: 'לא נמצא email של גזבר ברשות. הקישור הועתק, שלח ידנית.' });
    }
  };

  const copyLink = () => {
    navigator.clipboard.writeText(showTokenLink);
    toast.push({ type: 'success', message: 'הקישור הועתק' });
  };

  const canCoordSign = currentUser.role === 'local' && request.status === 'draft' && !request.coordSignedAt;
  const canGenerateLink = request.status === 'awaiting-treasurer' || (request.coordSignedAt && !request.treasurerSignedAt);

  return (
    <window.Modal open={true} onClose={onClose} title={`חבילת תשלום #${request.reqNum}`} size="lg"
      footer={<window.Button variant="outline" onClick={onClose}>סגור</window.Button>}>
      {/* Summary */}
      <div className="p-4 rounded-xl bg-gradient-to-br from-brand-50 to-indigo-50 border border-brand-100 mb-4">
        <div className="grid grid-cols-2 md:grid-cols-4 gap-3 text-sm">
          <div>
            <div className="text-[10px] text-brand-700 font-semibold">רשות</div>
            <div className="font-bold">{auth?.name}</div>
          </div>
          <div>
            <div className="text-[10px] text-brand-700 font-semibold">רבעון</div>
            <div className="font-bold">Q{request.quarter}/{request.year}</div>
          </div>
          <div>
            <div className="text-[10px] text-brand-700 font-semibold">פעילויות</div>
            <div className="font-bold">{activities.length}</div>
          </div>
          <div>
            <div className="text-[10px] text-brand-700 font-semibold">סכום</div>
            <div className="font-bold ltr-num text-brand-900">{window.formatMoney(total)}</div>
          </div>
        </div>
      </div>

      {/* Workflow steps */}
      <div className="mb-5">
        <div className="flex items-center gap-2 mb-3">
          <window.Icon.Activity size={16} className="text-brand-600"/>
          <h3 className="font-display font-bold text-sm">מצב החתימות</h3>
        </div>
        <div className="space-y-2">
          {/* Step 1: Audit */}
          <div className="p-3 rounded-lg bg-emerald-50 border border-emerald-200 flex items-center gap-3">
            <div className="w-8 h-8 rounded-full bg-emerald-500 text-white flex items-center justify-center">
              <window.Icon.CheckCircle size={16}/>
            </div>
            <div className="flex-1">
              <div className="font-semibold text-sm">1. אישור חברת בקרה (אשד)</div>
              <div className="text-[11px] text-emerald-700">כל הפעילויות אושרו</div>
            </div>
            <span className="text-xs text-emerald-700 font-bold">✓ הושלם</span>
          </div>

          {/* Step 2: Coord */}
          <div className={`rounded-lg border ${request.coordSignedAt ? 'bg-emerald-50 border-emerald-200' : 'bg-amber-50 border-amber-200'}`}>
            <div className="p-3 flex items-center gap-3">
              <div className={`w-8 h-8 rounded-full text-white flex items-center justify-center ${request.coordSignedAt ? 'bg-emerald-500' : 'bg-amber-500'}`}>
                {request.coordSignedAt ? <window.Icon.CheckCircle size={16}/> : <window.Icon.Edit size={14}/>}
              </div>
              <div className="flex-1">
                <div className="font-semibold text-sm">2. חתימת רכז הפרויקט</div>
                <div className="text-[11px] text-slate-600">
                  {request.coordSignedAt ? `נחתם ${window.formatDate(request.coordSignedAt)}` : 'ממתין לחתימה'}
                </div>
              </div>
              {canCoordSign && !signOpen && (
                <window.Button variant="primary" size="sm" icon={<window.Icon.Edit size={12}/>} onClick={() => setSignOpen(true)}>חתום</window.Button>
              )}
              {request.coordSignedAt && request.coordSignature && (
                <img src={request.coordSignature} alt="חתימת רכז" className="h-10 max-w-[120px] object-contain bg-white rounded border border-emerald-200 p-0.5"/>
              )}
            </div>
            {canCoordSign && signOpen && (
              <div className="border-t border-amber-200 p-3 bg-white/70">
                <div className="text-xs font-semibold text-slate-700 mb-2">
                  אני, {currentUser.name}, מצהיר/ה בזאת כי בדקתי את דו"ח הביצוע ומאשר/ת את הגשת דרישת התשלום.
                </div>
                <window.SignaturePad value={coordSignature} onChange={setCoordSignature} height={140}/>
                <div className="flex items-center justify-end gap-2 mt-3">
                  <window.Button variant="outline" size="sm" onClick={() => { setSignOpen(false); setCoordSignature(null); }}>ביטול</window.Button>
                  <window.Button variant="success" size="sm" icon={<window.Icon.CheckCircle size={12}/>} onClick={submitCoordSign} disabled={!coordSignature}>אשר וחתום</window.Button>
                </div>
              </div>
            )}
          </div>

          {/* Step 3: Treasurer */}
          <div className={`p-3 rounded-lg border flex items-center gap-3 ${request.treasurerSignedAt ? 'bg-emerald-50 border-emerald-200' : request.coordSignedAt ? 'bg-cyan-50 border-cyan-200' : 'bg-slate-50 border-slate-200'}`}>
            <div className={`w-8 h-8 rounded-full text-white flex items-center justify-center ${request.treasurerSignedAt ? 'bg-emerald-500' : request.coordSignedAt ? 'bg-cyan-500' : 'bg-slate-300'}`}>
              {request.treasurerSignedAt ? <window.Icon.CheckCircle size={16}/> : <window.Icon.Send size={14}/>}
            </div>
            <div className="flex-1">
              <div className="font-semibold text-sm">3. חתימת גזבר הרשות</div>
              <div className="text-[11px] text-slate-600">
                {request.treasurerSignedAt ? `נחתם ${window.formatDate(request.treasurerSignedAt)} ע״י ${request.treasurerSignerName || 'גזבר'}`
                  : request.treasurerToken ? `קישור תקף עד ${window.formatDate(request.treasurerTokenExpiresAt)}`
                  : 'טרם נשלח קישור'}
              </div>
            </div>
            {canGenerateLink && !request.treasurerSignedAt && (
              <window.Button variant="primary" size="sm" icon={<window.Icon.Send size={12}/>} onClick={generateLink}>
                {request.treasurerToken ? 'חדש קישור' : 'שלח לגזבר'}
              </window.Button>
            )}
            {request.treasurerSignedAt && request.treasurerSignature && (
              <img src={request.treasurerSignature} alt="חתימת גזבר" className="h-10 max-w-[120px] object-contain bg-white rounded border border-emerald-200 p-0.5"/>
            )}
          </div>

          {/* Step 4: Download */}
          <div className={`p-3 rounded-lg border flex items-center gap-3 ${request.status === 'fully-signed' ? 'bg-emerald-50 border-emerald-200' : 'bg-slate-50 border-slate-200'}`}>
            <div className={`w-8 h-8 rounded-full text-white flex items-center justify-center ${request.status === 'fully-signed' ? 'bg-emerald-500' : 'bg-slate-300'}`}>
              <window.Icon.Download size={14}/>
            </div>
            <div className="flex-1">
              <div className="font-semibold text-sm">4. הורדת חבילה חתומה</div>
              <div className="text-[11px] text-slate-600">
                {request.status === 'fully-signed' ? 'כל החתימות הושלמו' : 'ממתין לחתימות קודמות'}
              </div>
            </div>
            {request.status === 'fully-signed' && (
              <window.Button variant="success" size="sm" icon={<window.Icon.Download size={12}/>} onClick={async () => {
                toast.push({ type: 'info', message: 'מייצר PDF מלא...' });
                await window.generatePaymentPackagePDF(activities, state, {
                  quarter: request.quarter, year: request.year, requestNumber: request.reqNum, request
                });
                updatePaymentRequest(request.id, { status: 'submitted' });
                toast.push({ type: 'success', title: 'החבילה הוגשה', message: 'סטטוס עודכן ל״הוגש למשרד״' });
              }}>הורד וסמן כמוגש</window.Button>
            )}
          </div>
        </div>
      </div>

      {/* Token link modal */}
      {showTokenLink && (
        <div className="p-4 rounded-xl bg-cyan-50 border-2 border-cyan-300 mt-4">
          <div className="flex items-start gap-2 mb-3">
            <window.Icon.Info size={18} className="text-cyan-700 shrink-0 mt-0.5"/>
            <div className="text-sm">
              <div className="font-bold text-cyan-900">קישור חתימה נוצר</div>
              <div className="text-xs text-cyan-800 mt-1">תקף ל-24 שעות. הגזבר נכנס ללא סיסמה ורואה רק את טופס דרישת התשלום לחתימה.</div>
              {auth?.treasurerEmail ? (
                <div className="text-xs text-cyan-800 mt-1">שלח את הקישור במייל ל-<strong>{auth.treasurerName}</strong> ({auth.treasurerEmail})</div>
              ) : (
                <div className="text-xs text-amber-800 mt-1">⚠ לא הוגדר גזבר ברשות. הוסף פרטים בעריכת הרשות.</div>
              )}
            </div>
          </div>
          <div className="flex gap-2">
            <input readOnly value={showTokenLink} className="input text-xs ltr-num flex-1 bg-white"/>
            <window.Button variant="primary" size="sm" icon={<window.Icon.FileText size={12}/>} onClick={copyLink}>העתק</window.Button>
          </div>
        </div>
      )}

      {/* Activities in package */}
      <div className="mt-5">
        <div className="text-xs font-semibold text-slate-500 mb-2">פעילויות בחבילה ({activities.length})</div>
        <div className="border border-slate-200 rounded-lg divide-y divide-slate-100 max-h-60 overflow-y-auto">
          {activities.map(a => (
            <div key={a.id} className="p-2.5 flex items-center gap-2 text-xs">
              <span className="font-bold text-slate-700 min-w-[40px]">{a.activityCode}</span>
              <span className="flex-1 truncate">{a.activityName}</span>
              <span className="font-bold text-brand-700 ltr-num">{window.formatMoney(a.totalActualBudget)}</span>
            </div>
          ))}
        </div>
      </div>
    </window.Modal>
  );
};
