/* OurNetHelps Mortgage Q&A Assistant — Frontend Widget */
/* globals onhmqaData */
(function(){
'use strict';

function onhmqaInit(){

var CFG = window.onhmqaData || {};

/* ── Custom Q&A from broker settings ── */
var ONHMQA_DB = CFG.qa || [];

/* ── Built-in default mortgage Q&A ── */
var ONHMQA_DEFAULT=[
  {k:["rate","rates","interest","today rate","current rate","mortgage rate"],q:"What are current mortgage rates?",a:"Mortgage rates change daily based on market conditions. Contact me directly for a live quote tailored to your loan size, credit profile, and situation."},
  {k:["pre-approval","preapproval","pre approval","get approved","qualify","pre-qualify","prequalify"],q:"How do I get pre-approved?",a:"Getting pre-approved is a great first step. I will need some income documents and financial information. Timelines vary depending on your situation. Reach out and I can guide you through the process."},
  {k:["down payment","downpayment","how much down","minimum down","down payment needed"],q:"How much down payment do I need?",a:"It depends on the loan program and your profile. Some programs allow low down-payment options. Contact me to find out which programs you may qualify for and what fits your situation best."},
  {k:["credit score","credit","fico","minimum credit","credit needed","bad credit"],q:"What credit score do I need?",a:"Credit requirements vary by loan program, lender, and borrower profile. Generally, higher scores can open more options and better rates. Contact me to review your situation and find programs that may work for you."},
  {k:["closing cost","closing costs","how much closing","fees","total cost"],q:"What are the closing costs?",a:"Closing costs vary by loan, location, lender, and transaction. They can include appraisal, title insurance, and lender fees among other items. Your Loan Estimate will detail the expected costs for your specific loan."},
  {k:["fha","va loan","conventional","usda","loan type","what loan","which loan","loan types"],q:"What loan types do you offer?",a:"I work with a range of loan programs including FHA, VA, Conventional, and USDA. Each has different eligibility requirements and benefits. Contact me to find out which programs may be available for your situation."},
  {k:["how long","timeline","closing time","how fast","process time","time to close"],q:"How long does the process take?",a:"Timelines vary depending on the loan type, documentation, lender, underwriting, and appraisal. I work to keep the process moving and will update you at every stage. Contact me for a more specific estimate."},
  {k:["refinance","refi","lower rate","lower payment","cash out","refinancing"],q:"Should I refinance?",a:"Whether refinancing makes sense depends on your current rate, new rate, closing costs, remaining term, and how long you plan to stay. I can run a break-even analysis to see if it could save you money."},
  {k:["first time","first home","first buyer","first-time","buying first","new buyer"],q:"I am a first-time homebuyer",a:"Congratulations! Start with a free pre-approval so you know your budget. I specialize in first-time buyers and will explain every step clearly. Down payment assistance programs may also be available in your area."},
  {k:["contact","reach","call","email","talk","speak","appointment","schedule","get in touch"],q:"How do I contact you?",a:"You can call or text me directly using the phone number shown above, or send an email. I typically respond within a few hours on business days."}
];

/* ── Helpers ── */
function isMobile(){ return window.innerWidth<=540; }

function safeText(str){
  var d=document.createElement('div');
  d.textContent=String(str||'');
  return d.innerHTML;
}

function linkify(t){
  if(t.indexOf('<a ')!==-1){ return t.replace(/\n/g,'<br>'); }
  return t.replace(/https?:\/\/[^\s<,\n"']+/g,function(u){
    return '<a href="'+u+'" target="_blank" rel="noopener noreferrer">'+u+'</a>';
  }).replace(/\n/g,'<br>');
}

/* ── DOM refs ── */
var Btn       = document.getElementById('onhmqa-btn');
var Box       = document.getElementById('onhmqa-box');
var Msgs      = document.getElementById('onhmqa-msgs');
var Chips     = document.getElementById('onhmqa-chips');
var Inp       = document.getElementById('onhmqa-inp');
var Snd       = document.getElementById('onhmqa-snd');
var Popup     = document.getElementById('onhmqa-popup');
var PopupX    = document.getElementById('onhmqa-popup-x');
var HeadClose = document.getElementById('onhmqa-head-close');

if(!Btn||!Box){return;}

var isOpen=false, started=false, msgCount=0, popupTimer=null;

/* ── hidePopup ── */
function hidePopup(){
  if(!Popup) return;
  Popup.classList.remove('onhmqa-popup-show');
  if(popupTimer){ clearTimeout(popupTimer); popupTimer=null; }
}

/* ── openChat / closeChat ── */
function openChat(){
  hidePopup();
  isOpen=true;
  Box.classList.add('onhmqa-visible');
  Btn.classList.add('onhmqa-open');
  Btn.setAttribute('aria-expanded','true');
  if(!started){ started=true; init(); }
  if(!isMobile()){ setTimeout(function(){ Inp.focus(); },250); }
  if(isMobile()){ document.body.style.overflow='hidden'; }
}

function closeChat(){
  isOpen=false;
  Box.classList.remove('onhmqa-visible');
  Btn.classList.remove('onhmqa-open');
  Btn.setAttribute('aria-expanded','false');
  document.body.style.overflow='';
  Btn.focus();
}

/* ── Button click ── */
Btn.addEventListener('click',function(e){
  e.stopPropagation();
  isOpen ? closeChat() : openChat();
});

/* ── Outside click ── */
document.addEventListener('click',function(e){
  if(!isOpen) return;
  if(Box.contains(e.target)) return;
  if(Btn===e.target) return;
  closeChat();
});

document.addEventListener('keydown',function(e){
  if(e.key==='Escape' && isOpen){ closeChat(); }
});

window.addEventListener('resize',function(){
  if(!isMobile() && isOpen){ document.body.style.overflow=''; }
});

/* ── Mobile header close button ── */
if(HeadClose){
  HeadClose.addEventListener('click',function(e){
    e.stopPropagation();
    closeChat();
  });
}

/* ── Popup bubble ── */
if(CFG.popupOn && Popup){
  var dismissed=false;
  try{ if(sessionStorage.getItem('onhmqa_popup_off')) dismissed=true; }catch(ex){}

  if(!dismissed){
    popupTimer=setTimeout(function(){
      Popup.classList.add('onhmqa-popup-show');
      var autoHide=setTimeout(function(){ hidePopup(); },8000);

      Popup.addEventListener('click',function(e){
        e.stopPropagation();
        if(e.target===PopupX) return;
        clearTimeout(autoHide);
        hidePopup();
        openChat();
      });

      if(PopupX){
        PopupX.addEventListener('click',function(e){
          e.stopPropagation();
          clearTimeout(autoHide);
          hidePopup();
          try{ sessionStorage.setItem('onhmqa_popup_off','1'); }catch(ex){}
        });
      }
    }, CFG.popupDelay*1000);
  }
}

/* ── Init conversation ── */
function init(){
  addBot(CFG.welcome||'Hi! Ask me anything about mortgages.');
  buildChips();
}

/* ── Message helpers ── */
function addBot(html){
  var d=document.createElement('div');
  d.className='onhmqa-m onhmqa-bot';
  d.innerHTML=linkify(html);
  Msgs.appendChild(d);
  scrollDown();
}

function addUsr(text){
  var d=document.createElement('div');
  d.className='onhmqa-m onhmqa-usr';
  d.textContent=text;
  Msgs.appendChild(d);
  scrollDown();
}

function scrollDown(){ Msgs.scrollTop=Msgs.scrollHeight; }

/* ── Typing indicator ── */
function showTyping(){
  var d=document.createElement('div');
  d.className='onhmqa-m onhmqa-bot';
  d.id='onhmqa-typing';
  d.innerHTML='<span class="onhmqa-typing-dots"><span class="onhmqa-dot"></span><span class="onhmqa-dot"></span><span class="onhmqa-dot"></span></span>';
  Msgs.appendChild(d);
  scrollDown();
  return d;
}
function killTyping(d){ if(d && d.parentNode){ d.parentNode.removeChild(d); } }

/* ── Chips ── */
function buildChips(){
  Chips.innerHTML='';
  var count=0;
  function addChip(q){
    if(count>=4) return;
    var c=document.createElement('button');
    c.className='onhmqa-chip';
    c.type='button';
    c.textContent=q;
    c.addEventListener('click',function(e){ e.stopPropagation(); Chips.innerHTML=''; handle(q); });
    Chips.appendChild(c);
    count++;
  }
  ONHMQA_DB.forEach(function(item){ if(item.q) addChip(item.q); });
  ONHMQA_DEFAULT.forEach(function(item){ if(item.q && count<4) addChip(item.q); });
}

/* ── Answer matching ── */
function findAns(q){
  var ql=q.toLowerCase();
  var best=null, top=0;
  function search(db){
    db.forEach(function(item){
      var score=0;
      item.k.forEach(function(kw){
        if(ql.indexOf(kw.toLowerCase())!==-1){
          score += 1 + (kw.length>10 ? 2 : kw.length>6 ? 1 : 0);
        }
      });
      if(score>top){ top=score; best=item; }
    });
  }
  search(ONHMQA_DB);
  if(top===0) search(ONHMQA_DEFAULT);
  return top>0 ? best.a : null;
}

/* ── Handle message ── */
function handle(q){
  q=q.trim();
  if(!q || Snd.disabled) return;
  Snd.disabled=true;
  Inp.disabled=true;
  addUsr(q);
  Inp.value='';
  msgCount++;
  Chips.innerHTML='';
  var t=showTyping();
  setTimeout(function(){
    killTyping(t);
    var ans=findAns(q);
    if(ans){
      addBot(ans);
    } else {
      var fb=safeText(CFG.fallback||'');
      if(CFG.email){ fb+=' <a href="mailto:'+safeText(CFG.email)+'">'+safeText(CFG.email)+'</a>'; }
      if(CFG.contactUrl){ fb+=' or <a href="'+safeText(CFG.contactUrl)+'" target="_blank" rel="noopener noreferrer">use the contact form</a>.'; }
      addBot(fb);
    }
    Snd.disabled=false;
    Inp.disabled=false;
    if(!isMobile()) Inp.focus();
  }, 650+Math.random()*300);
}

Snd.addEventListener('click',function(e){ e.stopPropagation(); handle(Inp.value); });
Inp.addEventListener('keydown',function(e){
  if(e.key==='Enter'){ e.preventDefault(); handle(Inp.value); }
});

} // end onhmqaInit

if(document.readyState==='loading'){
  document.addEventListener('DOMContentLoaded', onhmqaInit);
} else {
  onhmqaInit();
}

})();
