// WorkerBee.jsx — scripted "Bee" guided chat that replaces the CTA form.
// Inline preview in the CTA → expands to a full-screen takeover the instant Q1 is
// answered (logo top-left + Step 1–4 rail) → can be minimized to a Bee FAB with an
// unread dot. All scripted; the real concept work is handled downstream by the studio.

var useState = React.useState, useEffect = React.useEffect, useRef = React.useRef;

const WB_INTRO = "Hi, I'm Bee. I can help you sort what your site needs first — what to build, what is slowing it down, and the next useful step.";
const WB_CLOSING_TITLE = "Perfect — that's everything I need.";
const WB_CLOSING_BODY = "I'm handing this to the Siteworks studio to put together a homepage prototype direction, the honest first opportunities, and what we'd build first. We'll be in touch shortly.";

const WB_QUESTIONS = {
  q1: {
    step: 1, multi: true,
    prompt: "What do you need built?",
    hint: "You can select multiple.",
    opts: ["Marketing site", "Shopify store", "B2B / SaaS site", "Full rebuild", "Landing pages", "Not sure yet", "Other"],
    other: "Other",
    otherPlaceholder: "Tell me what you have in mind…",
  },
  q2: {
    step: 2, multi: false,
    prompt: "Where's your site today?",
    hint: "Select one.",
    opts: ["No site yet", "DIY builder (Wix, Squarespace)", "WordPress", "Custom / agency build", "Shopify", "Outdated, needs a refresh", "Other"],
    other: "Other",
    otherPlaceholder: "Tell me about your current site…",
  },
  q3: {
    step: 3, multi: true,
    prompt: "What's the #1 thing the new site should do?",
    hint: "You can select multiple.",
    opts: ["Win more inquiries", "Look more premium", "Explain a complex offer", "Sell products", "Be faster on mobile", "Be easy for us to edit"],
  },
};
const WB_STEPS = [
  { n: 1, label: "What you need", sub: "Project type" },
  { n: 2, label: "Where you are", sub: "Current site" },
  { n: 3, label: "Your goals", sub: "What matters" },
  { n: 4, label: "Concept", sub: "We design it" },
];

let __wbId = 0;
const wbId = () => ++__wbId;

// --- orbit "Bee" mark ---
function BeeIcon({ size = 22 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 32 32" fill="none" aria-hidden="true">
      <defs>
        <linearGradient id="wbBeeG" x1="0" y1="0" x2="1" y2="1">
          <stop offset="0%" stopColor="#FFB78C" />
          <stop offset="55%" stopColor="#F26422" />
          <stop offset="100%" stopColor="#8C4FE0" />
        </linearGradient>
      </defs>
      {/* orbit ring */}
      <circle cx="16" cy="16" r="9.5" stroke="url(#wbBeeG)" strokeWidth="2.2" />
      {/* horizontal flare across the ring */}
      <path d="M3.5 16.6 H28.5" stroke="#FF9A63" strokeWidth="1.5" strokeLinecap="round" opacity="0.9" />
      {/* bright core */}
      <circle cx="16" cy="16" r="2.6" fill="#FFE3CF" />
      <circle cx="16" cy="16" r="1.4" fill="#fff" />
    </svg>
  );
}

function WBAvatar() {
  return <span className="wb-avatar" aria-hidden="true"><BeeIcon size={20} /></span>;
}

function WBTyping() {
  return (
    <div className="wb-row bee">
      <WBAvatar />
      <div className="wb-bubble bee wb-typing"><span /><span /><span /></div>
    </div>
  );
}

function WBMessage({ m }) {
  if (m.from === "bee") {
    return (
      <div className="wb-row bee">
        <WBAvatar />
        <div className={"wb-bubble bee" + (m.closing ? " closing" : "")}>
          {m.closing ? (
            <React.Fragment>
              <span className="wb-close-chk"><i className="ri-check-line" /></span>
              <div className="wb-close-title">{WB_CLOSING_TITLE}</div>
              <div className="wb-close-body">{WB_CLOSING_BODY}</div>
            </React.Fragment>
          ) : (
            <React.Fragment>
              <span className="wb-bubble-text">{m.text}</span>
              {m.hint && <span className="wb-hint">{m.hint}</span>}
            </React.Fragment>
          )}
        </div>
      </div>
    );
  }
  return (
    <div className="wb-row user">
      <div className="wb-bubble user">
        {m.chips && m.chips.map((c) => <span key={c} className="wb-answer-chip">{c}</span>)}
        {m.note && <span className="wb-answer-note">{m.note}</span>}
      </div>
    </div>
  );
}

