/* global React */
/* Pausa FAQ chat — hybrid assistant.
   • When a built-in model is available (window.claude.complete, e.g. in preview),
     it answers conversationally, grounded ONLY on the FAQ knowledge base below.
   • Otherwise (e.g. the deployed site) it falls back to keyword-matching the
     curated answers, so it always stays accurate and never invents facts.
   Source copy: FAQ_LLM_ANSWERS.md (warm, pop-up-ready answers). */
const { useState, useRef, useEffect } = React;

const PAUSA_QA = [
  { g: "Outcomes", q: "How is success measured?", a: "We measure at two levels. For each leader: pre- and post-program scores across the four dimensions of wellbeing — Physical, Mental, Emotional, and Purpose & Values — via the Pausa Vitality Check. For the organisation: psychosocial risk documentation aligned with ESRS S1 (CSRD) and ISO 45003. The real outcome isn't just how people feel — it's decision quality, less invisible depletion, and measurable shifts in team cohesion. Where biomarker testing is included, we track objective markers before and after." },
  { g: "Outcomes", q: "What outcomes should we expect after 12 months?", a: "The most consistent shifts: clearer thinking under pressure, less friction inside the leadership team, and a shared language for wellbeing that makes it discussable rather than avoided. You also leave with a documented wellbeing baseline your People team can use for ESRS S1 reporting. We won't promise exact individual numbers — outcomes depend on engagement — but teams that complete the full 12-month arc improve measurably across all four dimensions." },
  { g: "Outcomes", q: "How do you measure impact for our board or investors?", a: "You leave with three board-ready, audit-ready things: team-aggregate pre/post Vitality Check scores, an ESRS S1-aligned psychosocial risk package, and a record of behavioural commitments and completion rates. If you need an internal ROI case, we help you frame it in the language your CFO responds to — risk mitigation, retention, decision quality — not just wellbeing scores." },
  { g: "Science", q: "How much of the program is evidence-based versus experiential?", a: "The foundation is entirely science-based: the Pausa Method integrates neuroscience, behavioural science, and evidence-based wellbeing research, aligned with WHO and World Psychiatric Association frameworks, the U.S. Surgeon General's Framework for Workplace Mental Health, and ISO 45003. The Sprint has no experiential elements — it's a structured facilitated session with documented outputs. The Reset includes experiential components (nature, movement, food, silence), but each is part of a protocol, not decoration. We're always happy to say what's validated and what's exploratory." },
  { g: "Science", q: "What methodology guides the program design?", a: "The Pausa Method draws on three disciplines: neuroscience, behavioural science, and evidence-based wellbeing research. The diagnostic layer is the Pausa Vitality Check — a 30-item team assessment across four dimensions. The intervention layer uses structured behavioural design: finding the smallest adjustment most likely to shift someone's wellbeing under their real working conditions. The integration layer (Pausa Circle) is built around the WHO and WPA's five core lifestyle pillars." },
  { g: "Biomarkers", q: "Which biomarkers are included?", a: "The Pausa Lab panel covers 100+ clinical markers across 11 body systems: haematology, cardiovascular, liver & digestion, immunity & inflammation, metabolism & endocrinology, musculoskeletal, nervous system & stress, kidneys, hormonal, thyroid, and a wearables overlay. Samples are processed through certified clinical labs. Results arrive within 5 working days and are reviewed by a clinician before they reach you — in plain language, not raw lab notation." },
  { g: "Biomarkers", q: "How personalized is the biomarker component?", a: "Each participant gets a results consultation to walk through their specific markers, understand normal versus optimal for performance, and translate findings into behavioural adjustments. The report is individual and confidential — no raw data is shared with the organisation. Where a marker warrants medical attention, we refer participants to appropriate specialists." },
  { g: "Biomarkers", q: "How do you separate individual biomarker data from corporate reporting?", a: "Biomarker results stay strictly between the participant and Pausa — the organisation never sees individual health data. What the organisation receives is anonymized team-aggregate wellbeing data from the Vitality Check, not from medical tests. It's a structural separation, not just a policy statement, and participants are told about this boundary before the program starts." },
  { g: "Facilitation", q: "Who facilitates the Pausa experience?", a: "Specialists with backgrounds in behavioural design, performance wellbeing, and applied psychology — with specific experience working with founders and executives, not generic corporate audiences. We don't use wellness generalists. Biomarker results are reviewed and explained by clinicians, and we bring in additional specialists for unusual organisational complexity. The facilitator background is always disclosed before the program begins." },
  { g: "Facilitation", q: "How do you handle team members who are skeptical?", a: "We design for skepticism. The Sprint opens with data — individual Vitality Check scores — not mindfulness or group sharing. Nothing requires you to engage with anything that feels 'soft.' It's behavioural design and physiological measurement, so it speaks to people who respond to evidence. A pre-program orientation call is available for anyone who wants to understand the method first. One honest skeptic often becomes the most engaged participant." },
  { g: "What's next", q: "What happens after the retreat?", a: "The Reset is the beginning, not the product. Afterwards, participants join the Pausa Circle — a 12-month integration program of monthly offline touchpoints and quarterly anchor sessions, where the commitments made during the retreat get tested, adjusted, and sustained. It's structured around the WHO and WPA's five lifestyle pillars. Most of the measurable change happens in months 2–12, not during the retreat itself." },
  { g: "What's next", q: "What does the Pausa Circle look like for a corporate team?", a: "For B2B engagements, the Circle can be a private cohort (your team only, with a dedicated facilitator loop) or integration into a broader mixed-company cohort where leaders benefit from peer diversity. Most corporate clients choose the private format in year one. Format and cadence are agreed on the discovery call and can be adjusted after the first quarter." },
  { g: "What's next", q: "What happens concretely in months 2 to 12?", a: "Monthly: a structured 90-minute offline touchpoint — part check-in, part peer accountability, part behavioural recalibration. Quarterly: a half-day anchor session, in person or facilitated remotely. At 12 months: a repeat Vitality Check to measure the delta across all four dimensions. Between sessions: behavioural commitment tracking via the Pausa platform. Your internal sponsor receives a quarterly progress summary." },
  { g: "Fit & logistics", q: "Who else is in the room?", a: "Sprint cohorts are from a single organisation (8–12 participants) — your leadership team, no external mixing. Reset cohorts are curated across companies: founders, executives, and senior leaders at a comparable stage of professional intensity. We screen for readiness, not seniority. Pausa Open, our community event, brings together ~30 founders and executives in a non-commercial format." },
  { g: "Fit & logistics", q: "What is the total time commitment per year?", a: "Sprint-only: one full day. Sprint + Reset: one full day plus three days (including travel to the retreat near Lisbon). Sprint + Reset + Circle: add roughly 2–3 hours per month. A full-year engagement is about 8–10 days of active participation — concentrated at the start, lighter through the year. If freeing your team for three consecutive days feels impossible, that's worth discussing — it's often a signal, not a barrier." },
  { g: "Fit & logistics", q: "How do you tailor the program for founders versus corporate leadership?", a: "The science is the same; the lens shifts. Founder cohorts go deeper on Purpose & Values and physical health — the dimensions most depleted by early-stage building. Corporate leadership cohorts spend more time on team dynamics and the collective wellbeing map, because there the system matters as much as the individual. The Vitality Check adapts its emphasis, the facilitator frames questions differently, and the outputs look different." },
  { g: "Fit & logistics", q: "What level of internal sponsorship do you need?", a: "One internal person to own logistics and internal comms — usually a People Lead, HR Director, or Chief of Staff. We don't need a dedicated project manager; we handle design, facilitation, measurement, and documentation. From your side: the ability to get the right people in the room, a clear brief on what success looks like, and a sponsor willing to participate themselves. Leaders who go first get the best outcomes from their teams." },
  { g: "Fit & logistics", q: "What types of teams are not a good fit for Pausa?", a: "Four clear cases: teams in active operational crisis where no one can be offline for a day (the timing is wrong, not the program); organisations that see wellbeing as a perk rather than a performance input; teams wanting a one-off motivational talk or luxury offsite with no intent to change behaviour; and individuals needing clinical mental health support — we refer those to professionals and don't position Pausa as therapy or medical treatment. We decline work where the fit isn't right." },
];

