// ============================================================
// Lead-appears tutorial popup (Real Estate)
// Polls re_leads after the first chat send and waits for the AI
// to enrich the row (name, intent, areas, budget, type…) before
// firing the popup, with a preview of what was captured.
// ============================================================

(function () {
  const CONFIG = {
    table:         're_leads',
    phoneCol:      'phone',
    placeholderName: 'New Lead',
    select:        'id,name,contact_phone,intent,budget_min,budget_max,preferred_type,preferred_bedrooms,preferred_areas,status',
    targetSection: 'leads',
    targetLabel:   'Leads',
    recordNoun:    'lead',
    pollMs:        120000,
    intervalMs:    2500,
    initialDelayMs: 4000
  };

  function isEnriched(row) {
    if (!row) return false;
    if (row.name && row.name !== CONFIG.placeholderName) return true;
    if (row.intent) return true;
    if (row.budget_max || row.budget_min) return true;
    if (row.preferred_type) return true;
    if (row.preferred_bedrooms) return true;
    if (Array.isArray(row.preferred_areas) && row.preferred_areas.length) return true;
    if (row.status && row.status !== 'new') return true;
    return false;
  }

  function fmtMoney(n) {
    if (!n) return '';
    n = Number(n);
    if (n >= 1000000) return (n / 1000000).toFixed(1).replace(/\.0$/, '') + 'M';
    if (n >= 1000)    return Math.round(n / 1000) + 'K';
    return String(n);
  }

  function buildPreview(row) {
    const out = [];
    if (row.name && row.name !== CONFIG.placeholderName) out.push({ label: 'Name', value: row.name });
    if (row.intent) out.push({ label: 'Intent', value: row.intent });
    const areas = (row.preferred_areas || []).join(', ');
    if (areas) out.push({ label: 'Areas', value: areas });
    const typeParts = [];
    if (row.preferred_bedrooms) typeParts.push(row.preferred_bedrooms + '-bed');
    if (row.preferred_type) typeParts.push(row.preferred_type);
    if (typeParts.length) out.push({ label: 'Property', value: typeParts.join(' ') });
    const lo = row.budget_min, hi = row.budget_max;
    if (lo || hi) {
      let budget = '';
      if (lo && hi) budget = 'QAR ' + fmtMoney(lo) + ' – ' + fmtMoney(hi);
      else if (hi)  budget = 'up to QAR ' + fmtMoney(hi);
      else if (lo)  budget = 'from QAR ' + fmtMoney(lo);
      out.push({ label: 'Budget', value: budget });
    }
    if (row.status && row.status !== 'new') out.push({ label: 'Stage', 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,
              'limit':           '1'
            });
            const row = rows && rows[0];
            if (isEnriched(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 now</div>
          <h2 className="lead-tutorial-title">You just landed in the database</h2>
          <p className="lead-tutorial-body">
            The agent extracted these details from your conversation and saved
            them as a real <strong>{state.noun}</strong> in our backend. The{' '}
            <strong>{state.label}</strong> tab is fetching it live — want to
            see yourself there?
          </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;
})();
