{% load static %}
<!doctype html>
<html lang="en" data-is-staff=\"{% if request.user.is_authenticated and request.user.is_staff %}1{% else %}0{% endif %}\">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>{% if page_title %}{{ page_title }} | {% endif %}Holistic Caregiver</title>
  <link rel="manifest" href="/manifest.json">
  <meta name="theme-color" content="#0B2B40">
  <link rel="apple-touch-icon" href="/static/website/pwa/icons/icon-192x192.png">
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="default">

  <meta name="description" content="{{ page_description|default:'Professional home care and nursing services you can trust.' }}">
  <link rel="icon" href="{% static 'website/img/favicon.png' %}">
  <link rel="stylesheet" href="{% static 'website/css/site.css' %}">
</head>
<body>
  {% include "website/partials/navbar.html" %}
  <main class="container">
    {% block content %}{% endblock %}
    {% include "website/partials/cta_strip.html" %}
  </main>
  {% include "website/partials/footer.html" %}

  <script>
/* PWA: service worker + install prompt */
(function(){
  if ('serviceWorker' in navigator) {
    window.addEventListener('load', function(){
      navigator.serviceWorker.register('/sw.js').catch(function(){});
    });
  }

  let deferredPrompt = null;
  const btn = document.getElementById('pwaInstallBtn');
  const btn2 = document.getElementById('pwaInstallBtnFooter');

  function showBtn(){
    if(btn) btn.style.display = 'inline-flex';
    if(btn2) btn2.style.display = 'inline-flex';
  }
  function hideBtn(){
    if(btn) btn.style.display = 'none';
    if(btn2) btn2.style.display = 'none';
  }

  window.addEventListener('beforeinstallprompt', (e) => {
    e.preventDefault();
    deferredPrompt = e;
    showBtn();
  });

  if(btn){
    btn.addEventListener('click', async () => {
      if(!deferredPrompt) return;
      deferredPrompt.prompt();
      const choice = await deferredPrompt.userChoice;
      deferredPrompt = null;
      if(choice && choice.outcome === 'accepted') hideBtn();
    });

  if(btn2){
    btn2.addEventListener('click', async () => {
      if(!deferredPrompt) return;
      deferredPrompt.prompt();
      const choice = await deferredPrompt.userChoice;
      deferredPrompt = null;
      if(choice && choice.outcome === 'accepted') hideBtn();
    });
  }

  }

  window.addEventListener('appinstalled', () => hideBtn());
})();
</script>


<script>
/* Support widget toggle */
(function(){
  const fab = document.getElementById('supportFab');
  const panel = document.getElementById('supportPanel');
  const closeBtn = document.getElementById('supportClose');
  if(!fab || !panel || !closeBtn) return;

  function open(){ panel.classList.add('open'); }
  function close(){ panel.classList.remove('open'); }

  fab.addEventListener('click', ()=> {
    if(panel.classList.contains('open')) close(); else open();
  });
  closeBtn.addEventListener('click', close);

  // close when clicking outside on desktop
  document.addEventListener('click', (e)=>{
    if(!panel.classList.contains('open')) return;
    if(panel.contains(e.target) || fab.contains(e.target)) return;
    close();
  });
})();
</script>