const KB_TEXT = PAUSA_QA.map((x) => "Q: " + x.q + "\nA: " + x.a).join("\n\n");

const CHAT_INSTRUCTIONS =
  "You are Pausa's friendly website assistant. Pausa is a performance-wellbeing company for founders and leadership teams: a full-body biomarker baseline, immersive nature resets near Lisbon, and a 12-month integration Circle, with wearables and weekly check-ins adding a continuous layer — building a system of record for human performance. " +
  "Answer the leader's question in a warm, conversational, human tone — like a knowledgeable host, not a brochure. Keep it to 2–4 sentences. " +
  "Use ONLY facts from the knowledge base below. If the question isn't covered there, say honestly that you're not certain and gently suggest booking a discovery call. " +
  "Never invent numbers, claims, or policies. Never name third-party partners or suppliers. Do not use markdown headings, bullet points, or asterisks — just natural sentences.";

const STARTER_QUESTIONS = [
  "How is success measured?",
  "Which biomarkers are included?",
  "What happens after the retreat?",
  "What's the total time commitment?",
  "Who isn't a good fit for Pausa?",
];

function curatedAnswer(q) {
  const words = (q.toLowerCase().match(/[a-z]{3,}/g) || []);
  const stop = { the: 1, and: 1, for: 1, are: 1, you: 1, our: 1, how: 1, what: 1, does: 1, with: 1, that: 1, this: 1, your: 1 };
  let best = null, score = 0;
  for (const item of PAUSA_QA) {
    const hay = (item.q + " " + item.q + " " + item.a).toLowerCase();
    let s = 0;
    for (const w of words) { if (stop[w]) continue; if (hay.indexOf(w) !== -1) s++; }
    if (s > score) { score = s; best = item; }
  }
  if (best && score >= 2) return best.a;
  return "I'm not certain about that one, and I'd rather not guess. The quickest way to a precise answer is a short discovery call — or ask me about outcomes & measurement, the science, biomarker testing, facilitation, the 12-month Circle, or whether your team is a fit.";
}

