<?php
/* BrewBot floating widget */
?>
<style>
  :root { /*theme*/
    --bb-bg:#fff;
    --bb-cream:#f3ede4;
    --bb-border:#e7dfd4;
    --bb-primary:#2f241d;
    --bb-shadow:0 16px 48px rgba(0,0,0,.18);
    --bb-radius:16px;
  }

  .bb-fab{ /*fab button*/
    position:fixed;
    right:16px;
    bottom:calc(16px + env(safe-area-inset-bottom,0px));
    height:48px;
    border-radius:9999px;
    border:0;
    cursor:pointer;
    background:var(--bb-primary);
    color:#fff;
    font-size:14px;
    font-weight:600;
    z-index:9999;
    box-shadow:0 8px 24px rgba(0,0,0,.25);
    display:inline-flex;
    align-items:center;
    gap:8px;
    padding:0 16px;
  }

  .bb-fab:focus {
    outline:2px solid #4c9ffe;
    outline-offset:2px;
  }

  .bb-panel { /*chat panel*/
    position:fixed;
    right:16px;
    bottom:calc(80px + env(safe-area-inset-bottom,0px));
    width:clamp(320px, 92vw, 420px); /* keep inside viewport */
    max-height:min(70vh,560px);
    z-index:9999;
    display:none;
    background:var(--bb-bg);
    border:1px solid var(--bb-border);
    border-radius:var(--bb-radius);
    box-shadow:var(--bb-shadow);
    overflow:hidden;
  }

  .bb-open .bb-panel {
    display:flex;
    flex-direction:column;
  }

  .bb-head { /*header*/
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:10px;
    padding:12px 14px;
    border-bottom:1px solid var(--bb-border);
    background:var(--bb-cream);
    color:var(--bb-primary);
    font:700 14px/1.2 "Georgia","Times New Roman",ui-serif,serif;
  }

  .bb-left { display:flex; align-items:center; gap:10px; }
  .bb-dot { width:10px; height:10px; border-radius:50%; background:#2ecc71; box-shadow:0 0 0 3px #ffffff80; }
  .bb-actions { display:flex; gap:6px; }

  .bb-btn {
    width:28px;
    height:28px;
    border:1px solid var(--bb-border);
    background:#fff;
    border-radius:8px;
    cursor:pointer;
    font:700 14px/1 Arial;
    display:grid;
    place-items:center;
  }

  .bb-log { /*messages*/
    padding:12px;
    flex:1;
    min-height:0;
    overflow:auto;
    overflow-x:hidden;
    background:#fff;
    word-break:break-word;
    overflow-wrap:anywhere;
  }

  .bb-log p {
    margin:0 0 10px;
    font:14px/1.5 system-ui,-apple-system,Segoe UI,Roboto,Arial;
    color:#2a2a2a;
    white-space:pre-wrap;
    word-break:break-word;
    overflow-wrap:anywhere;
    hyphens:auto;
  }

  .bb-log b { color:var(--bb-primary); }

  .bb-bar { /*input*/
    display:flex;
    gap:8px;
    padding:10px;
    border-top:1px solid var(--bb-border);
    background:#fff;
  }

  .bb-input {
    flex:1;
    padding:12px;
    border:1px solid #d9d3ca;
    border-radius:12px;
    font-size:16px;
    min-height:48px;
  }

  .bb-send {
    padding:0 16px;
    min-width:84px;
    height:48px;
    border:0;
    border-radius:12px;
    background:var(--bb-primary);
    color:#fff;
    font-size:16px;
    cursor:pointer;
  }

  @media (max-width:600px) { /* mobile adaptation */
    .bb-panel { right:50%; transform:translateX(50%); max-height:75vh; }
    .bb-fab { height:56px; font-size:15px; padding:0 18px; }
  }

  /* clickable product links in BrewBot replies */
  .bb-log a {
    color: #0066cc;             /* nice blue */
    font-weight: 400;           /* bolded */
    text-decoration: none;      /* remove underline by default */
    cursor: pointer;
  }

  .bb-log a:hover,
  .bb-log a:focus {
    text-decoration: underline; /* underline on hover for clarity */
  }
</style>


<button class="bb-fab" id="bb-fab" aria-haspopup="dialog" aria-controls="bb-panel" aria-expanded="false" title="Open BrewBot">
  <span aria-hidden="true">☕</span>
  <span class="bb-label">Try our Chatbot</span>
</button>

<div class="bb-panel" id="bb-panel" role="dialog" aria-label="BrewBot chat">
  <div class="bb-head">
    <div class="bb-left"><span class="bb-dot"></span> BrewBot • Coffee help</div>
    <div class="bb-actions">
      <!-- minimise only -->
      <button type="button" class="bb-btn" id="bb-min" title="Minimise" aria-label="Minimise">–</button>
    </div>
  </div>

  <div class="bb-log" id="bb-log" role="log" aria-live="polite"></div>

  <form class="bb-bar" id="bb-form" autocomplete="off">
    <input id="bb-input" class="bb-input" autocomplete="off" placeholder="Ask Anything" aria-label="Message BrewBot" />
    <button class="bb-send" id="bb-send" type="submit">Send</button>
  </form>
</div>

<script>
(function(){ 
    //widget
  const root=document.documentElement,
        fab=document.getElementById('bb-fab'),
        panel=document.getElementById('bb-panel'),
        log=document.getElementById('bb-log'),
        form=document.getElementById('bb-form'),
        input=document.getElementById('bb-input'),
        btnMin=document.getElementById('bb-min');

  const CSRF=document.querySelector('meta[name="csrfToken"]')?.content || '';
  const ENDPOINT='<?= $this->Url->build("/api/chat/recommend") ?>';

  //open and close
  function openChat(){ root.classList.add('bb-open'); fab.setAttribute('aria-expanded','true'); localStorage.setItem('brewhub_chat_open','1'); setTimeout(()=>input?.focus(),50); }
  function closeChat(){ root.classList.remove('bb-open'); fab.setAttribute('aria-expanded','false'); localStorage.setItem('brewhub_chat_open','0'); fab.focus(); }
  fab.addEventListener('click', ()=> root.classList.contains('bb-open') ? closeChat() : openChat());
  btnMin.addEventListener('click', closeChat);

  //add line
  function add(who, txt){
  const isBot = who === 'BrewBot';
  const safe = (txt ?? '').toString();
  const content = isBot ? safe : safe.replace(/</g, '&lt;');
  log.insertAdjacentHTML('beforeend', `<p><b>${who}:</b> ${content}</p>`);
  log.scrollTop = log.scrollHeight;
}


  /* hello */
  add('BrewBot','Hi! I can recommend a coffee or share our hours, address and contact. What would you like?');

  /* submit */
  form.addEventListener('submit', async (e)=>{
    e.preventDefault();
    const msg=input.value.trim(); if(!msg) return;
    add('You', msg); input.value='';

    const ctrl=new AbortController(); const t=setTimeout(()=>ctrl.abort(),20000);
    try{
      const r=await fetch(ENDPOINT,{
        method:'POST',credentials:'same-origin',
        headers:{'Content-Type':'application/json',...(CSRF? {'X-CSRF-Token':CSRF}: {})},
        body:JSON.stringify({message:msg}),signal:ctrl.signal
      });
      clearTimeout(t);

      /* quiet fallback (no visible errors) */
      const ct=(r.headers.get('content-type')||'').toLowerCase();
      let reply='';
      if(ct.includes('application/json')){
        const j=await r.json().catch(()=>null);
        reply=(j && (j.text||j.error)) ? (j.text||'') : 'Sorry—could you try that again?';
      }else{
        await r.text().catch(()=>{});
        reply='Sorry—having a little trouble right now. Please try again.';
      }
      add('BrewBot', reply || 'Sorry—could you try that again?');
    }catch(_){
      add('BrewBot','Sorry—having a little trouble right now. Please try again.');
    }
  });

  /* keep scroll tidy */
  window.addEventListener('resize', ()=> { log.scrollTop=log.scrollHeight; });

  /* remember open state */
  if(localStorage.getItem('brewhub_chat_open')==='1') openChat();
})();
</script>