<script>
/* In-app push notifications (PWA-friendly) for staff */
(function(){
  const isStaff = document.documentElement.getAttribute('data-is-staff') === '1';
  if(!isStaff) return;

  // Ask permission once (optional)
  if ('Notification' in window && Notification.permission === 'default') {
    // do not annoy: only ask after first interaction
    window.addEventListener('click', function once(){
      window.removeEventListener('click', once);
      try{ Notification.requestPermission(); }catch(e){}
    }, {once:true});
  }

  let seen = new Set();
  async function poll(){
    try{
      const res = await fetch("{% url 'website:staff_notifications_poll' %}", {credentials:'same-origin'});
      const data = await res.json();
      const items = data.items || [];
      const newIds = [];
      for(const n of items){
        if(seen.has(n.id)) continue;
        seen.add(n.id);
        newIds.push(n.id);
        // Browser notification
        if ('Notification' in window && Notification.permission === 'granted') {
          try{ new Notification(n.title, { body: n.body || '' }); }catch(e){}
        }
        // Tiny toast
        const toast = document.createElement('div');
        toast.style.position='fixed';
        toast.style.left='16px';
        toast.style.bottom='16px';
        toast.style.zIndex='9999';
        toast.style.padding='12px 14px';
        toast.style.borderRadius='14px';
        toast.style.border='1px solid rgba(0,0,0,.08)';
        toast.style.background='#fff';
        toast.style.boxShadow='0 18px 50px rgba(11,43,64,.18)';
        toast.innerHTML = '<strong>'+ (n.title||'Notification') +'</strong><div style="margin-top:4px;font-size:12px;opacity:.75">'+ (n.body||'') +'</div>';
        toast.addEventListener('click', ()=>{ if(n.url) location.href=n.url; });
        document.body.appendChild(toast);
        setTimeout(()=>{ toast.remove(); }, 6500);
      }

      // Mark read (batch)
      if(newIds.length){
        const fd = new FormData();
        fd.append('ids', newIds.join(','));
        fd.append('csrfmiddlewaretoken', (document.querySelector('input[name=csrfmiddlewaretoken]')||{}).value || '');
        fetch("{% url 'website:staff_notifications_mark_read' %}", {method:'POST', body: fd, credentials:'same-origin'}).catch(()=>{});
      }
    }catch(e){}
  }
  setInterval(poll, 12000);
  poll();
})();

  // --- Premium support widget: preview + typing + instant success ---
  const previewEl = document.getElementById("supportPreview");
  const typingEl = document.getElementById("supportTyping");
  const supportForm = document.getElementById("supportForm");

  const loadBtn = document.getElementById("supportLoadPreview");
  if(loadBtn){
    loadBtn.addEventListener("click", () => loadPreview());
  }

  // Prefill phone + ticket id from localStorage
  try{
    const p = localStorage.getItem("hc_support_phone") || "";
    const t = localStorage.getItem("hc_support_ticket") || "";
    const phoneIn = supportForm?.querySelector('input[name="phone"]');
    const ticketIn = supportForm?.querySelector('input[name="ticket_id"]');
    if(phoneIn && p && !phoneIn.value) phoneIn.value = p;
    if(ticketIn && t && !ticketIn.value) ticketIn.value = t;
  }catch(e){}


  function escapeHtml(s){
    return (s||"").replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;");
  }

  function renderPreview(messages, ticketUrl){
    if(!previewEl) return;
    if(!messages || messages.length===0){
      previewEl.innerHTML = '';
      return;
    }
    const parts = [];
    parts.push('<div class="preview-head">Recent conversation</div>');
    for(const m of messages){
      const cls = (m.sender === "staff") ? "staff" : (m.sender === "client" ? "client" : "bot");
      parts.push(
        `<div class="bubble ${cls}">${escapeHtml(m.message)}</div>`
      );
    }
    if(ticketUrl){
      parts.push(`<a class="preview-link" href="${ticketUrl}">Open full conversation →</a>`);
    }
    previewEl.innerHTML = parts.join("");
  }

  async function loadPreview(){
    try{
      const phone = (document.getElementById("supportLookupPhone")?.value || localStorage.getItem("hc_support_phone") || "").trim();
      const qs = phone ? ("?phone=" + encodeURIComponent(phone)) : "";
      const r = await fetch("{% url 'website:support_panel_preview' %}" + qs, {headers: {"X-Requested-With":"XMLHttpRequest"}});
      const j = await r.json();
      if(j && j.ok){
          try{ if(j.ticket_public_id){ localStorage.setItem("hc_support_ticket", j.ticket_public_id); const ti = supportForm.querySelector('input[name="ticket_id"]'); if(ti) ti.value = j.ticket_public_id; } }catch(e){}
        renderPreview(j.messages || [], j.ticket_url || "");
      } else {
        renderPreview([], "");
      }
    }catch(e){
      renderPreview([], "");
    }
  }

  
  // Cross-device preview: store phone locally and reload preview
  const lookupPhone = document.getElementById("supportLookupPhone");
  const lookupBtn = document.getElementById("supportLookupBtn");
  if (lookupPhone){
    const saved = localStorage.getItem("hc_support_phone");
    if (saved && !lookupPhone.value){ lookupPhone.value = saved; }
    lookupPhone.addEventListener("change", () => {
      const v = lookupPhone.value.trim();
      if (v) localStorage.setItem("hc_support_phone", v);
      loadPreview();
    });
  }
  if (lookupBtn){
    lookupBtn.addEventListener("click", () => {
      const v = (lookupPhone?.value || "").trim();
      if (v) localStorage.setItem("hc_support_phone", v);
      loadPreview();
    });
  }

