// ============================================================
// Appointment-appears tutorial popup (Medical)
// Polls hsp_appointments after the first chat send. The row only
// exists once the AI workflow actually books a slot, so the
// existence check is already substantive. We fetch the full row
// so we can preview the booking details inside the popup.
// ============================================================

(function () {
  const CONFIG = {
    table:         'hsp_appointments',
    phoneCol:      'patient_phone',
    select:        'id,patient_name,doctor_name,specialty_code,scheduled_for,duration_min,status,reason_for_visit',
    targetSection: 'appointments',
    targetLabel:   'Appointments',
    recordNoun:    'appointment',
    pollMs:        180000, // 3 min — AI booking flow can take a while
    intervalMs:    3000,
    initialDelayMs: 4000
  };

  function fmtSchedule(iso) {
    if (!iso) return '';
    try {
      const d = new Date(iso);
      const day = d.toLocaleDateString('en-US', { weekday: 'short', day: 'numeric', month: 'short' });
      const tm  = d.toTimeString().slice(0, 5);
      return day + ' · ' + tm;
    } catch (e) { return iso; }
  }

  function buildPreview(row) {
    const out = [];
    if (row.patient_name && row.patient_name !== 'New Patient') {
      out.push({ label: 'Patient', value: row.patient_name });
    }
    if (row.doctor_name) {
      const spec = row.specialty_code ? ' · ' + row.specialty_code : '';
      out.push({ label: 'Doctor', value: row.doctor_name + spec });
    }
    if (row.scheduled_for) {
      const dur = row.duration_min ? ' (' + row.duration_min + ' min)' : '';
      out.push({ label: 'When', value: fmtSchedule(row.scheduled_for) + dur });
    }
    if (row.reason_for_visit) out.push({ label: 'Reason', value: row.reason_for_visit });
    if (row.status) out.push({ label: 'Status', value: row.status });
    return out;
  }

  const firedFor = new Set();
  let activePoll = null;

  window.__leadTutorial = {
    async pollAndFire(sessionPhone) {
      if (!sessionPhone || firedFor.has(sessionPhone)) return;
      if (activePoll === sessionPhone) return;
      activePoll = sessionPhone;
      await new Promise(r => setTimeout(r, CONFIG.initialDelayMs));
      const deadline = Date.now() + CONFIG.pollMs;
      try {
        while (Date.now() < deadline) {
          try {
            const rows = await window.__api.sbGet(CONFIG.table, {
              'select':          CONFIG.select,
              [CONFIG.phoneCol]: 'eq.' + sessionPhone,
              'order':           'scheduled_for.desc',
              'limit':           '1'
            });
            const row = rows && rows[0];
            if (row) {
              firedFor.add(sessionPhone);
              window.dispatchEvent(new CustomEvent('lead-tutorial-show', {
                detail: { rowId: row.id, section: CONFIG.targetSection, label: CONFIG.targetLabel, noun: CONFIG.recordNoun, preview: buildPreview(row) }
              }));
              return;
            }
          } catch (e) { /* keep polling */ }
          await new Promise(r => setTimeout(r, CONFIG.intervalMs));
        }
      } finally {
        if (activePoll === sessionPhone) activePoll = null;
      }
    }
  };

  const { useState: useStateTp, useEffect: useEffectTp } = React;

  const LeadTutorialPopup = () => {
    const [state, setState] = useStateTp(null);
    useEffectTp(() => {
      const onShow = (e) => setState(e.detail);
      window.addEventListener('lead-tutorial-show', onShow);
      return () => window.removeEventListener('lead-tutorial-show', onShow);
    }, []);
    if (!state) return null;
    const close = () => setState(null);
    const goThere = () => {
      window.__pulseRowId = state.rowId;
      window.dispatchEvent(new CustomEvent('nav-to-section', { detail: state.section }));
      setState(null);
    };
    const preview = state.preview || [];
    return (
      <div className="lead-tutorial-overlay" onClick={close}>
        <div className="lead-tutorial-modal" onClick={(e) => e.stopPropagation()}>
          <div className="lead-tutorial-badge">LIVE · just booked</div>
          <h2 className="lead-tutorial-title">Your appointment is live</h2>
          <p className="lead-tutorial-body">
            The agent just booked a real <strong>{state.noun}</strong> in our
            backend. The <strong>{state.label}</strong> tab is fetching it
            live — want to see it on the calendar?
          </p>
          {preview.length > 0 && (
            <div className="lead-tutorial-preview">
              {preview.map((p, i) => (
                <div key={i} className="lead-tutorial-preview-row">
                  <span className="lead-tutorial-preview-label">{p.label}</span>
                  <span className="lead-tutorial-preview-value">{p.value}</span>
                </div>
              ))}
            </div>
          )}
          <div className="lead-tutorial-actions">
            <button className="btn ghost" onClick={close}>Not now</button>
            <button className="btn primary" onClick={goThere}>Show me where I appear →</button>
          </div>
        </div>
      </div>
    );
  };

  window.LeadTutorialPopup = LeadTutorialPopup;
})();