// the interactive answer composer for the currently-awaited question
function WBComposer({ qKey, onSubmit }) {
  const q = WB_QUESTIONS[qKey];
  const [sel, setSel] = useState(q.multi ? [] : "");
  const [otherText, setOtherText] = useState("");
  const [detailText, setDetailText] = useState("");
  const [err, setErr] = useState(false);

  const has = (o) => (q.multi ? sel.includes(o) : sel === o);
  const toggle = (o) => {
    setErr(false);
    if (q.multi) setSel((s) => (s.includes(o) ? s.filter((x) => x !== o) : [...s, o]));
    else setSel((s) => (s === o ? "" : o));
  };

  const chosen = q.multi ? sel : (sel ? [sel] : []);
  const needsOther = q.other && chosen.includes(q.other);
  const needsDetail = q.detail && chosen.includes(q.detail);
  const canSend = chosen.length > 0 && (!needsOther || otherText.trim()) && (!needsDetail || detailText.trim());

  const send = () => {
    if (!canSend) { setErr(true); return; }
    const chips = chosen.map((c) => (c === q.other && otherText.trim() ? `Other: ${otherText.trim()}` : c));
    let note = "";
    if (needsDetail && detailText.trim()) note = detailText.trim();
    onSubmit({ chips, note, raw: { sel: chosen, otherText: otherText.trim(), detailText: detailText.trim() } });
  };

  return (
    <div className="wb-composer">
      <div className="wb-chips">
        {q.opts.map((o) => (
          <button type="button" key={o} className={"wb-chip" + (has(o) ? " sel" : "")} onClick={() => toggle(o)}>
            {has(o) && <i className="ri-check-line wb-chip-chk" />}{o}
          </button>
        ))}
      </div>
      {needsOther && (
        <input className="wb-text" autoFocus placeholder={q.otherPlaceholder} value={otherText}
          onChange={(e) => { setOtherText(e.target.value); setErr(false); }}
          onKeyDown={(e) => { if (e.key === "Enter") send(); }} />
      )}
      {needsDetail && (
        <input className="wb-text" autoFocus placeholder={q.detailPlaceholder} value={detailText}
          onChange={(e) => { setDetailText(e.target.value); setErr(false); }}
          onKeyDown={(e) => { if (e.key === "Enter") send(); }} />
      )}
      <div className="wb-composer-foot">
        <span className={"wb-err" + (err ? " show" : "")}><i className="ri-information-line" /> Pick at least one to continue.</span>
        <button type="button" className="btn btn-primary wb-continue" style={canSend ? undefined : { opacity: 0.5 }} onClick={send}>
          Continue <i className="ri-arrow-right-line" />
        </button>
      </div>
    </div>
  );
}

