
<script>



const WEBHOOK_URL       = 'https://n8n.dataman.in/webhook/panna';
const HEARTBEAT_URL     = 'https://n8n.dataman.in/webhook/panna-heartbeat';
const PROACTIVE_URL     = 'https://n8n.dataman.in/webhook/panna-proactive';
const UPLOAD_RECORD_URL = 'https://n8n.dataman.in/webhook/panna-upload-record';
const SECRET_TOKEN   = 'panna-secret-2026';
const LOGO_URL       = 'https://pannameditour.com/wp-content/uploads/2026/04/logo.png';

(function () {
  'use strict';

  // ── Country codes (expanded for international patients) ────────────────────
  const COUNTRY_CODES = [
    { name: 'India',            iso: 'IN', dial: '91',  digits: 10 },
    { name: 'Bangladesh',       iso: 'BD', dial: '880', digits: 10 },
    { name: 'Nepal',            iso: 'NP', dial: '977', digits: 10 },
    { name: 'Pakistan',         iso: 'PK', dial: '92',  digits: 10 },
    { name: 'Sri Lanka',        iso: 'LK', dial: '94',  digits: 9  },
    { name: 'UAE',              iso: 'AE', dial: '971', digits: 9  },
    { name: 'Saudi Arabia',     iso: 'SA', dial: '966', digits: 9  },
    { name: 'Kuwait',           iso: 'KW', dial: '965', digits: 8  },
    { name: 'Qatar',            iso: 'QA', dial: '974', digits: 8  },
    { name: 'Oman',             iso: 'OM', dial: '968', digits: 8  },
    { name: 'Bahrain',          iso: 'BH', dial: '973', digits: 8  },
    { name: 'Iraq',             iso: 'IQ', dial: '964', digits: 10 },
    { name: 'Nigeria',          iso: 'NG', dial: '234', digits: 10 },
    { name: 'Kenya',            iso: 'KE', dial: '254', digits: 9  },
    { name: 'Tanzania',         iso: 'TZ', dial: '255', digits: 9  },
    { name: 'Uganda',           iso: 'UG', dial: '256', digits: 9  },
    { name: 'Ethiopia',         iso: 'ET', dial: '251', digits: 9  },
    { name: 'Ghana',            iso: 'GH', dial: '233', digits: 9  },
    { name: 'Zambia',           iso: 'ZM', dial: '260', digits: 9  },
    { name: 'Zimbabwe',         iso: 'ZW', dial: '263', digits: 9  },
    { name: 'South Africa',     iso: 'ZA', dial: '27',  digits: 9  },
    { name: 'Senegal',          iso: 'SN', dial: '221', digits: 9  },
    { name: 'Cameroon',         iso: 'CM', dial: '237', digits: 9  },
    { name: 'Kazakhstan',       iso: 'KZ', dial: '7',   digits: 10 },
    { name: 'Uzbekistan',       iso: 'UZ', dial: '998', digits: 9  },
    { name: 'Afghanistan',      iso: 'AF', dial: '93',  digits: 9  },
    { name: 'Myanmar',          iso: 'MM', dial: '95',  digits: 9  },
    { name: 'Malaysia',         iso: 'MY', dial: '60',  digits: 9  },
    { name: 'Indonesia',        iso: 'ID', dial: '62',  digits: 10 },
    { name: 'USA / Canada',     iso: 'US', dial: '1',   digits: 10 },
    { name: 'United Kingdom',   iso: 'GB', dial: '44',  digits: 10 },
    { name: 'Australia',        iso: 'AU', dial: '61',  digits: 9  },
    { name: 'Other',            iso: 'XX', dial: '',    digits: 0  },
  ];

  // ── Device & timer ─────────────────────────────────────────────────────────
  const isMobile     = /Mobi|Android/i.test(navigator.userAgent);
  const pageLoadTime = Date.now();
  function getTimeOnPage() { return Math.floor((Date.now() - pageLoadTime) / 1000); }

  // ── UUID ───────────────────────────────────────────────────────────────────
  function generateUUID() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
      const r = (Math.random() * 16) | 0;
      return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);
    });
  }
  function getOrCreateUUID() {
    let id = localStorage.getItem('pmt_uuid');
    if (!id) { id = generateUUID(); localStorage.setItem('pmt_uuid', id); }
    return id;
  }

  // ── Geo ────────────────────────────────────────────────────────────────────
  async function fetchGeo() {
    const cached = localStorage.getItem('pmt_geo');
    if (cached) { try { return JSON.parse(cached); } catch (e) {} }
    try {
      const ctrl = new AbortController();
      const tid  = setTimeout(() => ctrl.abort(), 3000);
      const res  = await fetch('https://ipapi.co/json/', { signal: ctrl.signal });
      clearTimeout(tid);
      const data = await res.json();
      if (data && !data.error) {
        const geo = {
          city:         data.city         || '',
          country:      data.country_name || '',
          country_code: data.country_code || '',
          region:       data.region       || '',
          lat:          data.latitude     || null,
          lng:          data.longitude    || null
        };
        localStorage.setItem('pmt_geo', JSON.stringify(geo));
        return geo;
      }
    } catch (e) {}
    return { city: '', country: '', country_code: '', region: '' };
  }

  // ── localStorage helpers ───────────────────────────────────────────────────
  function getMessageCount()      { return parseInt(sessionStorage.getItem('pmt_msgcount') || '0', 10); }
  function setMessageCount(n)     { sessionStorage.setItem('pmt_msgcount', String(n)); }
  function getHistory()           { try { return JSON.parse(sessionStorage.getItem('pmt_history') || '[]'); } catch (e) { return []; } }
  function saveHistory(h)         { sessionStorage.setItem('pmt_history', JSON.stringify(h.slice(-10))); }
  function getVisitCount()        { const c = parseInt(localStorage.getItem('pmt_visit_count') || '0', 10) + 1; localStorage.setItem('pmt_visit_count', String(c)); return c; }
  function getHasChatted()        { return localStorage.getItem('pmt_has_chatted') === 'true'; }
  function setHasChatted()        { localStorage.setItem('pmt_has_chatted', 'true'); }
  function getChatCount()         { return parseInt(localStorage.getItem('pmt_chat_count') || '0', 10); }
  function incChatCount()         { localStorage.setItem('pmt_chat_count', String(getChatCount() + 1)); }
  function getHasSharedContact()  { return localStorage.getItem('pmt_has_shared_contact') === 'true'; }
  function setHasSharedContact()  { localStorage.setItem('pmt_has_shared_contact', 'true'); }
  function getLastN8nSync()       { return parseInt(localStorage.getItem('pmt_last_sync') || '0', 10); }
  function setLastN8nSync()       { localStorage.setItem('pmt_last_sync', String(Date.now())); }

  // ── Extracted info accumulator ─────────────────────────────────────────────
  function getExtractedInfo() {
    try { return JSON.parse(localStorage.getItem('pmt_extracted_info') || 'null') || {}; } catch (e) { return {}; }
  }
  function mergeExtractedInfo(incoming) {
    if (!incoming || typeof incoming !== 'object') return;
    const current = getExtractedInfo();
    Object.keys(incoming).forEach(function (k) {
      if (incoming[k] !== null && incoming[k] !== undefined && incoming[k] !== '') {
        current[k] = incoming[k];
      }
    });
    localStorage.setItem('pmt_extracted_info', JSON.stringify(current));
  }

  // ── Language helpers (international mapping) ───────────────────────────────
  function getRegionalLanguages(iso) {
    if (['AE','SA','KW','QA','BH','OM','IQ','JO','LB','YE','SY'].includes(iso)) return ['Arabic'];
    if (iso === 'BD') return ['Bengali'];
    if (iso === 'AF') return ['Pashto', 'Dari'];
    if (iso === 'NP') return ['Nepali', 'Hindi'];
    if (iso === 'PK') return ['Urdu'];
    if (iso === 'LK') return ['Tamil', 'Sinhala'];
    if (iso === 'IN') return ['Hindi'];
    if (['SN','ML','CI','GN','CM','MG','BJ','TG','BF','CD'].includes(iso)) return ['French'];
    if (['KE','TZ','UG','RW','BI'].includes(iso)) return ['Swahili'];
    if (['KZ','UZ','TJ','TM','KG','RU','BY'].includes(iso)) return ['Russian'];
    if (['MM','TH','VN'].includes(iso)) return [];
    return [];
  }

  // ── Country code helpers ───────────────────────────────────────────────────
  function countryNameToISO(name) {
    if (!name) return null;
    const n = name.trim().toLowerCase();
    const map = {
      'afghanistan':'AF','afganistan':'AF','bangladesh':'BD','nepal':'NP','india':'IN',
      'pakistan':'PK','sri lanka':'LK','myanmar':'MM','bhutan':'BT','maldives':'MV',
      'uae':'AE','united arab emirates':'AE','saudi arabia':'SA','kuwait':'KW',
      'bahrain':'BH','qatar':'QA','oman':'OM','iraq':'IQ','iran':'IR','jordan':'JO',
      'lebanon':'LB','syria':'SY','yemen':'YE','israel':'IL','turkey':'TR',
      'egypt':'EG','morocco':'MA','algeria':'DZ','tunisia':'TN','libya':'LY',
      'nigeria':'NG','ghana':'GH','kenya':'KE','tanzania':'TZ','ethiopia':'ET',
      'uganda':'UG','rwanda':'RW','sudan':'SD','somalia':'SO','zambia':'ZM',
      'zimbabwe':'ZW','south africa':'ZA','angola':'AO','cameroon':'CM',
      'uk':'GB','united kingdom':'GB','usa':'US','united states':'US',
      'canada':'CA','australia':'AU','new zealand':'NZ','singapore':'SG',
      'malaysia':'MY','indonesia':'ID','thailand':'TH','philippines':'PH',
      'vietnam':'VN','cambodia':'KH','china':'CN','japan':'JP','south korea':'KR',
      'russia':'RU','ukraine':'UA','germany':'DE','france':'FR','italy':'IT',
      'spain':'ES','netherlands':'NL','sweden':'SE','norway':'NO','denmark':'DK',
      'brazil':'BR','argentina':'AR','colombia':'CO','peru':'PE','mexico':'MX',
      'uzbekistan':'UZ','kazakhstan':'KZ','tajikistan':'TJ','kyrgyzstan':'KG',
      'turkmenistan':'TM','mongolia':'MN'
    };
    return map[n] || null;
  }

  function getDefaultCountry() {
    try {
      const g   = JSON.parse(localStorage.getItem('pmt_geo') || '{}');
      const iso = (g.country_code || '').toUpperCase();
      return COUNTRY_CODES.find(c => c.iso === iso) || COUNTRY_CODES[0];
    } catch (e) { return COUNTRY_CODES[0]; }
  }

  // ── State ──────────────────────────────────────────────────────────────────
  const visitorId          = getOrCreateUUID();
  const visitCount         = getVisitCount();
  const isReturning        = visitCount > 1;
  if (isReturning) localStorage.setItem('pmt_is_returning', 'true');
  let geo                  = { city: '', country: '', country_code: '', region: '' };
  let selectedLanguage     = localStorage.getItem('pmt_lang') || '';
  let msgCount             = getMessageCount();
  let widgetOpened         = false;
  let fallbackMode         = false;
  let conversationStarted  = false;
  let contactCardShown     = false;
  let reEngagementShown    = false;
  let idleTimer            = null;
  let awaitingLanguageInput = false;
  let sessionEndSent       = false;
  let closeCardShown       = false;
  let heartbeatTimer       = null;
  const IDLE_MS            = 2 * 60 * 1000;

  function retryPendingContact() {
    const pending = localStorage.getItem('pmt_pending_contact');
    if (!pending) return;
    try {
      const data = JSON.parse(pending);
      fetch(WEBHOOK_URL, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'x-secret-token': SECRET_TOKEN },
        body: JSON.stringify(data)
      }).then(function (res) {
        if (res.ok) localStorage.removeItem('pmt_pending_contact');
      }).catch(function () {});
    } catch (e) {}
  }
  window.addEventListener('online', retryPendingContact);

  function checkAndSyncStats() {
    const THREE_HOURS = 3 * 60 * 60 * 1000;
    if (Date.now() - getLastN8nSync() < THREE_HOURS) return;
    fetch(WEBHOOK_URL, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', 'x-secret-token': SECRET_TOKEN },
      body: JSON.stringify({
        visitor_id:      visitorId,
        site_id:         'PANNA',
        message_type:    'stats_sync',
        language:        selectedLanguage || 'English',
        visitor_context: buildVisitorContext()
      })
    }).then(function () { setLastN8nSync(); }).catch(function () {});
  }

  // ── Heartbeat ──────────────────────────────────────────────────────────────
  function sendHeartbeat() {
    const g = (function () { try { return JSON.parse(localStorage.getItem('pmt_geo') || '{}'); } catch (e) { return {}; } })();
    fetch(HEARTBEAT_URL, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      keepalive: true,
      body: JSON.stringify({
        visitor_id:   visitorId,
        current_page: location.href,
        chat_open:    widgetOpened,
        country_code: g.country_code || '',
        lat:          g.lat  || null,
        lng:          g.lng  || null
      })
    }).catch(function () {});
  }
  function startHeartbeat() { sendHeartbeat(); heartbeatTimer = setInterval(sendHeartbeat, 10000); }

  // ── Proactive invite polling ───────────────────────────────────────────────
  function startProactivePoll() {
    setInterval(function () {
      if (widgetOpened) return;
      fetch(PROACTIVE_URL + '?visitor_id=' + encodeURIComponent(visitorId))
        .then(function (r) { return r.ok ? r.json() : null; })
        .then(function (d) {
          if (!d || !d.message) return;
          openWidget();
          setTimeout(function () { addBubble(d.message, 'bot'); }, 400);
        })
        .catch(function () {});
    }, 5000);
  }

  fetchGeo().then(g => { geo = g; checkAndSyncStats(); retryPendingContact(); startHeartbeat(); startProactivePoll(); });

  // ── Styles ─────────────────────────────────────────────────────────────────
  const PRIMARY   = '#16a34a';
  const PRIMARY_D = '#15803d';
  const styles = `
    #pmt-chat-launcher {
      position: fixed !important; bottom: 24px !important; right: 24px !important;
      width: 56px !important; height: 56px !important; min-width: 56px !important; min-height: 56px !important;
      background: ${PRIMARY} !important; border-radius: 50% !important;
      box-shadow: 0 4px 16px rgba(22,163,74,0.45) !important;
      cursor: pointer !important; display: flex !important; align-items: center !important; justify-content: center !important;
      z-index: 2147483640 !important; transition: transform 0.2s ease, box-shadow 0.2s ease;
      border: none !important; outline: none !important; padding: 0 !important;
      overflow: visible !important; box-sizing: border-box !important;
    }
    #pmt-chat-launcher:hover { transform: scale(1.08); box-shadow: 0 6px 24px rgba(22,163,74,0.55); }
    #pmt-chat-launcher svg { width: 28px; height: 28px; fill: #ffffff; }
    #pmt-chat-launcher .pmt-launcher-logo {
      width: 36px !important; height: 36px !important; max-width: 36px !important; max-height: 36px !important;
      border-radius: 50% !important; object-fit: cover !important; flex-shrink: 0 !important;
      border: 2px solid rgba(255,255,255,0.8) !important; display: block !important;
    }
    #pmt-chat-launcher .pmt-launcher-initial {
      width: 36px; height: 36px; border-radius: 50%;
      background: rgba(255,255,255,0.25); border: 2px solid rgba(255,255,255,0.8);
      display: flex; align-items: center; justify-content: center;
      font-size: 18px; font-weight: 700; color: #fff; font-family: Arial, sans-serif;
    }
    #pmt-chat-launcher .pmt-notif-dot {
      position: absolute; top: -2px; right: -2px;
      min-width: 18px; height: 18px; background: #ef4444;
      border-radius: 9px; border: 2px solid #ffffff;
      display: flex; align-items: center; justify-content: center;
      font-size: 11px; font-weight: 700; color: #fff; font-family: Arial, sans-serif; padding: 0 3px;
    }
    #pmt-chat-widget {
      position: fixed !important; bottom: 10px !important; right: 24px !important;
      width: 360px !important; height: 460px; max-height: calc(100dvh - 170px);
      background: #ffffff; border-radius: 16px;
      box-shadow: 0 8px 40px rgba(0,0,0,0.18);
      display: flex; flex-direction: column;
      z-index: 2147483639; overflow: hidden;
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
      font-size: 14px;
      transition: opacity 0.25s ease, transform 0.25s ease;
      transform-origin: bottom right;
    }
    #pmt-chat-widget.pmt-hidden  { opacity: 0; pointer-events: none; transform: scale(0.92) translateY(12px); }
    #pmt-chat-widget.pmt-visible { opacity: 1; pointer-events: all;  transform: scale(1)    translateY(0);    }
    .pmt-header {
      background: linear-gradient(135deg, ${PRIMARY} 0%, ${PRIMARY_D} 100%);
      padding: 8px 16px; display: flex; align-items: center;
      justify-content: space-between; flex-shrink: 0;
    }
    .pmt-header-right { display: flex; align-items: center; gap: 8px; }
    .pmt-name   { font-weight: 700; font-size: 14px; line-height: 1.2; color: #ffffff; }
    .pmt-status { font-size: 11px; opacity: 0.85; display: flex; align-items: center; gap: 4px; color: #ffffff; }
    .pmt-status-dot { width: 7px; height: 7px; background: #4ade80; border-radius: 50%; display: inline-block; }
    .pmt-close-btn {
      background: none; border: none; cursor: pointer;
      color: rgba(255,255,255,0.8); padding: 4px; border-radius: 4px;
      display: flex; align-items: center; justify-content: center;
      transition: color 0.15s; outline: none;
    }
    .pmt-close-btn:hover { color: #ffffff; }
    .pmt-close-btn svg { width: 18px; height: 18px; stroke: currentColor; fill: none; }
    .pmt-messages {
      flex: 1; overflow-y: auto; padding: 16px 14px;
      display: flex; flex-direction: column; gap: 10px;
      scroll-behavior: smooth; position: relative;
    }
    .pmt-messages::-webkit-scrollbar { width: 4px; }
    .pmt-messages::-webkit-scrollbar-track { background: transparent; }
    .pmt-messages::-webkit-scrollbar-thumb { background: #e2e8f0; border-radius: 2px; }
    .pmt-bubble {
      max-width: 82%; padding: 10px 13px; border-radius: 14px;
      line-height: 1.5; word-break: break-word; font-size: 13.5px;
    }
    .pmt-bubble.pmt-bot    { background: #f0fdf4; color: #1e293b; align-self: flex-start; border-bottom-left-radius: 4px; }
    .pmt-bubble.pmt-user   { background: ${PRIMARY}; color: #ffffff; align-self: flex-end; border-bottom-right-radius: 4px; }
    .pmt-bubble.pmt-system { background: #fef3c7; color: #92400e; align-self: center; font-size: 12px; text-align: center; border-radius: 8px; max-width: 90%; }
    .pmt-typing-indicator {
      display: flex; align-items: center; gap: 4px;
      padding: 10px 13px; background: #f0fdf4;
      border-radius: 14px; border-bottom-left-radius: 4px;
      align-self: flex-start; width: fit-content;
    }
    .pmt-typing-indicator span {
      width: 7px; height: 7px; background: #86efac;
      border-radius: 50%; display: inline-block;
      animation: pmt-bounce 1.2s infinite;
    }
    .pmt-typing-indicator span:nth-child(2) { animation-delay: 0.2s; }
    .pmt-typing-indicator span:nth-child(3) { animation-delay: 0.4s; }
    @keyframes pmt-bounce {
      0%, 60%, 100% { transform: translateY(0);    }
      30%            { transform: translateY(-5px); }
    }
    .pmt-lang-selector { display: flex; flex-wrap: wrap; gap: 7px; padding: 4px 0 2px; }
    .pmt-lang-btn {
      padding: 6px 12px; border: 1.5px solid ${PRIMARY};
      background: #ffffff; color: ${PRIMARY}; border-radius: 20px;
      cursor: pointer; font-size: 12.5px; font-weight: 500;
      transition: background 0.15s, color 0.15s; outline: none; font-family: inherit;
    }
    .pmt-lang-btn:hover { background: ${PRIMARY}; color: #ffffff; }
    .pmt-footer {
      padding: 10px 12px 12px; border-top: 1px solid #f0fdf4;
      background: #ffffff; flex-shrink: 0;
    }
    .pmt-input-row { display: flex; gap: 8px; align-items: flex-end; }
    .pmt-input {
      flex: 1; padding: 9px 12px; border: 1.5px solid #e2e8f0;
      border-radius: 22px; outline: none; font-size: 13.5px;
      font-family: inherit; resize: none; line-height: 1.4;
      max-height: 80px; overflow-y: auto;
      transition: border-color 0.15s; color: #1e293b;
    }
    .pmt-input:focus    { border-color: ${PRIMARY}; }
    .pmt-input:disabled { background: #f8fafc; color: #94a3b8; cursor: not-allowed; }
    .pmt-send-btn {
      width: 38px !important; height: 38px !important; min-width: 38px !important; min-height: 38px !important;
      background: ${PRIMARY} !important;
      border: none !important; border-radius: 50% !important; cursor: pointer !important;
      display: flex !important; align-items: center !important; justify-content: center !important;
      flex-shrink: 0 !important; transition: background 0.15s, transform 0.1s; outline: none !important;
      padding: 0 !important; box-sizing: border-box !important;
    }
    .pmt-send-btn:hover    { background: ${PRIMARY_D}; }
    .pmt-send-btn:active   { transform: scale(0.92); }
    .pmt-send-btn:disabled { background: #cbd5e1; cursor: not-allowed; }
    .pmt-send-btn svg { width: 17px; height: 17px; fill: #ffffff; }
    .pmt-powered { text-align: center; font-size: 10.5px; color: #64748b; margin-top: 6px; }
    .pmt-contact-card {
      background: #ffffff; border: 1.5px solid #e2e8f0;
      border-radius: 14px; padding: 10px; width: 100%;
      box-sizing: border-box; align-self: stretch;
      display: flex; flex-direction: column; gap: 7px;
    }
    .pmt-contact-heading { font-size: 13px; font-weight: 600; color: #1e293b; line-height: 1.3; }
    .pmt-contact-subtext { font-size: 11.5px; color: #64748b; line-height: 1.4; margin-top: -3px; }
    .pmt-field-group { display: flex; flex-direction: column; gap: 3px; }
    .pmt-field-label { font-size: 11.5px; font-weight: 600; color: #1e293b; }
    .pmt-field-label.pmt-req::after { content: ' *'; color: #ef4444; }
    .pmt-field-input {
      padding: 5px 10px; border: 1.5px solid #e2e8f0;
      border-radius: 8px; font-size: 13px; font-family: inherit;
      outline: none; color: #1e293b; transition: border-color 0.15s; background: #fff;
    }
    .pmt-field-input:focus    { border-color: ${PRIMARY}; }
    .pmt-field-input.pmt-err  { border-color: #ef4444; }
    .pmt-phone-row {
      display: flex; align-items: center;
      border: 1.5px solid #e2e8f0; border-radius: 8px;
      overflow: hidden; background: #fff; transition: border-color 0.15s;
    }
    .pmt-phone-row:focus-within { border-color: ${PRIMARY}; }
    .pmt-phone-row.pmt-err      { border-color: #ef4444; }
    .pmt-country-select {
      border: none; outline: none; background: #f8fafc;
      font-size: 12px; font-family: inherit;
      padding: 8px 4px 8px 8px; color: #1e293b; cursor: pointer;
      max-width: 110px; border-right: 1px solid #e2e8f0; flex-shrink: 0;
    }
    .pmt-dial-code {
      padding: 8px 6px; font-size: 12.5px; color: #475569;
      font-weight: 600; flex-shrink: 0;
      border-right: 1px solid #e2e8f0; background: #f8fafc;
      min-width: 42px; text-align: center;
    }
    .pmt-phone-input {
      flex: 1; border: none; outline: none;
      font-size: 13px; font-family: inherit;
      padding: 8px 10px; color: #1e293b; background: #fff; min-width: 0;
    }
    .pmt-field-error { font-size: 11.5px; color: #ef4444; min-height: 0; line-height: 1.3; }
    .pmt-btn-row { display: flex; gap: 8px; align-items: center; margin-top: 4px; }
    .pmt-contact-submit {
      flex: 2; padding: 7px 12px; background: ${PRIMARY};
      color: #fff; border: none; border-radius: 8px;
      font-size: 13px; font-weight: 600; cursor: pointer;
      font-family: inherit; transition: background 0.15s; outline: none;
    }
    .pmt-contact-submit:hover    { background: ${PRIMARY_D}; }
    .pmt-contact-submit:disabled { background: #94a3b8; cursor: not-allowed; }
    .pmt-contact-skip {
      flex: 1; background: none; border: 1.5px solid #e2e8f0; border-radius: 8px;
      color: #64748b; font-size: 12.5px; cursor: pointer; font-family: inherit;
      text-align: center; padding: 7px 8px; outline: none;
    }
    .pmt-contact-skip:hover { color: #1e293b; border-color: #94a3b8; }
    .pmt-reengage-overlay {
      position: absolute; inset: 0; background: rgba(255,255,255,0.97);
      z-index: 10; display: flex; align-items: center;
      justify-content: center; padding: 16px; box-sizing: border-box; overflow-y: auto;
    }
    .pmt-faq-chips { display: flex; flex-direction: column; gap: 6px; margin-top: 6px; }
    .pmt-faq-chip {
      padding: 7px 12px; border: 1.5px solid ${PRIMARY};
      background: #fff; color: ${PRIMARY}; border-radius: 20px;
      cursor: pointer; font-size: 12.5px; font-family: inherit;
      text-align: left; transition: background 0.15s, color 0.15s; outline: none; line-height: 1.4;
    }
    .pmt-faq-chip:hover { background: ${PRIMARY}; color: #fff; }
    .pmt-fallback-form { display: flex; flex-direction: column; gap: 8px; padding-top: 4px; }
    @media (max-width: 480px) {
      #pmt-chat-widget {
        width: 100vw; height: 100%; bottom: 0; right: 0;
        border-radius: 0; border-top-left-radius: 16px; border-top-right-radius: 16px;
        max-height: 100dvh;
      }
      #pmt-chat-launcher { bottom: 16px; right: 16px; }
    }
    #pmt-chat-launcher.pmt-launcher-hidden { display: none !important; }
    .grecaptcha-badge { display: none !important; }
  `;

  // ── DOM Construction ───────────────────────────────────────────────────────
  function buildWidget() {
    const styleEl = document.createElement('style');
    styleEl.textContent = styles;
    document.head.appendChild(styleEl);

    const launcher = document.createElement('button');
    launcher.id = 'pmt-chat-launcher';
    launcher.setAttribute('aria-label', 'Open chat');
    const logoInner = LOGO_URL
      ? `<img class="pmt-launcher-logo" src="${LOGO_URL}" alt="Panna" onerror="this.style.display='none';this.nextSibling.style.display='flex'"><span class="pmt-launcher-initial" style="display:none">P</span>`
      : `<span class="pmt-launcher-initial">P</span>`;
    launcher.innerHTML = `${logoInner}<span class="pmt-notif-dot" id="pmt-notif-dot">1</span>`;
    document.documentElement.appendChild(launcher);

    const widget = document.createElement('div');
    widget.id = 'pmt-chat-widget';
    widget.className = 'pmt-hidden';
    widget.setAttribute('role', 'dialog');
    widget.setAttribute('aria-label', 'Panna Medi Tour Chat');
    widget.innerHTML = `
      <div class="pmt-header">
        <div class="pmt-name">Dravya — Panna Medi Tour</div>
        <div class="pmt-header-right">
          <div class="pmt-status"><span class="pmt-status-dot"></span>Online</div>
          <button class="pmt-close-btn" id="pmt-close-btn" aria-label="Close chat">
            <svg viewBox="0 0 24 24" stroke-width="2.5" stroke-linecap="round">
              <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
            </svg>
          </button>
        </div>
      </div>
      <div class="pmt-messages" id="pmt-messages"></div>
      <div class="pmt-footer" id="pmt-footer">
        <div class="pmt-input-row">
          <textarea class="pmt-input" id="pmt-input" placeholder="Type a message..." rows="1" aria-label="Chat input"></textarea>
          <button class="pmt-send-btn" id="pmt-send-btn" aria-label="Send message">
            <svg viewBox="0 0 24 24"><path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/></svg>
          </button>
        </div>
        <div class="pmt-powered">Panna Medi Tour — Medical Travel Facilitator</div>
      </div>`;
    document.documentElement.appendChild(widget);
    return { launcher, widget };
  }

  const { launcher, widget } = buildWidget();
  const messagesEl = document.getElementById('pmt-messages');
  const inputEl    = document.getElementById('pmt-input');
  const sendBtn    = document.getElementById('pmt-send-btn');
  const closeBtn   = document.getElementById('pmt-close-btn');
  const notifDot   = document.getElementById('pmt-notif-dot');

  // ── Helpers ────────────────────────────────────────────────────────────────
  function scrollToBottom() { messagesEl.scrollTop = messagesEl.scrollHeight; }

  function addBubble(text, role) {
    const b = document.createElement('div');
    b.className = 'pmt-bubble pmt-' + role;
    b.textContent = text;
    messagesEl.appendChild(b);
    scrollToBottom();
    return b;
  }

  function showTyping()   { const e = document.createElement('div'); e.className = 'pmt-typing-indicator'; e.id = 'pmt-typing'; e.innerHTML = '<span></span><span></span><span></span>'; messagesEl.appendChild(e); scrollToBottom(); }
  function removeTyping() { const e = document.getElementById('pmt-typing'); if (e) e.remove(); }

  function setInputEnabled(on) {
    inputEl.disabled = !on;
    sendBtn.disabled = !on;
    if (on) inputEl.focus();
  }

  inputEl.addEventListener('input', function () {
    this.style.height = 'auto';
    this.style.height = Math.min(this.scrollHeight, 80) + 'px';
  });

  // ── Contact card ───────────────────────────────────────────────────────────
  function safeVal(s) { return (s || '').replace(/"/g, '&quot;').replace(/</g, '&lt;'); }

  function buildContactCardHTML(uid, type, prefill, isUpdate) {
    const isExit    = type === 'early_exit_contact';
    const isPrefill = prefill && (prefill.name || prefill.whatsapp || prefill.email);
    const heading   = isUpdate
      ? 'Update your contact details'
      : isPrefill
        ? 'We\'ve noted your details — please confirm below.'
        : isExit
          ? 'Before you go...'
          : 'Connect with our patient advisor.';
    const subtext   = isUpdate
      ? 'Review and update your details — our team will be notified.'
      : isPrefill
        ? 'Review and adjust if needed — our advisor will reach out to you on WhatsApp.'
        : isExit
          ? 'Leave your contact details and our advisor will reach out to you on WhatsApp.'
          : '';
    const submitText = isUpdate ? 'Update my details' : isExit ? 'Connect me' : 'Send my details';
    const skipText   = isUpdate ? 'Cancel' : 'Skip for now';
    let defC = getDefaultCountry();
    // Override with country mentioned in conversation if available
    const convCountry = (prefill && (prefill.country_of_origin || prefill.country)) || '';
    if (convCountry) {
      const iso = countryNameToISO(convCountry);
      const found = iso && COUNTRY_CODES.find(c => c.iso === iso);
      if (found) defC = found;
    }
    const options    = COUNTRY_CODES.map(c =>
      `<option value="${c.iso}" data-dial="${c.dial}" data-digits="${c.digits}"${c.iso === defC.iso ? ' selected' : ''}>+${c.dial} ${c.name}</option>`
    ).join('');

    const stored     = getExtractedInfo();
    const merged     = Object.assign({}, stored, prefill || {});
    const nameVal    = safeVal(merged.name);
    const emailVal   = safeVal(merged.email);
    const phoneVal   = safeVal(merged.whatsapp || merged.phone || '');
    const treatVal   = safeVal(merged.treatment_interest || '');

    return `
      <div class="pmt-contact-card" id="pmt-card-${uid}">
        <div class="pmt-contact-heading">${heading}</div>
        ${subtext ? `<div class="pmt-contact-subtext">${subtext}</div>` : ''}
        <div class="pmt-field-group">
          <label class="pmt-field-label pmt-req">Your Name</label>
          <input type="text" class="pmt-field-input" id="pmt-name-${uid}" placeholder="Your full name" autocomplete="name" value="${nameVal}"/>
          <div class="pmt-field-error" id="pmt-name-err-${uid}"></div>
        </div>
        <div class="pmt-field-group">
          <label class="pmt-field-label">WhatsApp Number</label>
          <div class="pmt-phone-row" id="pmt-phone-row-${uid}">
            <select class="pmt-country-select" id="pmt-country-${uid}">${options}</select>
            <span class="pmt-dial-code" id="pmt-dial-${uid}">+${defC.dial}</span>
            <input type="tel" class="pmt-phone-input" id="pmt-phone-${uid}"
              placeholder="${defC.digits > 0 ? defC.digits + ' digits' : 'Number'}"
              autocomplete="tel" maxlength="15" value="${phoneVal}"/>
          </div>
          <div class="pmt-field-error" id="pmt-phone-err-${uid}"></div>
        </div>
        <div class="pmt-field-group">
          <label class="pmt-field-label">Email</label>
          <input type="email" class="pmt-field-input" id="pmt-email-${uid}" placeholder="your@email.com" autocomplete="email" value="${emailVal}"/>
          <div class="pmt-field-error" id="pmt-email-err-${uid}"></div>
        </div>
        <div style="display:flex;gap:8px;">
          <div class="pmt-field-group" style="flex:1;">
            <label class="pmt-field-label pmt-req">Treatment</label>
            <input type="text" class="pmt-field-input" id="pmt-treatment-${uid}" placeholder="e.g. IVF, knee replacement..." value="${treatVal}"/>
            <div class="pmt-field-error" id="pmt-treatment-err-${uid}"></div>
          </div>
          <div class="pmt-field-group" style="flex:1;">
            <label class="pmt-field-label pmt-req">Country</label>
            <input type="text" class="pmt-field-input" id="pmt-origin-${uid}" placeholder="e.g. Bangladesh, UAE..." value="${safeVal(merged.country_of_origin || merged.country || geo.country || '')}"/>
            <div class="pmt-field-error" id="pmt-origin-err-${uid}"></div>
          </div>
        </div>
        <div class="pmt-field-group">
          <label class="pmt-field-label">Medical Records <span style="font-size:11px;color:#9ca3af;">(optional — PDF, DOC, JPG, PNG)</span></label>
          <input type="file" id="pmt-file-${uid}" accept=".pdf,.doc,.docx,.jpg,.jpeg,.png" multiple style="display:none;"/>
          <div style="display:flex;gap:6px;align-items:center;flex-wrap:wrap;">
            <button type="button" id="pmt-pick-${uid}" onclick="document.getElementById('pmt-file-${uid}').click()" style="padding:6px 12px;border:1.5px dashed #16a34a;border-radius:8px;background:#f0fdf4;color:#16a34a;font-size:12px;font-weight:600;cursor:pointer;font-family:inherit;">+ Choose files</button>
            <button type="button" id="pmt-upload-btn-${uid}" style="padding:6px 14px;background:#16a34a;color:#fff;border:none;border-radius:8px;font-size:12px;font-weight:600;cursor:pointer;font-family:inherit;display:none;">Upload</button>
            <span id="pmt-file-label-${uid}" style="font-size:11px;color:#6b7280;">No file chosen</span>
          </div>
          <div class="pmt-field-error" id="pmt-file-err-${uid}"></div>
          <div id="pmt-upload-status-${uid}" style="font-size:11.5px;margin-top:3px;"></div>
        </div>
        <div class="pmt-field-error" id="pmt-contact-err-${uid}"></div>
        <div class="pmt-btn-row">
          <button class="pmt-contact-submit" id="pmt-submit-${uid}">${submitText}</button>
          <button class="pmt-contact-skip"   id="pmt-skip-${uid}">${skipText}</button>
        </div>
      </div>`;
  }

  function setupContactCardListeners(uid, type, onSkip) {
    // ── File picker wiring ────────────────────────────────────────────────────
    const fileInputEl   = document.getElementById('pmt-file-'          + uid);
    const fileLabelEl   = document.getElementById('pmt-file-label-'    + uid);
    const uploadBtnEl   = document.getElementById('pmt-upload-btn-'    + uid);
    const uploadStatusEl= document.getElementById('pmt-upload-status-' + uid);
    if (fileInputEl) {
      fileInputEl.addEventListener('change', function () {
        const count = this.files.length;
        if (fileLabelEl) fileLabelEl.textContent = count > 0 ? count + ' file' + (count > 1 ? 's' : '') + ' chosen' : 'No file chosen';
        if (uploadBtnEl) uploadBtnEl.style.display = count > 0 ? 'inline-block' : 'none';
        if (uploadStatusEl) uploadStatusEl.textContent = '';
      });
    }
    if (uploadBtnEl) {
      uploadBtnEl.addEventListener('click', function () {
        const nameEl  = document.getElementById('pmt-name-'  + uid);
        const phoneEl = document.getElementById('pmt-phone-' + uid);
        const fileErrEl = document.getElementById('pmt-file-err-' + uid);
        if (!nameEl || !nameEl.value.trim()) {
          if (fileErrEl) fileErrEl.textContent = 'Please fill in your name before uploading.';
          return;
        }
        if (!phoneEl || !phoneEl.value.trim()) {
          if (fileErrEl) fileErrEl.textContent = 'Please fill in your phone number before uploading.';
          return;
        }
        if (fileErrEl) fileErrEl.textContent = '';
        const files = fileInputEl ? Array.from(fileInputEl.files) : [];
        if (!files.length) return;
        uploadBtnEl.disabled    = true;
        uploadBtnEl.textContent = 'Uploading…';
        if (uploadStatusEl) uploadStatusEl.style.color = '#6b7280';
        if (uploadStatusEl) uploadStatusEl.textContent = 'Uploading ' + files.length + ' file' + (files.length > 1 ? 's' : '') + '…';
        let done = 0, failed = 0;
        files.forEach(function (file) {
          const reader = new FileReader();
          reader.onload = async function (e) {
            const base64 = e.target.result.split(',')[1];
            try {
              const res = await fetch(UPLOAD_RECORD_URL, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'x-secret-token': SECRET_TOKEN },
                body: JSON.stringify({ visitor_id: visitorId, file_name: file.name, file_size: file.size, file_type: file.type || 'application/pdf', file_data: base64 })
              });
              if (res.ok) { done++; } else { failed++; }
            } catch (err) { failed++; }
            if (done + failed === files.length) {
              uploadBtnEl.disabled    = false;
              uploadBtnEl.textContent = '+ Upload more';
              if (uploadStatusEl) {
                uploadStatusEl.style.color = failed > 0 ? '#dc2626' : '#16a34a';
                uploadStatusEl.textContent = failed > 0
                  ? (done + ' uploaded, ' + failed + ' failed. Try again.')
                  : '✓ ' + done + ' file' + (done > 1 ? 's' : '') + ' uploaded successfully.';
              }
              if (fileInputEl) fileInputEl.value = '';
              if (fileLabelEl) fileLabelEl.textContent = 'No file chosen';
            }
          };
          reader.readAsDataURL(file);
        });
      });
    }

    const countryEl = document.getElementById('pmt-country-' + uid);
    const dialEl    = document.getElementById('pmt-dial-'    + uid);
    const phoneEl   = document.getElementById('pmt-phone-'   + uid);
    if (countryEl) {
      countryEl.addEventListener('change', function () {
        const opt    = this.options[this.selectedIndex];
        const dial   = opt.getAttribute('data-dial');
        const digits = parseInt(opt.getAttribute('data-digits')) || 0;
        if (dialEl)  dialEl.textContent = '+' + dial;
        if (phoneEl) phoneEl.placeholder = digits > 0 ? digits + ' digits' : 'Number';
        if (phoneEl) phoneEl.maxLength   = digits > 0 ? digits : 15;
      });
    }
    const submitEl = document.getElementById('pmt-submit-' + uid);
    const skipEl   = document.getElementById('pmt-skip-'   + uid);
    if (submitEl) {
      submitEl.addEventListener('click', function () {
        if (!validateAndSubmitCard(uid, type)) return;
        submitEl.disabled    = true;
        submitEl.textContent = 'Sending...';
      });
    }
    if (skipEl) {
      skipEl.addEventListener('click', function () { if (onSkip) onSkip(); });
    }
  }

  function validateAndSubmitCard(uid, type) {
    let valid = true;
    const nameEl        = document.getElementById('pmt-name-'         + uid);
    const emailEl       = document.getElementById('pmt-email-'        + uid);
    const phoneEl       = document.getElementById('pmt-phone-'        + uid);
    const countryEl     = document.getElementById('pmt-country-'      + uid);
    const treatmentEl   = document.getElementById('pmt-treatment-'    + uid);
    const originEl      = document.getElementById('pmt-origin-'       + uid);
    const nameErrEl     = document.getElementById('pmt-name-err-'     + uid);
    const phoneErrEl    = document.getElementById('pmt-phone-err-'    + uid);
    const emailErrEl    = document.getElementById('pmt-email-err-'    + uid);
    const treatErrEl    = document.getElementById('pmt-treatment-err-'+ uid);
    const originErrEl   = document.getElementById('pmt-origin-err-'   + uid);
    const contactErrEl  = document.getElementById('pmt-contact-err-'  + uid);
    const phoneRowEl    = document.getElementById('pmt-phone-row-'    + uid);

    [nameErrEl, phoneErrEl, emailErrEl, treatErrEl, originErrEl, contactErrEl].forEach(e => { if (e) e.textContent = ''; });
    if (nameEl)      nameEl.classList.remove('pmt-err');
    if (phoneRowEl)  phoneRowEl.classList.remove('pmt-err');
    if (emailEl)     emailEl.classList.remove('pmt-err');
    if (treatmentEl) treatmentEl.classList.remove('pmt-err');
    if (originEl)    originEl.classList.remove('pmt-err');

    const name      = nameEl      ? nameEl.value.trim()      : '';
    const email     = emailEl     ? emailEl.value.trim()     : '';
    const phone     = phoneEl     ? phoneEl.value.trim()     : '';
    const treatment = treatmentEl ? treatmentEl.value.trim() : '';
    const origin    = originEl    ? originEl.value.trim()    : '';
    const opt       = countryEl   ? countryEl.options[countryEl.selectedIndex] : null;
    const dial      = opt ? opt.getAttribute('data-dial')            : '';
    const digits    = opt ? parseInt(opt.getAttribute('data-digits')) || 0 : 0;

    if (!name) {
      if (nameEl)    nameEl.classList.add('pmt-err');
      if (nameErrEl) nameErrEl.textContent = 'Please enter your name.';
      valid = false;
    }
    if (!phone && !email) {
      if (phoneRowEl)  phoneRowEl.classList.add('pmt-err');
      if (phoneErrEl)  phoneErrEl.textContent = 'Please provide WhatsApp number or email — at least one is required.';
      valid = false;
    } else {
      if (phone) {
        const digitsOnly = phone.replace(/\D/g, '');
        if (digits > 0 && digitsOnly.length !== digits) {
          if (phoneRowEl)  phoneRowEl.classList.add('pmt-err');
          if (phoneErrEl)  phoneErrEl.textContent = 'Enter exactly ' + digits + ' digits for this country.';
          valid = false;
        }
      }
      if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
        if (emailEl)    emailEl.classList.add('pmt-err');
        if (emailErrEl) emailErrEl.textContent = 'Please enter a valid email address.';
        valid = false;
      }
    }
    if (!treatment) {
      if (treatmentEl) treatmentEl.classList.add('pmt-err');
      if (treatErrEl)  treatErrEl.textContent = 'Please tell us what treatment you are seeking.';
      valid = false;
    }
    if (!origin) {
      if (originEl)   originEl.classList.add('pmt-err');
      if (originErrEl) originErrEl.textContent = 'Please enter your country.';
      valid = false;
    }
    const fileEl    = document.getElementById('pmt-file-' + uid);
    const fileErrEl = document.getElementById('pmt-file-err-' + uid);
    const files     = fileEl ? Array.from(fileEl.files) : [];
    if (files.length > 3) {
      if (fileErrEl) fileErrEl.textContent = 'You can upload up to 3 files.';
      valid = false;
    } else {
      for (var fi = 0; fi < files.length; fi++) {
        if (files[fi].size > 3 * 1024 * 1024) {
          if (fileErrEl) fileErrEl.textContent = 'Each file must be smaller than 3 MB.';
          valid = false;
          break;
        }
      }
    }
    if (!valid) return false;

    const whatsapp = phone ? '+' + dial + phone.replace(/\D/g, '') : '';
    submitContactData(uid, type, name, email, whatsapp, treatment, origin);
    return true;
  }

  async function submitContactData(uid, type, name, email, whatsapp, treatment, origin) {
    const cardEl    = document.getElementById('pmt-card-' + uid);
    const extracted = getExtractedInfo();
    const payload = {
      visitor_id:           visitorId,
      site_id:              'PANNA',
      message_type:         type,
      name:                 name,
      email:                email    || '',
      whatsapp:             whatsapp || '',
      treatment_interest:   treatment || extracted.treatment_interest || '',
      country_of_origin:    origin    || extracted.country            || geo.country || '',
      language:             selectedLanguage || 'English',
      conversation_history: getHistory(),
      visitor_context:      buildVisitorContext()
    };
    try {
      await fetch(WEBHOOK_URL, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'x-secret-token': SECRET_TOKEN },
        body: JSON.stringify(payload)
      });
      localStorage.removeItem('pmt_pending_contact');
      setLastN8nSync();
    } catch (e) {
      localStorage.setItem('pmt_pending_contact', JSON.stringify(payload));
    }
    setHasSharedContact();
    if (cardEl) {
      cardEl.innerHTML = '<div style="text-align:center;padding:16px 0;color:#16a34a;font-weight:600;font-size:13.5px;">Thank you! Our advisor will reach out to you on WhatsApp shortly. 🙏</div>';
    }
    if (type === 'early_exit_contact') {
      setTimeout(function () {
        const overlay = document.getElementById('pmt-reengage-overlay');
        if (overlay) overlay.remove();
        hideWidget();
      }, 2500);
    }
  }

  // ── Show inline contact card ───────────────────────────────────────────────
  function showInlineContactCard(force, prefill, isUpdate) {
    if (!isUpdate && getHasSharedContact()) return;
    const existingCard = document.getElementById('pmt-card-inline');
    if (!force && !isUpdate) {
      if (existingCard) { existingCard.scrollIntoView({ behavior: 'smooth', block: 'nearest' }); return; }
      if (contactCardShown) return;
    } else {
      if (existingCard) {
        const wrap = existingCard.parentElement;
        if (wrap && wrap !== messagesEl) wrap.remove(); else existingCard.remove();
      }
    }
    contactCardShown = true;
    const type = isUpdate ? 'update_contact' : 'contact_capture';
    const hasPrefill = prefill && (prefill.name || prefill.whatsapp || prefill.email);
    if (!hasPrefill && !isUpdate) {
      addBubble('Please share your contact details below so our advisor can reach out to you on WhatsApp.', 'bot');
    }
    const wrapper = document.createElement('div');
    wrapper.style.alignSelf = 'stretch';
    wrapper.innerHTML = buildContactCardHTML('inline', type, prefill, isUpdate);
    messagesEl.appendChild(wrapper);
    setTimeout(function() { wrapper.scrollIntoView({ behavior: 'smooth', block: 'start' }); }, 50);
    setupContactCardListeners('inline', type, function () { wrapper.remove(); });
  }

  // ── Re-engagement overlay ──────────────────────────────────────────────────
  function showReEngagementOverlay() {
    if (reEngagementShown)     return;
    if (!conversationStarted)  return;
    if (getMessageCount() >= 12) return;
    if (getHasSharedContact()) return;
    reEngagementShown = true;
    clearIdleTimer();
    widget.classList.remove('pmt-hidden');
    widget.classList.add('pmt-visible');
    const overlay = document.createElement('div');
    overlay.className = 'pmt-reengage-overlay';
    overlay.id        = 'pmt-reengage-overlay';
    overlay.innerHTML = buildContactCardHTML('exit', 'early_exit_contact');
    messagesEl.appendChild(overlay);
    scrollToBottom();
    setupContactCardListeners('exit', 'early_exit_contact', function () {
      overlay.remove();
      hideWidget();
    });
  }

  // ── Idle timer ─────────────────────────────────────────────────────────────
  function resetIdleTimer() {
    clearIdleTimer();
    if (!conversationStarted) return;
    if (getMessageCount() >= 12) return;
    if (reEngagementShown) return;
    idleTimer = setTimeout(function () { showReEngagementOverlay(); }, IDLE_MS);
  }
  function clearIdleTimer() { if (idleTimer) { clearTimeout(idleTimer); idleTimer = null; } }

  ['keydown', 'click', 'touchstart'].forEach(function (ev) {
    widget.addEventListener(ev, function () {
      if (conversationStarted) resetIdleTimer();
    }, { passive: true });
  });

  // ── Language selector ──────────────────────────────────────────────────────
  const EXTRA_LANGUAGES = ['Arabic', 'Bengali', 'Pashto', 'Dari', 'French', 'Swahili', 'Russian', 'Nepali', 'Urdu', 'Tamil', 'Sinhala', 'Portuguese'];

  function showLanguageSelector() {
    const regional = getRegionalLanguages(geo.country_code || '');
    const seen     = new Set(['English']);
    const langMap  = [{ label: 'English', value: 'English' }];
    regional.forEach(function (lang) {
      if (!seen.has(lang)) { langMap.push({ label: lang, value: lang }); seen.add(lang); }
    });
    if (!seen.has('Bengali')) { langMap.push({ label: 'Bengali (\u09ac\u09be\u0982\u09b2\u09be)', value: 'Bengali' }); seen.add('Bengali'); }
    if (!seen.has('Pashto'))  { langMap.push({ label: 'Pashto (\u067e\u069a\u062a\u0648)',   value: 'Pashto'  }); seen.add('Pashto'); }

    const bubble = document.createElement('div');
    bubble.className = 'pmt-bubble pmt-bot';
    bubble.innerHTML = `
      <div style="margin-bottom:8px;">Please select your preferred language:</div>
      <div class="pmt-lang-selector" id="pmt-lang-selector-primary">
        ${langMap.map(l => `<button class="pmt-lang-btn" data-lang="${l.value}" data-label="${l.label}">${l.label}</button>`).join('')}
        <button class="pmt-lang-btn" id="pmt-lang-other">Other</button>
      </div>`;
    messagesEl.appendChild(bubble);
    scrollToBottom();

    bubble.querySelectorAll('.pmt-lang-btn:not(#pmt-lang-other)').forEach(function (btn) {
      btn.addEventListener('click', function () {
        selectLanguage(this.getAttribute('data-lang'), this.getAttribute('data-label'));
        bubble.querySelectorAll('.pmt-lang-btn').forEach(function (b) {
          b.disabled = true; b.style.opacity = '0.5'; b.style.cursor = 'default';
        });
        this.style.opacity = '1'; this.style.background = PRIMARY; this.style.color = '#fff';
      });
    });

    document.getElementById('pmt-lang-other').addEventListener('click', function () {
      bubble.querySelectorAll('.pmt-lang-btn').forEach(function (b) {
        b.disabled = true; b.style.opacity = '0.5'; b.style.cursor = 'default';
      });
      showExtendedLanguages(seen);
    });
  }

  function showExtendedLanguages(seen) {
    const extras = EXTRA_LANGUAGES.filter(function (l) { return !seen.has(l); }).slice(0, 6);
    const extBubble = document.createElement('div');
    extBubble.className = 'pmt-bubble pmt-bot';
    extBubble.innerHTML = `
      <div style="margin-bottom:8px;">Here are more options:</div>
      <div class="pmt-lang-selector">
        ${extras.map(l => `<button class="pmt-lang-btn" data-lang="${l}" data-label="${l}">${l}</button>`).join('')}
        <button class="pmt-lang-btn" id="pmt-lang-more">More &rarr;</button>
      </div>`;
    messagesEl.appendChild(extBubble);
    scrollToBottom();

    extBubble.querySelectorAll('.pmt-lang-btn:not(#pmt-lang-more)').forEach(function (btn) {
      btn.addEventListener('click', function () {
        selectLanguage(this.getAttribute('data-lang'), this.getAttribute('data-label'));
        extBubble.querySelectorAll('.pmt-lang-btn').forEach(function (b) {
          b.disabled = true; b.style.opacity = '0.5'; b.style.cursor = 'default';
        });
        this.style.opacity = '1'; this.style.background = PRIMARY; this.style.color = '#fff';
      });
    });

    document.getElementById('pmt-lang-more').addEventListener('click', function () {
      extBubble.querySelectorAll('.pmt-lang-btn').forEach(function (b) {
        b.disabled = true; b.style.opacity = '0.5'; b.style.cursor = 'default';
      });
      awaitingLanguageInput = true;
      setInputEnabled(true);
      addBubble('No problem! Just type the language you\'d like to chat in.', 'bot');
    });
  }

  function selectLanguage(lang, displayName) {
    selectedLanguage = lang;
    localStorage.setItem('pmt_lang', lang);
    if (!getHasChatted()) { setHasChatted(); incChatCount(); }
    conversationStarted = true;
    addBubble(displayName, 'user');
    setInputEnabled(true);
    resetIdleTimer();
    const greeting = lang === 'English'
      ? 'Language selected: English. Greet warmly: "Hi! I\'m Dravya from Panna Medi Tour. May I know your name please?"'
      : 'Language selected: ' + lang + '. Greet warmly in ' + lang + ' using Roman/English script only (never Devanagari, Arabic, Bengali or any native script). Introduce yourself as Dravya from Panna Medi Tour and ask for their name.';
    sendToWebhook(greeting, true);
  }

  // ── Fallback ───────────────────────────────────────────────────────────────
  function showFallback() {
    if (fallbackMode) return;
    fallbackMode = true;
    setInputEnabled(false);
    addBubble('We\'re having a little trouble connecting right now. Please leave your details below and our advisor will reach out to you on WhatsApp.', 'bot');
    const wrapper = document.createElement('div');
    wrapper.style.alignSelf = 'stretch';
    wrapper.innerHTML = buildContactCardHTML('fallback', 'contact_capture');
    messagesEl.appendChild(wrapper);
    scrollToBottom();
    setupContactCardListeners('fallback', 'contact_capture', function () { wrapper.remove(); });
  }

  // ── Session end ────────────────────────────────────────────────────────────
  function sendSessionEnd() {
    if (sessionEndSent)         return;
    if (!conversationStarted)   return;
    if (getMessageCount() < 2)  return;
    sessionEndSent = true;
    fetch(WEBHOOK_URL, {
      method:  'POST',
      headers: { 'Content-Type': 'application/json', 'x-secret-token': SECRET_TOKEN },
      body: JSON.stringify({
        visitor_id:           visitorId,
        site_id:              'PANNA',
        message:              '',
        message_type:         'session_end',
        language:             selectedLanguage || 'English',
        conversation_history: getHistory(),
        visitor_context:      buildVisitorContext()
      })
    }).catch(function () {});
  }

  // ── Build visitor context ──────────────────────────────────────────────────
  function buildVisitorContext() {
    return {
      city:               geo.city    || '',
      country:            geo.country || '',
      country_code:       geo.country_code || '',
      device:             isMobile ? 'mobile' : 'desktop',
      page_url:           window.location.href,
      visit_count:        visitCount,
      time_on_page:       getTimeOnPage(),
      has_chatted:        getHasChatted(),
      has_shared_contact: getHasSharedContact(),
      is_returning:       isReturning
    };
  }

  // ── Webhook ────────────────────────────────────────────────────────────────
  async function sendToWebhook(message, isSystem) {
    if (!isSystem) {
      const c = getMessageCount() + 1;
      setMessageCount(c);
      msgCount = c;
      const h = getHistory();
      h.push({ role: 'user', content: message });
      saveHistory(h);
    }

    setInputEnabled(false);
    showTyping();
    resetIdleTimer();

    try {
      const res = await fetch(WEBHOOK_URL, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'x-secret-token': SECRET_TOKEN },
        body: JSON.stringify({
          visitor_id:           visitorId,
          site_id:              'PANNA',
          message:              message,
          message_type:         'chat',
          language:             selectedLanguage || 'English',
          conversation_history: getHistory().slice(-10),
          visitor_context:      buildVisitorContext()
        })
      });

      if (!res.ok) throw new Error('HTTP ' + res.status);
      const data  = await res.json();
      removeTyping();

      const reply = data && data.reply ? data.reply : null;
      if (!reply) throw new Error('No reply');

      if (data.suggest_language && typeof data.suggest_language === 'string' && data.suggest_language !== selectedLanguage) {
        selectedLanguage = data.suggest_language;
        localStorage.setItem('pmt_lang', data.suggest_language);
      }

      setLastN8nSync();
      if (data.extracted_contact) mergeExtractedInfo(data.extracted_contact);
      const h = getHistory();
      h.push({ role: 'assistant', content: reply });
      saveHistory(h);
      addBubble(reply, 'bot');

      if (data.suggested_questions && Array.isArray(data.suggested_questions) && data.suggested_questions.length) {
        const chipsWrap = document.createElement('div');
        chipsWrap.className = 'pmt-faq-chips';
        data.suggested_questions.forEach(function (q) {
          const chip = document.createElement('button');
          chip.className   = 'pmt-faq-chip';
          chip.textContent = q;
          chip.addEventListener('click', function () {
            chipsWrap.remove();
            addBubble(q, 'user');
            conversationStarted = true;
            sendToWebhook(q, false);
          });
          chipsWrap.appendChild(chip);
        });
        messagesEl.appendChild(chipsWrap);
        scrollToBottom();
      }

      const current = getMessageCount();
      if (current >= 12) {
        addBubble('Thank you for connecting with us. Our advisor will reach out to you on WhatsApp shortly.', 'system');
        setInputEnabled(false);
        clearIdleTimer();
        showInlineContactCard(true);
      } else {
        setInputEnabled(true);
        if (data.contact_update && getHasSharedContact()) {
          showInlineContactCard(true, data.extracted_contact || null, true);
        } else if (current === 11) {
          showInlineContactCard();
        } else if (data.request_contact && !getHasSharedContact()) {
          showInlineContactCard(true, data.extracted_contact || null);
        }
        resetIdleTimer();
      }

    } catch (e) {
      removeTyping();
      showFallback();
    }
  }

  // ── Send handler ───────────────────────────────────────────────────────────
  function handleSend() {
    if (fallbackMode) return;
    const text = inputEl.value.trim();
    if (!text) return;
    if (awaitingLanguageInput) {
      awaitingLanguageInput = false;
      inputEl.value = ''; inputEl.style.height = 'auto';
      selectLanguage(text, text);
      return;
    }
    if (getMessageCount() >= 12) return;
    if (!selectedLanguage) {
      selectedLanguage = 'English';
      localStorage.setItem('pmt_lang', 'English');
      if (!getHasChatted()) { setHasChatted(); incChatCount(); }
    }
    inputEl.value = ''; inputEl.style.height = 'auto';
    addBubble(text, 'user');
    conversationStarted = true;
    sendToWebhook(text, false);
  }

  sendBtn.addEventListener('click', handleSend);
  inputEl.addEventListener('keydown', function (e) {
    if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); handleSend(); }
  });

  // ── Open / Close ───────────────────────────────────────────────────────────
  function hideWidget() {
    sendSessionEnd();
    widget.classList.remove('pmt-visible');
    widget.classList.add('pmt-hidden');
    launcher.classList.remove('pmt-launcher-hidden');
    notifDot.style.display = 'block';
  }

  closeBtn.addEventListener('click', function () {
    if (!getHasSharedContact() && !closeCardShown && getMessageCount() < 12) {
      closeCardShown = true;
      clearIdleTimer();
      addBubble('Before you go — our advisor can help you find the right hospital and treatment in India. Would you like to leave your WhatsApp number?', 'bot');
      showInlineContactCard(true);
    } else {
      hideWidget();
    }
  });

  launcher.addEventListener('click', function () { openWidget(); });

  function showWelcomeBack() {
    addBubble('Welcome back! Great to have you here again.', 'bot');
    const wrap = document.createElement('div');
    wrap.className = 'pmt-bubble pmt-bot';
    wrap.style.maxWidth = '100%';
    wrap.innerHTML = `
      <div style="margin-bottom:8px;">What would you like to do?</div>
      <div class="pmt-lang-selector" style="flex-direction:column;">
        <button class="pmt-lang-btn" id="pmt-wb-status">Has your advisor reached out to me?</button>
        <button class="pmt-lang-btn" id="pmt-wb-update">Update my contact details</button>
        <button class="pmt-lang-btn" id="pmt-wb-question">I have a question</button>
      </div>`;
    messagesEl.appendChild(wrap);
    scrollToBottom();

    function disableButtons() {
      wrap.querySelectorAll('.pmt-lang-btn').forEach(function (b) {
        b.disabled = true; b.style.opacity = '0.5'; b.style.cursor = 'default';
      });
    }

    document.getElementById('pmt-wb-status').addEventListener('click', function () {
      disableButtons();
      addBubble('Has your advisor reached out to me?', 'user');
      conversationStarted = true;
      setInputEnabled(getMessageCount() < 12);
      resetIdleTimer();
    });

    document.getElementById('pmt-wb-update').addEventListener('click', function () {
      disableButtons();
      addBubble('Update my contact details', 'user');
      contactCardShown = false;
      showInlineContactCard(true);
    });

    document.getElementById('pmt-wb-question').addEventListener('click', function () {
      disableButtons();
      addBubble('I have a question', 'user');
      conversationStarted = true;
      setInputEnabled(true);
      resetIdleTimer();
    });
  }

  function openWidget() {
    launcher.classList.add('pmt-launcher-hidden');
    if (widgetOpened) {
      if (widget.classList.contains('pmt-hidden')) {
        widget.classList.remove('pmt-hidden');
        widget.classList.add('pmt-visible');
        notifDot.style.display = 'none';
      }
      return;
    }
    widgetOpened = true;
    if (heartbeatTimer) { clearInterval(heartbeatTimer); }
    heartbeatTimer = setInterval(sendHeartbeat, 3000);
    widget.classList.remove('pmt-hidden');
    widget.classList.add('pmt-visible');
    notifDot.style.display = 'none';
    localStorage.setItem('pmt_opened', 'true');

    if (getHasSharedContact()) {
      showWelcomeBack();
    } else {
      if (selectedLanguage && getHistory().length > 0) {
        setInputEnabled(getMessageCount() < 12);
        if (getMessageCount() >= 12) {
          addBubble('Thank you for connecting with us. Our advisor will reach out to you on WhatsApp shortly.', 'system');
        } else {
          conversationStarted = true;
          resetIdleTimer();
        }
      } else {
        selectedLanguage = selectedLanguage || 'English';
        if (!localStorage.getItem('pmt_lang')) localStorage.setItem('pmt_lang', 'English');
        addBubble("Hi! I'm Dravya from Panna Medi Tour. How can I help you today?", 'bot');
        conversationStarted = true;
        setInputEnabled(true);
        resetIdleTimer();
      }
    }
  }

  // ── Auto-open ──────────────────────────────────────────────────────────────
  notifDot.style.display = 'flex';
  if (!isMobile && !getHasSharedContact()) {
    const pulseStyle = document.createElement('style');
    pulseStyle.textContent = `@keyframes pmt-pulse {
      0%   { box-shadow: 0 4px 16px rgba(22,163,74,0.45); }
      50%  { box-shadow: 0 4px 32px rgba(22,163,74,0.75), 0 0 0 8px rgba(22,163,74,0.12); }
      100% { box-shadow: 0 4px 16px rgba(22,163,74,0.45); }
    }`;
    document.head.appendChild(pulseStyle);
    setTimeout(function () { launcher.style.animation = 'pmt-pulse 1s ease 2'; }, 5000);
    setTimeout(function () { openWidget(); }, 25000);
  }

})();
________________________________________

</script>
<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type="text/xsl" href="//pannameditour.com/wp-content/plugins/wordpress-seo/css/main-sitemap.xsl"?>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
	<sitemap>
		<loc>https://pannameditour.com/post-sitemap.xml</loc>
		<lastmod>2026-04-01T11:52:14+00:00</lastmod>
	</sitemap>
	<sitemap>
		<loc>https://pannameditour.com/page-sitemap.xml</loc>
		<lastmod>2026-05-08T06:17:08+00:00</lastmod>
	</sitemap>
	<sitemap>
		<loc>https://pannameditour.com/category-sitemap.xml</loc>
		<lastmod>2026-04-01T11:52:14+00:00</lastmod>
	</sitemap>
	<sitemap>
		<loc>https://pannameditour.com/author-sitemap.xml</loc>
		<lastmod>2025-07-23T08:06:37+00:00</lastmod>
	</sitemap>
</sitemapindex>
<!-- XML Sitemap generated by Yoast SEO -->