// When panel opens, load last 3 messages
  if (supportFab && supportPanel){
    if(supportFab) supportFab.addEventListener("click", () => {
      setTimeout(loadPreview, 150);
    }, {capture:false});
  }

  // Ajax submit for instant success + typing animation
  if (supportForm){
    supportForm.addEventListener("submit", async (ev) => {
      ev.preventDefault();
      if(typingEl){ typingEl.style.display = "flex"; }
      const formData = new FormData(supportForm);
      try{
        const r = await fetch(supportForm.action, {
          method: "POST",
          headers: {"X-Requested-With":"XMLHttpRequest"},
          body: formData
        });
        const j = await r.json();
        if(typingEl){ typingEl.style.display = "none"; }

        if(j && j.ok){
          try{ if(j.ticket_public_id){ localStorage.setItem("hc_support_ticket", j.ticket_public_id); const ti = supportForm.querySelector('input[name="ticket_id"]'); if(ti) ti.value = j.ticket_public_id; } }catch(e){}
          // success bubble
          const url = j.ticket_url || "";
          const success = document.createElement("div");
          success.className = "bubble bot success";
          success.innerHTML = "Sent ✅ We’ve received your message.";
          previewEl?.prepend(success);

          // clear message box
          const ta = supportForm.querySelector('textarea[name="message"]');
          if(ta) ta.value = "";

          // Reload preview so user sees latest 3
          await loadPreview();

          // Optional: show link
          if(url){
            const link = document.createElement("a");
            link.className = "preview-link";
            link.href = url;
            link.textContent = "Open full conversation →";
            previewEl?.appendChild(link);
          }
        } else {
          const err = document.createElement("div");
          err.className = "bubble bot notice";
          err.textContent = "Could not send right now. Please try again or use WhatsApp/Call.";
          previewEl?.prepend(err);
        }
      }catch(e){
        if(typingEl){ typingEl.style.display = "none"; }
        const err = document.createElement("div");
        err.className = "bubble bot notice";
        err.textContent = "Network error. Please try again or use WhatsApp/Call.";
        previewEl?.prepend(err);
      }
    });
  }

</script>

<!-- Floating support chat (Olutech iCare style) -->
<button id="icareChatFab" class="icare-chat-fab" type="button" aria-label="Open chat">
  Chat
</button>

<div id="icareChatPanel" class="icare-chat-panel" aria-hidden="true" role="dialog" aria-label="Support chat">
  <div class="icare-chat-head">
    <div>
      <div class="icare-chat-title">Olutech iCare Support</div>
      <div class="icare-chat-sub">We're here to help!</div>
    </div>
    <button id="icareChatClose" class="icare-chat-close" type="button" aria-label="Close chat">✕</button>
  </div>

  <div class="icare-chat-body" id="icareChatBody">
    <div class="icare-msg bot">
      <div class="icare-bubble">
        <div class="icare-msg-name">Support Bot</div>
        Hi! 😊 How can we help you today?
      </div>
    </div>

    <div class="icare-help-card">
      <div class="icare-help-title">Need more help?</div>

      <a class="icare-help-row" href="https://wa.me/{{ SITE_WHATSAPP }}" target="_blank" rel="noopener">
        <span class="icare-help-left">
          <span class="icare-help-kind">WhatsApp</span>
          <span class="icare-help-meta">{{ SITE_PHONE }}</span>
        </span>
        <span class="icare-help-action">Open</span>
      </a>

      <a class="icare-help-row" href="mailto:{{ SITE_EMAIL }}">
        <span class="icare-help-left">
          <span class="icare-help-kind">Email</span>
          <span class="icare-help-meta">{{ SITE_EMAIL }}</span>
        </span>
        <span class="icare-help-action">Send</span>
      </a>

      <a class="icare-help-row" href="{% url 'website:support_ticket_create' %}">
        <span class="icare-help-left">
          <span class="icare-help-kind">Create Support Ticket</span>
          <span class="icare-help-meta">Sign in to open a detailed ticket.</span>
        </span>
        <span class="icare-help-action">Go</span>
      </a>
    </div>
  </div>

  <form id="icareChatForm" class="icare-chat-input" autocomplete="off">
    <input id="icareChatInput" type="text" placeholder="Type your message..." maxlength="600" />
    <button class="icare-send" type="submit" aria-label="Send">➤</button>
  </form>
</div>