function WorkerBee() {
  const [feed, setFeed] = useState([]);
  const [awaiting, setAwaiting] = useState(null);     // 'q1' | 'q2' | 'q3' | null
  const [typing, setTyping] = useState(false);
  const [step, setStep] = useState(1);                // 1..4 for the rail
  const [started, setStarted] = useState(false);      // answered Q1
  const [expanded, setExpanded] = useState(false);    // full-screen takeover
  const [unread, setUnread] = useState(false);        // dot on the FAB
  const [isMobile, setIsMobile] = useState(false);    // FAB-only chat widget on phones
  const started_ref = useRef(false);
  const feedEndRef = useRef(null);
  const overlayFeedRef = useRef(null);
  const inlineRef = useRef(null);
  const mounted = useRef(false);
  const timers = useRef([]);
  const at = (ms, fn) => { const t = setTimeout(fn, ms); timers.current.push(t); return t; };

  // kick off ONLY when the inline card scrolls into view — like Worker Bee noticing
  // the visitor arrive — then the intro and Q1 stream in one at a time.
  const kickoff = () => {
    if (mounted.current) return;
    mounted.current = true;
    setFeed([{ id: wbId(), from: "bee", text: WB_INTRO }]);
    setTyping(true);
    at(1300, () => {
      setTyping(false);
      setFeed((f) => [...f, { id: wbId(), from: "bee", text: WB_QUESTIONS.q1.prompt, hint: WB_QUESTIONS.q1.hint }]);
      setAwaiting("q1");
    });
  };
  // track viewport so the bee collapses to a chat-widget FAB on phones
  useEffect(() => {
    const mq = window.matchMedia("(max-width: 760px)");
    const sync = () => setIsMobile(mq.matches);
    sync();
    mq.addEventListener ? mq.addEventListener("change", sync) : mq.addListener(sync);
    return () => { mq.removeEventListener ? mq.removeEventListener("change", sync) : mq.removeListener(sync); };
  }, []);

  useEffect(() => {
    const el = inlineRef.current;
    if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) { kickoff(); io.disconnect(); } });
    }, { threshold: 0.4 });
    io.observe(el);
    return () => { io.disconnect(); timers.current.forEach(clearTimeout); };
  }, []);

  // autoscroll feeds on new content
  useEffect(() => {
    if (feedEndRef.current) feedEndRef.current.scrollTop = feedEndRef.current.scrollHeight;
    if (overlayFeedRef.current) overlayFeedRef.current.scrollTop = overlayFeedRef.current.scrollHeight;
  }, [feed, typing, awaiting]);

  // lock page scroll + hide site nav while the takeover is open
  useEffect(() => {
    document.body.style.overflow = expanded ? "hidden" : "";
    document.body.classList.toggle("wb-takeover", expanded);
    return () => { document.body.style.overflow = ""; document.body.classList.remove("wb-takeover"); };
  }, [expanded]);

  const askNext = (qKey, delay) => {
    setTyping(true);
    at(delay || 900, () => {
      setTyping(false);
      const q = WB_QUESTIONS[qKey];
      setFeed((f) => [...f, { id: wbId(), from: "bee", text: q.prompt, hint: q.hint }]);
      setAwaiting(qKey);
      setStep(q.step);
      if (!expanded) setUnread(true);
    });
  };

  const finish = (delay) => {
    setTyping(true);
    at(delay || 1000, () => {
      setTyping(false);
      setFeed((f) => [...f, { id: wbId(), from: "bee", closing: true }]);
      setStep(4);
      if (!expanded) setUnread(true);
    });
  };

  const handleSubmit = (qKey, payload) => {
    setFeed((f) => [...f, { id: wbId(), from: "user", chips: payload.chips, note: payload.note }]);
    setAwaiting(null);
    if (qKey === "q1") {
      started_ref.current = true;
      setStarted(true);
      setExpanded(true);
      setUnread(false);
      askNext("q2", 950);
    } else if (qKey === "q2") {
      askNext("q3", 950);
    } else if (qKey === "q3") {
      finish(1050);
    }
  };

  const openChat = () => { kickoff(); setExpanded(true); setUnread(false); };
  const closeChat = () => { setExpanded(false); setUnread(true); };

  // ----- conversation body (shared by inline + overlay) -----
  const Conversation = ({ scrollRef, variant }) => (
    <div className={"wb-feed " + variant} ref={scrollRef}>
      {feed.map((m) => <WBMessage key={m.id} m={m} />)}
      {typing && <WBTyping />}
      {awaiting && !typing && <WBComposer key={awaiting} qKey={awaiting} onSubmit={(p) => handleSubmit(awaiting, p)} />}
      {variant === "overlay" && <div style={{ height: 4 }} />}
    </div>
  );

  // ----- inline card (lives in the CTA) -----
  const inline = !started ? (
    <div className="wb-inline" ref={inlineRef}>
      <div className="wb-inline-head">
        <span className="wb-brandmark"><BeeIcon size={22} /></span>
        <div className="wb-headline">Shape your homepage prototype</div>
      </div>
      <Conversation scrollRef={feedEndRef} variant="inline" />
    </div>
  ) : (
    <div className="wb-inline wb-inline--open">
      <span className="wb-brandmark lg"><BeeIcon size={26} /></span>
      <div className="wb-resume-title">Your homepage prototype session is open</div>
      <div className="wb-resume-sub">Pick up right where you left off — {step >= 4 ? "all set" : `step ${step} of 4`}.</div>
      <button type="button" className="btn btn-primary" onClick={openChat}>Resume conversation <i className="ri-arrow-right-up-line" /></button>
    </div>
  );

  // ----- full-screen takeover + FAB (portaled to <body> so its z-index sits above
  // the site nav and isn't trapped in a section's stacking context) -----
  const portal = ReactDOM.createPortal(
    <React.Fragment>
      <div className={"wb-overlay" + (expanded ? " show" : "")} aria-hidden={!expanded}>
        <div className="wb-overlay-haze" aria-hidden="true" />
        <div className="wb-topbar">
          <Logo height={24} />
          <div className="wb-top-actions">
            <button type="button" className="wb-icon-btn" title="Minimize" onClick={closeChat}><i className="ri-subtract-line" /></button>
            <button type="button" className="wb-icon-btn" title="Close" onClick={closeChat}><i className="ri-close-line" /></button>
          </div>
        </div>
        <div className="wb-stage">
          <aside className="wb-rail">
            {WB_STEPS.map((s) => (
              <div key={s.n} className={"wb-step " + (step === s.n ? "active" : step > s.n ? "done" : "")}>
                <span className="wb-step-dot">{step > s.n ? <i className="ri-check-line" /> : s.n}</span>
                <div className="wb-step-text">
                  <span className="wb-step-label">{s.label}</span>
                  <span className="wb-step-sub">{s.sub}</span>
                </div>
              </div>
            ))}
          </aside>
          <main className="wb-main">
            <div className="wb-main-head">
              <span className="wb-brandmark"><BeeIcon size={22} /></span>
              <div className="wb-headline">Shape your homepage prototype</div>
            </div>
            <Conversation scrollRef={overlayFeedRef} variant="overlay" />
          </main>
        </div>
      </div>

      {((isMobile || started) && !expanded) && (
        <div className="wb-fab-wrap">
          {isMobile && !started && (
            <span className="wb-fab-label">Build your site concept</span>
          )}
          <button type="button" className="wb-fab" onClick={openChat} title={started ? "Resume Bee" : "Build your site concept"}>
            <BeeIcon size={26} />
            {(unread || (isMobile && !started)) && <span className="wb-fab-dot">1</span>}
          </button>
        </div>
      )}
    </React.Fragment>,
    document.body
  );

  return <React.Fragment>{inline}{portal}</React.Fragment>;
}

Object.assign(window, { WorkerBee, BeeIcon });
