// Help / FAQ + Profile + Chat widget + Tour
const { Button: BtnD, Info: InfoD, Ic: IcD } = window.UI;

function HelpScreen({ t, lang, onChat, onTour }) {
  const [openIdx, setOpenIdx] = React.useState(0);
  return (
    <div className="main">
      <div className="page-head">
        <div>
          <h1 className="page-title">{t.help.title_a} <em>{t.help.title_b}</em></h1>
          <p className="page-sub">{t.help.sub}</p>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 300px", gap: 32, alignItems: "start" }}>
        <div className="card" style={{ padding: "8px 24px" }}>
          {t.help.faq.map((f, i) => (
            <div className="faq-item" key={i} data-open={openIdx === i}>
              <button className="faq-q" onClick={() => setOpenIdx(openIdx === i ? -1 : i)}>
                <span>{f.q}</span>
                <span className="faq-chev"><IcD.chev /></span>
              </button>
              {openIdx === i && <div className="faq-a">{f.a}</div>}
            </div>
          ))}
        </div>

        <div className="col">
          <div className="card" style={{ background: "var(--accent)", color: "var(--accent-ink)", borderColor: "var(--accent)" }}>
            <h3 style={{ margin: 0, fontFamily: "var(--font-serif)", fontWeight: 400, fontSize: 22, letterSpacing: "-0.01em" }}>
              {t.help.contact_title}
            </h3>
            <button className="btn" data-block="true" style={{ background: "var(--accent-ink)", color: "var(--accent)", borderColor: "var(--accent-ink)" }} onClick={onChat}>
              <IcD.chat /> {t.help.contact_chat}
            </button>
            <div style={{ marginTop: 12, fontSize: 12.5, color: "rgba(255,255,255,0.7)", display: "flex", alignItems: "center", gap: 6 }}>
              <IcD.mail /> {t.help.contact_mail}
            </div>
          </div>

          <div className="card">
            <h3 style={{ margin: 0, fontSize: 14, fontWeight: 500 }}>
              {lang === "it" ? "Tour guidato" : "Guided tour"}
            </h3>
            <p style={{ margin: "6px 0 14px", color: "var(--ink-soft)", fontSize: 12.5 }}>
              {lang === "it" ? "Rivedi i passi principali per usare Bolton Transfer." : "Replay the key steps to use Bolton Transfer."}
            </p>
            <BtnD size="sm" icon={<IcD.sparkle />} onClick={onTour}>
              {lang === "it" ? "Avvia il tour" : "Start the tour"}
            </BtnD>
          </div>
        </div>
      </div>
    </div>
  );
}

function ProfileScreen({ t, lang, onLogout }) {
  return (
    <div className="main">
      <div className="page-head">
        <div>
          <h1 className="page-title">{t.profile.title_a} <em>{t.profile.title_b}</em>.</h1>
          <p className="page-sub">
            {lang === "it"
              ? "Account aziendale Bolton condiviso con il team Dugongo."
              : "Bolton company account shared with the Dugongo team."}
          </p>
        </div>
      </div>
      <div className="profile-compact">
        <div className="row" style={{ gap: 16, alignItems: "center" }}>
          <div className="av-lg">B</div>
          <div style={{ flex: 1 }}>
            <div style={{ fontWeight: 500, fontSize: 16 }}>{lang === "it" ? "Account Bolton" : "Bolton account"}</div>
            <div className="muted" style={{ fontSize: 13 }}>bolton@dugongo.it</div>
          </div>
          <BtnD variant="ghost" icon={<IcD.x />} onClick={onLogout}>{t.profile.logout}</BtnD>
        </div>
        <hr className="hr" />
        <div style={{ display: "flex", justifyContent: "flex-end", gap: 8 }}>
          <BtnD variant="ghost">{t.common.cancel}</BtnD>
          <BtnD variant="primary">{t.profile.save}</BtnD>
        </div>
      </div>
    </div>
  );
}