<script>
(function(){
  const fab = document.getElementById('icareChatFab');
  const panel = document.getElementById('icareChatPanel');
  const closeBtn = document.getElementById('icareChatClose');
  const form = document.getElementById('icareChatForm');
  const input = document.getElementById('icareChatInput');
  const body = document.getElementById('icareChatBody');

  if(!fab || !panel || !closeBtn || !form || !input || !body) return;

  function openPanel(){
    panel.classList.add('open');
    panel.setAttribute('aria-hidden','false');
    // tiny delay so the panel renders before focus
    setTimeout(()=>{ try{ input.focus(); }catch(e){} }, 20);
  }
  function closePanel(){
    panel.classList.remove('open');
    panel.setAttribute('aria-hidden','true');
  }
  function togglePanel(){
    if(panel.classList.contains('open')) closePanel();
    else openPanel();
  }

  fab.addEventListener('click', togglePanel);
  closeBtn.addEventListener('click', closePanel);

  document.addEventListener('keydown', (e)=>{
    if(e.key === 'Escape') closePanel();
  });

  // click-outside to close (but ignore clicks on fab/panel)
  document.addEventListener('click', (e)=>{
    if(!panel.classList.contains('open')) return;
    const t = e.target;
    if(panel.contains(t) || fab.contains(t)) return;
    closePanel();
  }, true);

  function escapeHtml(s){
    return (s||'').replaceAll('&','&amp;').replaceAll('<','&lt;').replaceAll('>','&gt;');
  }
  function appendMsg(kind, html){
    const wrap = document.createElement('div');
    wrap.className = 'icare-msg ' + kind;
    const bubble = document.createElement('div');
    bubble.className = 'icare-bubble';
    bubble.innerHTML = html;
    wrap.appendChild(bubble);
    body.appendChild(wrap);
    body.scrollTop = body.scrollHeight;
  }
  function showTyping(){
    const t = document.createElement('div');
    t.className = 'icare-typing';
    t.id = 'icareTyping';
    t.textContent = 'Typing…';
    body.appendChild(t);
    body.scrollTop = body.scrollHeight;
  }
  function hideTyping(){
    const t = document.getElementById('icareTyping');
    if(t) t.remove();
  }

  // keep a small session transcript (UX polish)
  function saveTranscript(){
    try{
      const items = [];
      body.querySelectorAll('.icare-msg').forEach(el=>{
        items.push({k: el.classList.contains('user') ? 'u':'b', h: el.querySelector('.icare-bubble')?.innerHTML || ''});
      });
      localStorage.setItem('icare_chat_transcript', JSON.stringify(items).slice(0, 8000));
    }catch(e){}
  }
  function loadTranscript(){
    try{
      const raw = localStorage.getItem('icare_chat_transcript');
      if(!raw) return;
      const items = JSON.parse(raw);
      // remove default bot hello + help card (first two nodes)
      // and rebuild transcript cleanly
      body.innerHTML = '';
      items.forEach(it=>{
        const kind = it.k === 'u' ? 'user' : 'bot';
        appendMsg(kind, it.h);
      });
      body.scrollTop = body.scrollHeight;
    }catch(e){}
  }
  // load only if not empty and looks valid
  loadTranscript();

  form.addEventListener('submit', (e)=>{
    e.preventDefault();
    const text = (input.value||'').trim();
    if(!text) return;
    appendMsg('user', escapeHtml(text));
    input.value = '';
    showTyping();

    // bot-style reply (front-end only) with clear next steps
    setTimeout(()=>{
      hideTyping();
      appendMsg('bot',
        '<div class="icare-msg-name">Support Bot</div>' +
        'Thanks! If this is urgent, use <b>WhatsApp</b> for fastest response. ' +
        'For detailed tracking, please open a <b>Support Ticket</b>.'
      );
      saveTranscript();
    }, 650);

    saveTranscript();
  });

  // optional: auto-open once per session on first visit (keeps it friendly, not annoying)
  try{
    const key = 'icare_chat_seen';
    if(!sessionStorage.getItem(key)){
      sessionStorage.setItem(key,'1');
      // do not auto-open on very small screens
      if(window.innerWidth > 420){
        setTimeout(()=>{}, 10);
      }
    }
  }catch(e){}

  // Lift chat widget when footer enters view (prevents overlap with footer install)
  try{
    const footerEl = document.querySelector('footer.footer');
    if(footerEl && 'IntersectionObserver' in window){
      const io = new IntersectionObserver((entries)=>{
        const isVis = entries && entries[0] && entries[0].isIntersecting;
        if(isVis){ fab.classList.add('lift'); panel.classList.add('lift'); }
        else { fab.classList.remove('lift'); panel.classList.remove('lift'); }
      }, { root:null, threshold:0.02 });
      io.observe(footerEl);
    }
  }catch(e){}

})();
</script>

</body>
</html>
