// ═══════════════════════════════════════════════════════════════
//  Coordinator-facing UX helpers:
//   • getCoordNextActions  – compute prioritized "what to do next"
//   • NextActionCard       – hero card on coord dashboard
//   • WorkflowStepper      – 6-step linear progress for an activity
// ═══════════════════════════════════════════════════════════════

// ───────────────────────────────────────────────
//  The 6 canonical steps in an activity lifecycle
// ───────────────────────────────────────────────
// Steps aligned EXACTLY with the status badges the coord sees.
// 6 stages: plan → approve → execute → report → approved-for-payment → paid
window.WORKFLOW_STEPS = [
  { key: 'plan',    label: 'תכנון',          icon: 'FileText'    },
  { key: 'approve', label: 'אושר עקרונית',   icon: 'CheckCircle' },
  { key: 'execute', label: 'בביצוע',         icon: 'Activity'    },
  { key: 'report',  label: 'דווח ביצוע',     icon: 'Upload'      },
  { key: 'approved',label: 'אושר לתשלום',    icon: 'Receipt'     },
  { key: 'paid',    label: 'שולם',           icon: 'CheckCircle' },
];

// Returns {current, done[]}. "done" = step fully complete; "current" = step
// actively in progress (first not-done). Mapping matches deriveStatus() precisely.
window.activityStepState = function(activity) {
  if (!activity) return { current: 0, done: [] };
  const done = [];
  // 1. plan — always done once activity exists
  done.push('plan');

  // 2. approve — principleApproval = approved OR skipped (2025 call)
  const approved = activity.principleApproval === 'approved' || activity.principleApproval === 'skipped';
  if (approved) done.push('approve');

  // 3. execute — approved AND activity has started
  const inExec = approved && (activity.startDate || activity.actualActivityCost);
  if (inExec) done.push('execute');

  // 4. report — execution fully reported & approved by national coord
  const reported = activity.totalActualBudget > 0 && activity.executionApproval === 'approved';
  if (reported) done.push('report');

  // 5. approved-for-payment — reached the payment pipeline. Includes audit
  //    pending/approved and the payment_pending gate. Matches badge "אושר לתשלום".
  const inPaymentFlow = reported && (
    activity.auditStatus === 'pending' ||
    activity.auditStatus === 'approved' ||
    activity.auditStatus === 'returned'
  );
  if (inPaymentFlow) done.push('approved');

  // 6. paid — ministry paid
  const paid = activity.paymentApproval === 'approved';
  if (paid) { if (!done.includes('approved')) done.push('approved'); done.push('paid'); }

  // current = first not-done, or last if all done
  const current = window.WORKFLOW_STEPS.findIndex(s => !done.includes(s.key));
  return { current: current === -1 ? 5 : current, done };
};

// ───────────────────────────────────────────────
//  WorkflowStepper — compact horizontal progress pill
// ───────────────────────────────────────────────
window.WorkflowStepper = function WorkflowStepper({ activity, compact = false }) {
  const { current, done } = window.activityStepState(activity);
  const Icon = window.Icon;

  return (
    <div className={`flex items-center ${compact ? 'gap-1' : 'gap-1.5'}`}>
      {window.WORKFLOW_STEPS.map((step, i) => {
        const isDone = done.includes(step.key);
        const isCurrent = i === current && !isDone;
        const I = Icon[step.icon] || Icon.CheckCircle;
        const size = compact ? 18 : 22;
        const iconSize = compact ? 10 : 12;
        return (
          <React.Fragment key={step.key}>
            <div
              title={`${i + 1}. ${step.label}${isDone ? ' ✓' : isCurrent ? ' (שלב נוכחי)' : ''}`}
              className={`shrink-0 rounded-full flex items-center justify-center transition-all
                ${isDone ? 'bg-emerald-500 text-white' :
                  isCurrent ? 'bg-brand-600 text-white ring-2 ring-brand-200 animate-pulse' :
                  'bg-slate-200 text-slate-400'}`}
              style={{ width: size, height: size }}
            >
              {isDone ? <Icon.CheckCircle size={iconSize}/> : <I size={iconSize}/>}
            </div>
            {i < window.WORKFLOW_STEPS.length - 1 && (
              <div className={`h-0.5 flex-1 transition-colors ${isDone && done.includes(window.WORKFLOW_STEPS[i + 1].key) ? 'bg-emerald-500' : isDone ? 'bg-brand-300' : 'bg-slate-200'}`} style={{ minWidth: compact ? 8 : 14 }}/>
            )}
          </React.Fragment>
        );
      })}
    </div>
  );
};