/* ---------- Chat widget (real-time SSE) ---------- */
function ChatWidget({ t, lang, open, setOpen }) {
  const [msgs, setMsgs]     = React.useState([]);
  const [draft, setDraft]   = React.useState("");
  const [unread, setUnread] = React.useState(false);
  const bottomRef = React.useRef(null);

  React.useEffect(() => {
    const token = localStorage.getItem("bt_token");
    if (!token) return;
    fetch("/api/chat/messages", { headers: { Authorization: "Bearer " + token } })
      .then(r => r.json())
      .then(data => {
        if (Array.isArray(data)) {
          setMsgs(data);
          if (!open && data.some(m => m.sender === "admin")) setUnread(true);
        }
      })
      .catch(() => {});
  }, []);

  React.useEffect(() => {
    const token = localStorage.getItem("bt_token");
    if (!token) return;
    let es;
    let cancelled = false;
    fetch("/api/chat/sse-ticket", {
      method: "POST",
      headers: { Authorization: "Bearer " + token },
    })
      .then(r => { if (!r.ok) throw new Error(r.status); return r.json(); })
      .then(({ ticket }) => {
        if (cancelled || !ticket) return;
        es = new EventSource("/api/chat/stream?ticket=" + encodeURIComponent(ticket));
        es.onmessage = (e) => {
          try {
            const msg = JSON.parse(e.data);
            setMsgs(prev => prev.some(m => m.id === msg.id) ? prev : [...prev, msg]);
            if (msg.sender === "admin" && !open) setUnread(true);
          } catch {}
        };
      })
      .catch(() => {});
    return () => {
      cancelled = true;
      if (es) es.close();
    };
  }, []);

  React.useEffect(() => {
    if (open) bottomRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [msgs, open]);

  const send = () => {
    const text = draft.trim();
    if (!text) return;
    const token = localStorage.getItem("bt_token");
    setDraft("");
    fetch("/api/chat/messages", {
      method: "POST",
      headers: { "Authorization": "Bearer " + token, "Content-Type": "application/json" },
      body: JSON.stringify({ text }),
    }).catch(() => {});
  };

  return (
    <>
      <button className="chat-fab" onClick={() => { setOpen(!open); setUnread(false); }} aria-label={lang === "it" ? "Apri chat" : "Open chat"}>
        <IcD.chat />
        {unread && !open && (
          <span style={{ position: "absolute", top: 8, right: 8, width: 10, height: 10, borderRadius: 5, background: "#FFB200", border: "2px solid var(--accent)" }} />
        )}
      </button>
      {open && (
        <div className="chat-panel">
          <div className="chat-head">
            <div className="av">D</div>
            <div style={{ flex: 1 }}>
              <div className="who">{t.chat.who}</div>
              <div className="stat">{t.chat.stat}</div>
            </div>
            <button className="iconbtn" onClick={() => setOpen(false)} aria-label="close"><IcD.x /></button>
          </div>
          <div className="chat-msgs">
            {msgs.map((m, i) => (
              <div className="chat-bubble" data-me={m.sender === "bolton"} key={m.id || i}>{m.text}</div>
            ))}
            <div ref={bottomRef} />
          </div>
          <div className="chat-input">
            <input placeholder={t.chat.ph} value={draft} onChange={(e) => setDraft(e.target.value)}
              onKeyDown={(e) => { if (e.key === "Enter") send(); }} />
            <button className="send" onClick={send} aria-label="send"><IcD.send /></button>
          </div>
        </div>
      )}
    </>
  );
}

/* ---------- Guided tour ---------- */
function GuidedTour({ open, onClose, steps, lang, labels }) {
  const [step, setStep] = React.useState(0);
  const [rect, setRect] = React.useState(null);

  React.useEffect(() => { if (open) setStep(0); }, [open]);

  React.useEffect(() => {
    if (!open) return;
    const s = steps[step];
    s?.enter?.();
    let alive = true;
    let raf = null;

    const tick = () => {
      if (!alive) return;
      const el = s?.getEl?.();
      if (el) {
        const r = el.getBoundingClientRect();
        setRect({ top: r.top - 6, left: r.left - 6, width: r.width + 12, height: r.height + 12, _place: s.place });
      } else {
        setRect(null);
      }
      raf = requestAnimationFrame(tick);
    };
    tick();
    return () => { alive = false; if (raf) cancelAnimationFrame(raf); };
  }, [open, step, steps]);

  if (!open) return null;

  let cardStyle = { top: "50%", left: "50%", transform: "translate(-50%, -50%)" };
  if (rect) {
    const place = rect._place || "right";
    const gap = 16;
    const cardW = 320;
    const cardH = 180;
    if (place === "right") cardStyle = { top: Math.max(20, rect.top), left: rect.left + rect.width + gap };
    else if (place === "left") cardStyle = { top: Math.max(20, rect.top), left: Math.max(20, rect.left - cardW - gap) };
    else if (place === "bottom") cardStyle = { top: rect.top + rect.height + gap, left: Math.max(20, rect.left) };
    else if (place === "top") cardStyle = { top: Math.max(20, rect.top - cardH - gap), left: Math.max(20, rect.left) };
    if (typeof cardStyle.left === "number" && cardStyle.left + cardW > window.innerWidth - 16) {
      cardStyle.left = window.innerWidth - cardW - 16;
    }
    if (typeof cardStyle.top === "number" && cardStyle.top + cardH > window.innerHeight - 16) {
      cardStyle.top = window.innerHeight - cardH - 16;
    }
  }

  return (
    <>
      <div className="tour-veil" onClick={onClose} />
      {rect && <div className="tour-spotlight" style={{ top: rect.top, left: rect.left, width: rect.width, height: rect.height }} />}
      <div className="tour-card" style={cardStyle}>
        <div className="tour-progress">
          {steps.map((_, i) => <span key={i} data-active={i === step} />)}
        </div>
        <h4>{steps[step].t}</h4>
        <p>{steps[step].d}</p>
        <div className="tour-foot">
          <button className="btn" data-variant="ghost" data-size="sm" onClick={onClose}>{labels.skip}</button>
          <div style={{ display: "flex", gap: 6 }}>
            {step > 0 && <button className="btn" data-size="sm" onClick={() => setStep(step - 1)}>{labels.back}</button>}
            <button className="btn" data-variant="primary" data-size="sm"
              onClick={() => step === steps.length - 1 ? onClose() : setStep(step + 1)}>
              {step === steps.length - 1 ? labels.done : labels.next}
            </button>
          </div>
        </div>
      </div>
    </>
  );
}

window.HelpScreen = HelpScreen;
window.ProfileScreen = ProfileScreen;
window.ChatWidget = ChatWidget;
window.GuidedTour = GuidedTour;
