// Supplier Approval Workflow — visualizes the full registration → approval lifecycle.
// Stages: Registration submitted → Procurement review → Compliance check → CEO approval → Approved.

const WORKFLOW_STAGES = [
  {
    id: 'submitted',
    label: 'Registration Submitted',
    short: 'Submitted',
    actor: 'Supplier',
    actorRole: 'Self-service portal',
    icon: 'send',
    blurb: 'Supplier completes the 5-step registration form: company, contacts, bank, documents, review.',
    duration: 'Same day',
    artifacts: ['Trade License', 'VAT Certificate', 'Chamber of Commerce', 'Insurance', 'Bank IBAN'],
    actions: ['Form auto-saved at every step', 'Documents validated for type and expiry', 'Submission acknowledged via email'],
  },
  {
    id: 'procurement',
    label: 'Procurement Review',
    short: 'Procurement',
    actor: 'Aisha Al Mansouri',
    actorRole: 'Procurement Lead',
    icon: 'eye',
    blurb: 'Procurement verifies business fit, checks for duplicate records, and confirms which group companies will engage.',
    duration: '1–3 days',
    artifacts: ['Capability assessment', 'Group-company assignment', 'Pre-qualification notes'],
    actions: ['Verify legal name against trade license', 'Cross-check against existing supplier list', 'Tag relevant group companies'],
  },
  {
    id: 'compliance',
    label: 'Compliance Check',
    short: 'Compliance',
    actor: 'Layla Hassan',
    actorRole: 'Compliance Officer',
    icon: 'shield',
    blurb: 'Compliance validates documents with issuing authorities and runs sanctions / blacklist screening.',
    duration: '2–5 days',
    artifacts: ['Document validity audit', 'Sanctions screening report', 'TRN authority lookup'],
    actions: ['Verify Trade License with DED', 'Confirm VAT TRN with FTA', 'Run UN / OFAC sanctions check', 'Approve or flag for clarification'],
  },
  {
    id: 'ceo',
    label: 'CEO Approval',
    short: 'CEO Sign-off',
    actor: 'Saif Al Khyeli',
    actorRole: 'Group CEO',
    icon: 'check',
    blurb: 'CEO reviews the dossier, approves the supplier for engagement, and authorizes PO issuance.',
    duration: 'Within 24 h of compliance pass',
    artifacts: ['Executive summary', 'Risk score', 'Digital signature on approval letter'],
    actions: ['Review consolidated dossier', 'Approve, request changes, or reject', 'Sign approval letter'],
  },
  {
    id: 'approved',
    label: 'Approved & Onboarded',
    short: 'Approved',
    actor: 'System',
    actorRole: 'Automated',
    icon: 'sparkle',
    blurb: 'Supplier is activated. Welcome email sent, supplier portal access provisioned, ready to receive POs.',
    duration: 'Immediate',
    artifacts: ['Welcome email', 'Supplier portal credentials', 'PO issuance unlocked'],
    actions: ['Status flipped to Approved', 'Supplier notified by email', 'Procurement officer assigned'],
  },
];

// Example timeline tied to Cedar IT Solutions (s03 in the data — currently pending).
const EXAMPLE_TIMELINE = [
  { stage: 'submitted',  date: '18 Apr 2026', time: '09:42', actor: 'Priya Krishnan',     note: 'Submitted registration with 4 documents and 2 contacts.' },
  { stage: 'procurement', date: '19 Apr 2026', time: '11:15', actor: 'Aisha Al Mansouri', note: 'Pre-qualified. Assigned to Saif Holdings + Saif Services.' },
  { stage: 'procurement', date: '22 Apr 2026', time: '14:08', actor: 'Aisha Al Mansouri', note: 'Capability call scheduled. Forwarded to compliance.' },
  { stage: 'compliance',  date: '24 Apr 2026', time: '10:30', actor: 'Layla Hassan',      note: 'Trade License verified with DED. VAT TRN confirmed.' },
  { stage: 'compliance',  date: '27 Apr 2026', time: '16:22', actor: 'Layla Hassan',      note: 'Sanctions screening clear. Recommending approval.' },
  { stage: 'ceo',         date: '28 Apr 2026', time: '09:00', actor: 'Saif Al Khyeli',    note: 'Dossier received for executive review.', pending: true },
];