async function getAnswer(question, history) {
  if (window.claude && typeof window.claude.complete === "function") {
    try {
      const convo = history
        .filter((m) => m.role === "user" || m.role === "assistant")
        .slice(-6)
        .map((m) => (m.role === "user" ? "Leader: " : "Pausa: ") + m.text)
        .join("\n");
      const prompt =
        CHAT_INSTRUCTIONS +
        "\n\nKNOWLEDGE BASE:\n" + KB_TEXT +
        "\n\nConversation so far:\n" + (convo || "(none yet)") +
        "\n\nLeader's question: " + question +
        "\n\nWrite Pausa's reply now:";
      const txt = await window.claude.complete(prompt);
      if (txt && txt.trim()) return txt.trim();
    } catch (e) { /* fall through to curated */ }
  }
  return curatedAnswer(question);
}

function SendIcon() {
  return (
    <svg viewBox="0 0 16 16" width="16" height="16" fill="currentColor" aria-hidden="true">
      <path d="M14.082 2.182a.5.5 0 0 1 .103.557L8.528 15.467a.5.5 0 0 1-.917-.007L5.57 10.694.803 8.652a.5.5 0 0 1-.006-.916l12.728-5.657a.5.5 0 0 1 .556.103z" />
    </svg>
  );
}

function nowHM() {
  const d = new Date();
  return String(d.getHours()).padStart(2, "0") + ":" + String(d.getMinutes()).padStart(2, "0");
}

