// Molara — Workflow stepper
//
// A persistent progress bar shown across the top of every signed-in screen.
// Two flows:
//   Patient: Search → Doctor → Book → Pay → Consult → Follow-up
//   Doctor:  Incoming → In consult → Prescribe → Follow-up → Closed
//
// The "current step" is derived from the route + the latest active consult's
// state. Past steps are clickable; future steps are dimmed.

const PATIENT_STEPS = [
  { k: 'search',   label: 'Search',     icon: 'search',   route: '/find' },
  { k: 'doctor',   label: 'Dentist',    icon: 'user',     route: null /* /doctor?id=… */ },
  { k: 'book',     label: 'Book',       icon: 'calendar', route: '/book' },
  { k: 'pay',      label: 'Pay',        icon: 'card',     route: '/pay' },
  { k: 'consult',  label: 'Consult',    icon: 'video',    route: '/visit' },
  { k: 'followup', label: 'Follow-up',  icon: 'chat',     route: '/visit/summary' },
];

const DOCTOR_STEPS = [
  { k: 'incoming',  label: 'Incoming',   icon: 'bell',     tab: 'home' },
  { k: 'inconsult', label: 'In consult', icon: 'video',    tab: 'home' },
  { k: 'prescribe', label: 'Prescribe',  icon: 'doc',      tab: 'home' },
  { k: 'followup',  label: 'Follow-up',  icon: 'chat',     tab: 'home' },
  { k: 'closed',    label: 'Closed',     icon: 'check',    tab: 'appointments' },
];

// Patient — figure out which step is "current" given the route and consult state.
function patientCurrentStep(route, consults) {
  const path = route.split('?')[0];
  if (path.startsWith('/visit/summary')) return 'followup';
  if (path.startsWith('/visit'))         return 'consult';
  if (path.startsWith('/pay'))           return 'pay';
  if (path.startsWith('/payments'))      return 'pay';
  if (path.startsWith('/confirmed'))     return 'consult';
  if (path.startsWith('/book'))          return 'book';
  if (path.startsWith('/instant'))       return 'consult';
  if (path.startsWith('/doctor'))        return 'doctor';
  if (path.startsWith('/find'))          return 'search';
  if (path.startsWith('/dashboard') || path === '/') {
    // On the dashboard? infer from latest consult progress
    const active = (consults || []).find((c) => !c.completed && !c.endedAt);
    if (active) {
      if (active.startedAt) return 'consult';
      if (active.paymentStatus === 'paid' || active.paid) return 'consult';
      return 'pay';
    }
    return 'search';
  }
  return 'search';
}

// How far has the patient progressed overall? (used to decide which steps are
// reachable / dimmed). Returns the index of the furthest step reached.
function patientFurthest(consults) {
  if (!consults || consults.length === 0) return 0;
  const c = consults[consults.length - 1];
  if (c.completed || c.endedAt) return 5;
  if (c.startedAt)              return 4;
  if (c.paymentStatus === 'paid' || c.paid) return 3;
  return 2; // booked
}

// Doctor — current step from the active consult on their dashboard.
function doctorCurrentStep(consults) {
  const active = (consults || []).find((c) => c.startedAt && !c.endedAt);
  if (active) return 'inconsult';
  const recentlyEnded = (consults || []).find((c) => c.endedAt && !c.prescribed);
  if (recentlyEnded) return 'prescribe';
  const followup = (consults || []).find((c) => c.prescribed && !c.followupClosed);
  if (followup) return 'followup';
  const upcoming = (consults || []).find((c) => !c.startedAt && !c.endedAt);
  if (upcoming) return 'incoming';
  return 'closed';
}

function doctorFurthest(consults) {
  if (!consults || consults.length === 0) return 0;
  const states = consults.map((c) => {
    if (c.followupClosed) return 4;
    if (c.prescribed)     return 3;
    if (c.endedAt)        return 2;
    if (c.startedAt)      return 1;
    return 0;
  });
  return Math.max(...states);
}