const ApprovalWorkflowPage = () => {
  const [active, setActive] = React.useState(3); // CEO stage — where Cedar IT currently sits
  const [playing, setPlaying] = React.useState(false);
  const playRef = React.useRef(null);

  React.useEffect(() => {
    if (!playing) { clearInterval(playRef.current); return; }
    playRef.current = setInterval(() => {
      setActive(a => {
        if (a >= WORKFLOW_STAGES.length - 1) { setPlaying(false); return WORKFLOW_STAGES.length - 1; }
        return a + 1;
      });
    }, 1400);
    return () => clearInterval(playRef.current);
  }, [playing]);

  const replay = () => { setActive(0); setPlaying(true); };

  const current = WORKFLOW_STAGES[active];
  const exampleEntries = EXAMPLE_TIMELINE.filter(e => WORKFLOW_STAGES.findIndex(s => s.id === e.stage) <= active);

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1 className="page-title">Supplier Approval Workflow</h1>
          <p className="page-subtitle">How a supplier moves from registration to approved — five stages, four owners, one signature.</p>
        </div>
        <div className="page-actions">
          <button className="btn" onClick={() => { setActive(0); setPlaying(false); }}>
            <Icon name="chevronLeft" size={13}/> Reset
          </button>
          {playing ? (
            <button className="btn btn-primary" onClick={() => setPlaying(false)}>
              <Icon name="pause" size={13}/> Pause
            </button>
          ) : (
            <button className="btn btn-accent" onClick={replay}>
              <Icon name="play" size={13}/> Play walkthrough
            </button>
          )}
        </div>
      </div>

      {/* Live example banner */}
      <div className="wf-example-banner">
        <Avatar name="Cedar IT Solutions" size="md" tone="oklch(0.62 0.14 290)"/>
        <div style={{ flex: 1 }}>
          <div className="wf-eb-title">Live example · <b>Cedar IT Solutions</b></div>
          <div className="wf-eb-sub">Submitted 18 Apr · currently <b>awaiting CEO approval</b> · 10 days in flight</div>
        </div>
        <Badge kind="amber">In progress</Badge>
      </div>

      {/* Big horizontal flow diagram */}
      <div className="wf-flow">
        <div className="wf-track">
          <div className="wf-track-fill" style={{ width: `${(active / (WORKFLOW_STAGES.length - 1)) * 100}%` }}/>
        </div>
        <div className="wf-stages">
          {WORKFLOW_STAGES.map((s, i) => {
            const state = i < active ? 'done' : i === active ? 'active' : 'pending';
            return (
              <button key={s.id} className="wf-stage" data-state={state} onClick={() => { setPlaying(false); setActive(i); }}>
                <div className="wf-stage-num">Stage {i + 1}</div>
                <div className="wf-stage-circle">
                  {state === 'done' ? <Icon name="check" size={18}/> :
                   state === 'active' ? <Icon name={s.icon} size={18}/> :
                   <Icon name={s.icon} size={18}/>}
                  {state === 'active' && <span className="wf-stage-pulse"/>}
                </div>
                <div className="wf-stage-label">{s.label}</div>
                <div className="wf-stage-actor">{s.actor}</div>
                <div className="wf-stage-role">{s.actorRole}</div>
              </button>
            );
          })}
        </div>
      </div>

      {/* Active stage detail */}
      <div className="wf-detail-grid">
        <div className="card wf-stage-card">
          <div className="card-header">
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <div className={`wf-detail-icon wf-detail-${current.id}`}><Icon name={current.icon} size={18}/></div>
              <div>
                <div className="wf-detail-pre">Stage {active + 1} of {WORKFLOW_STAGES.length}</div>
                <h3 className="card-title">{current.label}</h3>
              </div>
            </div>
            <Badge kind={active === WORKFLOW_STAGES.length - 1 ? 'green' : active === 0 ? 'blue' : 'accent'}>
              {active === WORKFLOW_STAGES.length - 1 ? 'Final' : active === 0 ? 'Entry' : 'Review gate'}
            </Badge>
          </div>
          <div className="card-body">
            <p className="wf-blurb">{current.blurb}</p>

            <div className="wf-meta-row">
              <div>
                <div className="wf-meta-label">Owner</div>
                <div className="wf-meta-val">{current.actor}</div>
                <div className="wf-meta-sub">{current.actorRole}</div>
              </div>
              <div>
                <div className="wf-meta-label">Typical duration</div>
                <div className="wf-meta-val">{current.duration}</div>
              </div>
              <div>
                <div className="wf-meta-label">Outcome</div>
                <div className="wf-meta-val">
                  {current.id === 'submitted' ? 'Application queued' :
                   current.id === 'approved' ? 'Active supplier' : 'Pass / clarify / reject'}
                </div>
              </div>
            </div>

            <div className="wf-section-label">What happens here</div>
            <ul className="wf-list">
              {current.actions.map((a, i) => (
                <li key={i}><span className="wf-list-dot"/>{a}</li>
              ))}
            </ul>

            <div className="wf-section-label">Artifacts produced</div>
            <div className="wf-chips">
              {current.artifacts.map((a, i) => (
                <span key={i} className="wf-chip"><Icon name="file" size={11}/> {a}</span>
              ))}
            </div>
          </div>
        </div>

        {/* Audit trail for live example */}
        <div className="card">
          <div className="card-header">
            <h3 className="card-title">Audit trail · Cedar IT</h3>
            <span className="text-xs text-mute">{exampleEntries.length} of {EXAMPLE_TIMELINE.length} events</span>
          </div>
          <div className="card-body" style={{ padding: 0 }}>
            <div className="wf-timeline">
              {EXAMPLE_TIMELINE.map((e, i) => {
                const stageIdx = WORKFLOW_STAGES.findIndex(s => s.id === e.stage);
                const reached = stageIdx <= active;
                return (
                  <div key={i} className="wf-tl-item" data-reached={reached} data-pending={e.pending}>
                    <div className="wf-tl-rail">
                      <div className="wf-tl-dot">
                        {e.pending && reached ? <span className="wf-tl-dot-pulse"/> :
                         reached ? <Icon name="check" size={10}/> : null}
                      </div>
                      {i < EXAMPLE_TIMELINE.length - 1 && <div className="wf-tl-line"/>}
                    </div>
                    <div className="wf-tl-content">
                      <div className="wf-tl-head">
                        <span className="wf-tl-actor">{e.actor}</span>
                        <span className="wf-tl-when">{e.date} · {e.time}</span>
                      </div>
                      <div className="wf-tl-note">{e.note}</div>
                      <div className="wf-tl-stage">{WORKFLOW_STAGES[stageIdx].short}</div>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      </div>

      {/* Decisions / branching */}
      <div className="card" style={{ marginTop: 18 }}>
        <div className="card-header">
          <h3 className="card-title">Decision points</h3>
          <span className="text-xs text-mute">Where applications can be paused, returned, or rejected</span>
        </div>
        <div className="card-body" style={{ padding: 0 }}>
          <div className="wf-decisions">
            {[
              { gate: 'Procurement review', pass: 'Forward to compliance', fail: 'Return to supplier for clarification', reject: 'Decline (industry / capability mismatch)' },
              { gate: 'Compliance check', pass: 'Forward to CEO', fail: 'Request updated documents', reject: 'Decline (failed sanctions / authority verification)' },
              { gate: 'CEO approval', pass: 'Mark as approved & onboard', fail: 'Send back to compliance with notes', reject: 'Decline (executive discretion)' },
            ].map((d, i) => (
              <div key={i} className="wf-decision">
                <div className="wf-decision-gate">
                  <Icon name="workflow" size={13}/> {d.gate}
                </div>
                <div className="wf-decision-branches">
                  <div className="wf-branch wf-branch-pass">
                    <span className="wf-branch-arrow">→</span>
                    <div><span className="wf-branch-tag">Pass</span>{d.pass}</div>
                  </div>
                  <div className="wf-branch wf-branch-back">
                    <span className="wf-branch-arrow">↺</span>
                    <div><span className="wf-branch-tag">Return</span>{d.fail}</div>
                  </div>
                  <div className="wf-branch wf-branch-reject">
                    <span className="wf-branch-arrow">✕</span>
                    <div><span className="wf-branch-tag">Reject</span>{d.reject}</div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { ApprovalWorkflowPage });