// ───────────────────────────────────────────────
//  WorkflowStepperLabeled — horizontal with labels
//  (used on activity detail page for bigger visual)
// ───────────────────────────────────────────────
window.WorkflowStepperLabeled = function WorkflowStepperLabeled({ activity }) {
  const { current, done } = window.activityStepState(activity);
  const Icon = window.Icon;
  return (
    <div className="w-full overflow-x-auto">
      <div className="flex items-start gap-0 min-w-[480px]">
        {window.WORKFLOW_STEPS.map((step, i) => {
          const isDone = done.includes(step.key);
          const isCurrent = i === current && !isDone;
          const I = Icon[step.icon] || Icon.CheckCircle;
          return (
            <React.Fragment key={step.key}>
              <div className="flex flex-col items-center gap-1.5 flex-1">
                <div className={`w-10 h-10 rounded-full flex items-center justify-center transition-all
                  ${isDone ? 'bg-emerald-500 text-white shadow-lg shadow-emerald-200' :
                    isCurrent ? 'bg-brand-600 text-white shadow-lg shadow-brand-200 ring-4 ring-brand-100' :
                    'bg-slate-100 text-slate-400 border border-slate-200'}`}>
                  {isDone ? <Icon.CheckCircle size={20}/> : <I size={18}/>}
                </div>
                <div className={`text-[11px] font-bold ${isDone ? 'text-emerald-700' : isCurrent ? 'text-brand-700' : 'text-slate-400'}`}>
                  {step.label}
                </div>
                {isCurrent && <div className="text-[10px] text-brand-600 -mt-1">שלב נוכחי</div>}
              </div>
              {i < window.WORKFLOW_STEPS.length - 1 && (
                <div className="flex-1 pt-5">
                  <div className={`h-1 rounded-full transition-colors ${
                    isDone && done.includes(window.WORKFLOW_STEPS[i + 1].key) ? 'bg-emerald-500' :
                    isDone ? 'bg-gradient-to-l from-slate-200 to-emerald-500' :
                    'bg-slate-200'}`}/>
                </div>
              )}
            </React.Fragment>
          );
        })}
      </div>
    </div>
  );
};