// ---------- Component ----------
function WorkflowStepper({ role, route, consults, onStepClick }) {
  const isDoc = role === 'doctor';
  const steps = isDoc ? DOCTOR_STEPS : PATIENT_STEPS;
  const current = isDoc ? doctorCurrentStep(consults) : patientCurrentStep(route, consults);
  const furthest = isDoc ? doctorFurthest(consults) : patientFurthest(consults);
  const currentIdx = Math.max(0, steps.findIndex((s) => s.k === current));

  const containerStyle = {
    display: 'flex', alignItems: 'stretch',
    gap: 0,
    padding: '14px 28px',
    background: '#fff',
    borderBottom: '1px solid var(--line)',
    fontFamily: 'var(--sans)',
    overflowX: 'auto',
    scrollbarWidth: 'none',
  };

  return (
    <div className="ml-stepper" style={containerStyle}>
      <style>{`
        .ml-stepper::-webkit-scrollbar { display: none; }
        .ml-stepper-step {
          display: flex; align-items: center; gap: 9px;
          padding: 8px 14px; border-radius: 999px;
          background: transparent; border: none; cursor: pointer;
          font-family: inherit; font-size: 12.5px;
          color: var(--ink-3); white-space: nowrap;
          transition: background 120ms, color 120ms;
        }
        .ml-stepper-step:hover:not([data-state="future"]) {
          background: var(--paper-2);
        }
        .ml-stepper-step[data-state="current"] {
          background: var(--blue-soft); color: var(--blue-deep);
          font-weight: 500;
        }
        .ml-stepper-step[data-state="done"] { color: var(--ink-2); }
        .ml-stepper-step[data-state="future"] { color: var(--ink-3); opacity: 0.5; cursor: default; }
        .ml-stepper-dot {
          width: 22px; height: 22px; border-radius: 50%;
          display: grid; place-items: center; flex-shrink: 0;
          background: var(--paper-2); color: var(--ink-3);
          font-size: 11px; font-weight: 600;
          font-family: var(--mono);
        }
        .ml-stepper-step[data-state="current"] .ml-stepper-dot {
          background: var(--blue-deep); color: #fff;
        }
        .ml-stepper-step[data-state="done"] .ml-stepper-dot {
          background: oklch(85% 0.10 165); color: oklch(35% 0.13 165);
        }
        .ml-stepper-arrow {
          align-self: center;
          color: var(--line-2);
          flex-shrink: 0;
          margin: 0 -2px;
        }
      `}</style>
      {steps.map((s, idx) => {
        const Icon = I[s.icon] || I.pulse;
        const state = idx === currentIdx ? 'current' : (idx < currentIdx || idx <= furthest) ? 'done' : 'future';
        const isClickable = state !== 'future';
        const num = idx + 1;
        return (
          <React.Fragment key={s.k}>
            <button
              className="ml-stepper-step"
              data-state={state}
              disabled={!isClickable}
              onClick={() => isClickable && onStepClick && onStepClick(s)}
              title={s.label}
            >
              <span className="ml-stepper-dot">
                {state === 'done' ? <I.check size={11}/> : num}
              </span>
              <Icon size={13}/>
              {s.label}
            </button>
            {idx < steps.length - 1 && (
              <svg className="ml-stepper-arrow" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <path d="M9 6l6 6-6 6"/>
              </svg>
            )}
          </React.Fragment>
        );
      })}
    </div>
  );
}

// Default click handler — patient flow
function patientStepClick(step, consults) {
  if (step.k === 'doctor') {
    const last = (consults || [])[consults.length - 1];
    if (last && last.docId) {
      window.navigate && window.navigate(`/doctor?id=${last.docId}`);
      return;
    }
    window.navigate && window.navigate('/find');
    return;
  }
  if (step.k === 'book') {
    const last = (consults || [])[consults.length - 1];
    if (last && last.docId) {
      window.navigate && window.navigate(`/book?doctor=${last.docId}`);
      return;
    }
    window.navigate && window.navigate('/find');
    return;
  }
  if (step.k === 'consult') {
    const active = (consults || []).find((c) => !c.completed && !c.endedAt);
    if (active) {
      // Joinable? otherwise bounce to /pay.
      const j = window.consultIsJoinable && window.consultIsJoinable(active);
      if (j && !j.ok) {
        window.navigate && window.navigate(`/pay?consult=${active.id}`);
      } else {
        window.navigate && window.navigate(`/visit?consult=${active.id}`);
      }
      return;
    }
  }
  if (step.k === 'pay') {
    const active = (consults || []).find((c) => !c.completed && !c.endedAt);
    if (active && active.paymentStatus !== 'paid') {
      window.navigate && window.navigate(`/pay?consult=${active.id}`);
      return;
    }
    window.navigate && window.navigate('/payments');
    return;
  }
  if (step.k === 'followup') {
    const last = (consults || [])[consults.length - 1];
    if (last) {
      window.navigate && window.navigate(`/visit/summary?consult=${last.id}`);
      return;
    }
  }
  if (step.route) window.navigate && window.navigate(step.route);
}

function doctorStepClick(step) {
  if (step.tab && window.location && window.location.hash) {
    window.location.hash = `/doctor-dashboard?tab=${step.tab}`;
  }
}

window.WorkflowStepper = WorkflowStepper;
window.patientStepClick = patientStepClick;
window.doctorStepClick = doctorStepClick;