function ChatCore({ nudge }) {
  const [messages, setMessages] = useState([
    { role: "assistant", text: "Hi — I'm Pausa's assistant. Ask me anything about how the programme works: outcomes, the science, biomarker testing, what happens after the retreat, or whether it's a fit for your team.", time: nowHM() },
  ]);
  const [input, setInput] = useState("");
  const [busy, setBusy] = useState(false);
  const scrollRef = useRef(null);
  const endRef = useRef(null);

  const askedOnce = messages.some((m) => m.role === "user");

  useEffect(() => {
    const el = scrollRef.current;
    if (el) el.scrollTop = el.scrollHeight;
  }, [messages, busy]);

  async function submit(q) {
    const question = (q || "").trim();
    if (!question || busy) return;
    setInput("");
    setMessages((m) => m.concat({ role: "user", text: question, time: nowHM() }));
    setBusy(true);
    const history = messages.concat({ role: "user", text: question });
    const text = await getAnswer(question, history);
    setMessages((m) => m.concat({ role: "assistant", text: text, cta: nudge, time: nowHM() }));
    setBusy(false);
  }

  // Allow other parts of the page (e.g. the floating question chips) to ask.
  useEffect(() => {
    window.pausaAsk = (q) => submit(q);
    return () => { if (window.pausaAsk) delete window.pausaAsk; };
  }, [messages, busy, nudge]);

  // Pick up a question queued before this chat instance mounted (floating mode).
  useEffect(() => {
    if (window.__pausaPendingQ) {
      const q = window.__pausaPendingQ;
      window.__pausaPendingQ = null;
      submit(q);
    }
    // eslint-disable-next-line
  }, []);

  return (
    <div className="chat">
      <div className="chat-log" ref={scrollRef}>
        {messages.map((m, i) => (
          <div key={i} className={"chat-msg " + m.role}>
            <span className={"chat-ava sm" + (m.role === "user" ? " user" : "")} aria-hidden="true">{m.role === "user" ? "You" : "P"}</span>
            <div className="chat-msg-body">
              <div className="chat-bubble">
                <p>{m.text}</p>
                {m.cta ? (
                  <button type="button" className="chat-book" onClick={() => window.__pausaBook && window.__pausaBook()}>
                    Book a discovery call
                    <span className="chat-book-arrow" aria-hidden="true">→</span>
                  </button>
                ) : null}
              </div>
              {m.time ? <time className="chat-time">{m.time}</time> : null}
            </div>
          </div>
        ))}
        {busy ? (
          <div className="chat-msg assistant">
            <span className="chat-ava sm" aria-hidden="true">P</span>
            <div className="chat-msg-body">
              <div className="chat-bubble"><span className="chat-typing"><i></i><i></i><i></i></span></div>
            </div>
          </div>
        ) : null}
        <div ref={endRef}></div>
      </div>

      {!askedOnce ? (
        <div className="chat-chips">
          {STARTER_QUESTIONS.map((q) => (
            <button type="button" key={q} className="chat-chip" onClick={() => submit(q)}>{q}</button>
          ))}
        </div>
      ) : null}

      <form className="chat-input" onSubmit={(e) => { e.preventDefault(); submit(input); }}>
        <input
          type="text"
          value={input}
          onChange={(e) => setInput(e.target.value)}
          placeholder="Ask about Pausa…"
          aria-label="Ask the Pausa assistant a question"
        />
        <button type="submit" className="chat-send" disabled={busy || !input.trim()} aria-label="Send">
          <SendIcon />
        </button>
      </form>
    </div>
  );
}

/* Inline panel — messaging-conversation styled card */
function PausaChatInline({ nudge }) {
  return (
    <div className="chat-inline">
      <div className="chat-head">
        <span className="chat-ava" aria-hidden="true">P</span>
        <div className="chat-head-meta">
          <div className="chat-head-name">Pausa Assistant</div>
          <div className="chat-head-status"><span className="chat-status-dot"></span> Online · replies instantly</div>
        </div>
      </div>
      <ChatCore nudge={nudge} />
    </div>
  );
}

/* Floating launcher + popover */
function PausaChatFloating({ nudge }) {
  const [open, setOpen] = useState(false);
  useEffect(() => {
    const prev = window.pausaAsk;
    window.pausaOpenChat = () => setOpen(true);
    return () => { delete window.pausaOpenChat; };
  }, []);
  return (
    <div className={"chat-fab-wrap" + (open ? " open" : "")}>
      {open ? (
        <div className="chat-pop" role="dialog" aria-label="Pausa assistant">
          <div className="chat-pop-head">
            <span className="chat-pop-title"><span className="chat-ava sm" aria-hidden="true">P</span> Ask Pausa</span>
            <button type="button" className="chat-pop-close" onClick={() => setOpen(false)} aria-label="Close chat">×</button>
          </div>
          <ChatCore nudge={nudge} />
        </div>
      ) : null}
      <button type="button" className="chat-fab" onClick={() => setOpen((o) => !o)} aria-label={open ? "Close chat" : "Open chat"}>
        {open ? "×" : (
          <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="1.7" aria-hidden="true">
            <path d="M21 11.5a8.38 8.38 0 0 1-8.5 8.5 8.5 8.5 0 0 1-3.8-.9L3 21l1.9-5.7A8.38 8.38 0 0 1 4 11.5 8.5 8.5 0 0 1 12.5 3 8.38 8.38 0 0 1 21 11.5z" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
        )}
      </button>
    </div>
  );
}

Object.assign(window, { PausaChatInline, PausaChatFloating, PAUSA_QA });