// ───────────────────────────────────────────────
//  getCoordNextActions — compute prioritized todo list for local coord
// ───────────────────────────────────────────────
window.getCoordNextActions = function(state, currentUser) {
  if (!currentUser || currentUser.role !== 'local') return [];
  const auth = (state.authorities || []).find(a => a.id === currentUser.authorityId);
  const activities = (state.activities || []).filter(a => a.authorityId === auth?.id);
  const payments = (state.paymentRequests || []).filter(r => r.authorityId === auth?.id);

  const requiredClusters = ['strategy', 'education', 'welfare'];
  const missingClusters = requiredClusters.filter(id => !activities.some(a => a.cluster === id));

  const needsReport = activities.filter(a =>
    (a.principleApproval === 'approved' || a.principleApproval === 'skipped') &&
    !a.totalActualBudget
  );

  const readyForAudit = activities.filter(a =>
    a.executionApproval === 'approved' &&
    (!a.auditStatus || a.auditStatus === 'returned') &&
    (a.paymentEvidence || []).length > 0
  );

  const auditApprovedNotBundled = activities.filter(a =>
    a.auditStatus === 'approved' &&
    !payments.some(p => (p.activityIds || []).includes(a.id))
  );

  const signablePayments = payments.filter(p => p.status === 'draft' && !p.coordSignedAt);
  const awaitingTreasurer = payments.filter(p => p.coordSignedAt && !p.treasurerSignedAt);
  const readyToDownload = payments.filter(p => p.status === 'fully-signed');

  const actions = [];

  if (activities.length === 0) {
    actions.push({
      priority: 'primary',
      icon: 'Plus',
      title: 'התחל את תכנית העבודה',
      description: 'הוסף פעילות ראשונה כדי להתחיל',
      ctaLabel: 'פעילות חדשה',
      ctaNav: 'new-activity',
      tone: 'brand'
    });
    return actions;
  }

  if (missingClusters.length > 0) {
    actions.push({
      priority: 'primary',
      icon: 'AlertCircle',
      title: `חסרות פעילויות ב-${missingClusters.length} אשכולות`,
      description: `יש להוסיף פעילות בכל אחד: ${missingClusters.map(id => window.clusterById(id)?.shortName).join(' · ')}`,
      ctaLabel: 'הוסף פעילות',
      ctaNav: 'new-activity',
      tone: 'amber'
    });
  }

  if (readyToDownload.length > 0) {
    const req = readyToDownload[0];
    actions.push({
      priority: 'primary',
      icon: 'Download',
      title: `הורד PDF חתום — דרישה #${req.reqNum}`,
      description: 'כל החתימות הושלמו. ההורדה מגישה את החבילה למשרד.',
      ctaLabel: 'פתח דרישה',
      ctaNav: 'payments',
      tone: 'emerald'
    });
  }

  if (signablePayments.length > 0) {
    const req = signablePayments[0];
    actions.push({
      priority: 'primary',
      icon: 'Edit',
      title: `חתום על דרישת תשלום #${req.reqNum}`,
      description: 'אשד אישר — חתימתך תפתח את שליחת הקישור לגזבר',
      ctaLabel: 'לחתימה',
      ctaNav: 'payments',
      tone: 'brand'
    });
  }

  if (awaitingTreasurer.length > 0) {
    const req = awaitingTreasurer[0];
    actions.push({
      priority: 'primary',
      icon: 'Send',
      title: `שלח קישור לגזבר — דרישה #${req.reqNum}`,
      description: 'הגזבר חותם דיגיטלית דרך קישור של 24 שעות',
      ctaLabel: 'צור קישור',
      ctaNav: 'payments',
      tone: 'cyan'
    });
  }

  if (auditApprovedNotBundled.length > 0) {
    actions.push({
      priority: 'secondary',
      icon: 'Receipt',
      title: `${auditApprovedNotBundled.length} פעילויות מוכנות לחבילת תשלום`,
      description: 'כל הפעילויות עברו בקרה — צור דרישת תשלום לאגוד שלהן',
      ctaLabel: 'צור דרישת תשלום',
      ctaNav: 'payments',
      tone: 'emerald'
    });
  }

  if (readyForAudit.length > 0) {
    actions.push({
      priority: 'secondary',
      icon: 'Shield',
      title: `${readyForAudit.length} פעילויות מוכנות לבקרת אשד`,
      description: 'חשבוניות הועלו ודווחו — שלח לבקרה',
      ctaLabel: 'שלח לבקרה',
      ctaNav: 'payments',
      tone: 'purple'
    });
  }

  if (needsReport.length > 0) {
    actions.push({
      priority: 'secondary',
      icon: 'Upload',
      title: `דווח ביצוע על ${needsReport.length} פעילויות`,
      description: 'פעילויות שאושרו עקרונית ומחכות לדיווח סכומים בפועל וחשבוניות',
      ctaLabel: 'לתכנית העבודה',
      ctaNav: 'programs',
      tone: 'blue'
    });
  }

  // Nothing urgent — encouragement message
  if (actions.length === 0) {
    actions.push({
      priority: 'primary',
      icon: 'CheckCircle',
      title: 'הכל מעודכן — כל הכבוד!',
      description: 'אין צעדים דחופים כרגע. המשך מעקב אחר פעילויות פעילות.',
      ctaLabel: 'לתכנית העבודה',
      ctaNav: 'programs',
      tone: 'emerald'
    });
  }

  return actions;
};

// ───────────────────────────────────────────────
//  NextActionCard — hero card on coord dashboard
// ───────────────────────────────────────────────
window.NextActionCard = function NextActionCard() {
  const { state, currentUser } = window.useApp();
  const { navigate } = window.useRouter();
  const actions = window.getCoordNextActions(state, currentUser);
  if (!actions.length) return null;

  const [primary, ...rest] = actions.filter(a => a.priority === 'primary')
    .concat(actions.filter(a => a.priority === 'secondary'));
  const secondary = rest.slice(0, 3);

  const toneClasses = {
    brand:   { bg: 'from-brand-600 to-indigo-600',  ring: 'ring-brand-200' },
    emerald: { bg: 'from-emerald-600 to-teal-600',  ring: 'ring-emerald-200' },
    amber:   { bg: 'from-amber-500 to-orange-500',  ring: 'ring-amber-200' },
    cyan:    { bg: 'from-cyan-600 to-sky-600',      ring: 'ring-cyan-200' },
    purple:  { bg: 'from-purple-600 to-fuchsia-600',ring: 'ring-purple-200' },
    blue:    { bg: 'from-blue-600 to-brand-700',    ring: 'ring-blue-200' },
  };
  const t = toneClasses[primary.tone] || toneClasses.brand;
  const PIcon = window.Icon[primary.icon] || window.Icon.Activity;

  return (
    <div className="mb-6 animate-fade-in">
      <div className={`rounded-2xl bg-gradient-to-br ${t.bg} text-white p-6 shadow-xl shadow-slate-200 relative overflow-hidden`}>
        {/* Decorative blobs */}
        <div className="absolute -top-20 -left-20 w-60 h-60 rounded-full bg-white/5 pointer-events-none"/>
        <div className="absolute -bottom-12 -right-12 w-40 h-40 rounded-full bg-white/5 pointer-events-none"/>

        <div className="relative flex items-start gap-4">
          <div className={`w-14 h-14 rounded-2xl bg-white/20 backdrop-blur flex items-center justify-center shrink-0 ring-4 ${t.ring} ring-opacity-30`}>
            <PIcon size={28}/>
          </div>
          <div className="flex-1 min-w-0">
            <div className="text-xs font-bold uppercase tracking-wider opacity-80 mb-1">הצעד הבא שלך</div>
            <div className="font-display font-black text-xl md:text-2xl leading-tight mb-1">{primary.title}</div>
            <div className="text-sm opacity-90 mb-4">{primary.description}</div>
            <button
              onClick={() => navigate(primary.ctaNav)}
              className="inline-flex items-center gap-2 px-5 py-2.5 rounded-xl bg-white text-slate-900 font-bold text-sm hover:bg-slate-50 transition-all hover:scale-[1.02] active:scale-[0.98] shadow-lg"
            >
              {primary.ctaLabel}
              <window.Icon.ChevronLeft size={16}/>
            </button>
          </div>
        </div>

        {secondary.length > 0 && (
          <div className="relative mt-5 pt-4 border-t border-white/20">
            <div className="text-[11px] font-bold uppercase tracking-wider opacity-70 mb-2">גם בתור — משימות נוספות</div>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-2">
              {secondary.map((a, i) => {
                const AIcon = window.Icon[a.icon] || window.Icon.Activity;
                return (
                  <button
                    key={i}
                    onClick={() => navigate(a.ctaNav)}
                    className="text-right flex items-center gap-2.5 p-2.5 rounded-lg bg-white/10 hover:bg-white/20 transition-colors group"
                  >
                    <div className="w-8 h-8 rounded-lg bg-white/20 flex items-center justify-center shrink-0">
                      <AIcon size={14}/>
                    </div>
                    <div className="flex-1 min-w-0">
                      <div className="text-xs font-bold truncate">{a.title}</div>
                      <div className="text-[10px] opacity-80 truncate">{a.ctaLabel}</div>
                    </div>
                    <window.Icon.ChevronLeft size={14} className="opacity-50 group-hover:opacity-100"/>
                  </button>
                );
              })}
            </div>
          </div>
        )}
      </div>
    </div>
  );
};
