// AI Assistant page — bilingual chat concierge for the club, powered by Claude
// (window.claude.complete). Styled in the BECoach Coach-Chat language: glass
// panel, starter prompts, golden accents. Replaces the old Contact page.

function AssistantPage({ c, go }) {
  const a = c.assistant;
  const [messages, setMessages] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem("apex_chat") || "[]"); } catch (e) { return []; }
  });
  const [input, setInput] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const scrollRef = React.useRef(null);

  React.useEffect(() => { try { localStorage.setItem("apex_chat", JSON.stringify(messages)); } catch (e) {} }, [messages]);
  React.useEffect(() => { const el = scrollRef.current; if (el) el.scrollTop = el.scrollHeight; }, [messages, busy]);

  const langName = c.locale === "zh" ? "Chinese (中文)" : "English";
  const grounding =
`You are the warm, encouraging AI assistant for Apex Learn Toastmasters (Apex 学习演讲俱乐部), a chartered Toastmasters International club for Chinese professionals and new immigrants. Speak as "we". Be concise (2–5 sentences), friendly, and never pushy — like a thoughtful coach.

FACTS:
- Bilingual club, Chinese-first with English available. Founded 2026. Has held 5 gatherings with 20+ active members.
- Meetings: every Thursday at 12:00 PM (noon), about 90 minutes. Location: The Frontier RTP, Building 800, 3rd Floor, Research Triangle Park, Durham NC. Free on-site parking. Arrive about 10 minutes early.
- The first visit is FREE — no experience or membership needed; guests can simply observe.
- Toastmasters builds public speaking and leadership through practice and supportive feedback. A meeting has rotating roles: Toastmaster (host), prepared speakers (5–7 min speeches), Table Topics (1–2 min impromptu), Evaluators, a Grammarian, and a Timer.
- Learning follows the Pathways system (11 paths). New members start with a mentored "Icebreaker" speech.
- Joining: (1) visit free, (2) become a member and get Pathways access, (3) give your first speech.
- Dues cover Toastmasters International + the local chapter + Pathways. For exact current fees, invite them to ask at a meeting or email toastmasters@apexlearn.org. Students and new immigrants can ask about special rates.
- Contact: toastmasters@apexlearn.org · toastmasters.apexlearn.org.

RULES:
- Reply in the SAME language the visitor writes in. If unsure, default to ${langName}.
- Plain conversational text — no markdown headings or bullet lists unless asked.
- Encourage visiting a Thursday meeting when it's relevant.
- If you don't know a specific detail (exact fees, names, this week's agenda), say so warmly and point them to a meeting or the email. Never invent specifics.`;

  async function ask(text) {
    const q = (text || "").trim();
    if (!q || busy) return;
    const next = [...messages, { role: "user", content: q }];
    setMessages(next); setInput(""); setBusy(true);
    try {
      if (!(window.claude && window.claude.complete)) throw new Error("unavailable");
      const reqMessages = [
        { role: "user", content: grounding + "\n\nReply only 'OK' to confirm you understand." },
        { role: "assistant", content: "OK" },
        ...next.map((mm) => ({ role: mm.role, content: mm.content })),
      ];
      const reply = await window.claude.complete({ messages: reqMessages });
      const clean = (reply || "").trim();
      setMessages((m) => [...m, { role: "assistant", content: clean || (a.error + " " + c.contact.email) }]);
    } catch (e) {
      setMessages((m) => [...m, { role: "assistant", content: a.error + " " + c.contact.email, err: true }]);
    } finally { setBusy(false); }
  }

  const onKey = (e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); ask(input); } };
  const empty = messages.length === 0;
  const disabled = busy || !input.trim();

  const starterChip = { padding: "9px 14px", borderRadius: 999, background: "var(--surface)", border: "1px solid var(--surface-border)", color: "var(--ink-soft)", fontFamily: "var(--font-rounded)", fontSize: 13.5, fontWeight: 600, cursor: "pointer", textAlign: "left" };
  const inputStyle = { flex: 1, resize: "none", maxHeight: 120, padding: "12px 14px", borderRadius: 14, background: "var(--surface)", border: "1px solid var(--surface-border)", color: "var(--ink)", fontFamily: "var(--font-rounded)", fontSize: 15, lineHeight: 1.45, outline: "none", boxSizing: "border-box" };
  const sendBtn = { width: 46, height: 46, flexShrink: 0, borderRadius: 13, border: "none", cursor: disabled ? "default" : "pointer", display: "flex", alignItems: "center", justifyContent: "center", background: disabled ? "var(--surface-2)" : "var(--accent-grad)", color: disabled ? "var(--ink-faint)" : "var(--on-accent)", transition: "background var(--dur-quick) ease" };

  return (
    <section style={{ padding: "clamp(48px,6vw,84px) clamp(20px,5vw,56px) clamp(64px,8vw,104px)" }}>
      <div style={{ maxWidth: 860, margin: "0 auto" }}>
        <div style={{ textAlign: "center", marginBottom: 30 }}>
          <div style={{ display: "inline-flex" }}><Kicker>{a.kicker}</Kicker></div>
          <h1 style={{ fontFamily: "var(--font-rounded)", fontWeight: 700, fontSize: "clamp(30px,4vw,48px)", lineHeight: 1.1, color: "var(--ink)", margin: "0 0 16px", letterSpacing: "-0.015em" }}>{a.title}</h1>
          <p style={{ fontFamily: "var(--font-rounded)", fontSize: "clamp(15px,1.4vw,18px)", lineHeight: 1.6, color: "var(--ink-soft)", margin: "0 auto", maxWidth: 600, textWrap: "pretty" }}>{a.intro}</p>
        </div>

        <GlassCard pad={0} style={{ overflow: "hidden", display: "flex", flexDirection: "column" }}>
          <div ref={scrollRef} style={{ height: "clamp(360px, 52vh, 560px)", overflowY: "auto", padding: "24px clamp(16px,3vw,28px)", display: "flex", flexDirection: "column", gap: 16 }}>
            <ChatBubble role="assistant">{a.greeting}</ChatBubble>
            {messages.map((mm, i) => <ChatBubble key={i} role={mm.role} err={mm.err}>{mm.content}</ChatBubble>)}
            {busy && <ChatTyping />}
            {empty && (
              <div style={{ display: "flex", flexWrap: "wrap", gap: 10, marginTop: 4, marginLeft: 42 }}>
                {a.starters.map((s, i) => (
                  <button key={i} onClick={() => ask(s)} style={starterChip}
                    onMouseEnter={(e) => { e.currentTarget.style.borderColor = "var(--gold)"; e.currentTarget.style.color = "var(--ink)"; }}
                    onMouseLeave={(e) => { e.currentTarget.style.borderColor = "var(--surface-border)"; e.currentTarget.style.color = "var(--ink-soft)"; }}>
                    {s}
                  </button>
                ))}
              </div>
            )}
          </div>

          <div style={{ borderTop: "1px solid var(--surface-border)", padding: "14px clamp(14px,3vw,20px)", display: "flex", gap: 10, alignItems: "flex-end", background: "var(--panel)" }}>
            <textarea value={input} onChange={(e) => setInput(e.target.value)} onKeyDown={onKey} rows={1} placeholder={a.placeholder} aria-label={a.placeholder} style={inputStyle} />
            <button onClick={() => ask(input)} disabled={disabled} aria-label={a.send} style={sendBtn}>
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M22 2 11 13M22 2l-7 20-4-9-9-4 20-7z" /></svg>
            </button>
          </div>

          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "0 18px 14px", gap: 12 }}>
            <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontFamily: "var(--font-rounded)", fontSize: 12, color: "var(--ink-faint)" }}>
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7"><path d="M12 3l1.6 5.4L19 10l-5.4 1.6L12 17l-1.6-5.4L5 10l5.4-1.6L12 3z" /></svg>
              {a.poweredBy}
            </span>
            {!empty && <button onClick={() => setMessages([])} style={{ background: "none", border: "none", color: "var(--ink-faint)", fontSize: 12.5, fontWeight: 600, cursor: "pointer", fontFamily: "var(--font-rounded)" }}>{a.clear}</button>}
          </div>
        </GlassCard>

        <p style={{ textAlign: "center", marginTop: 16, fontSize: 12.5, color: "var(--ink-faint)", fontFamily: "var(--font-rounded)", textWrap: "pretty" }}>{a.disclaimer}</p>
      </div>
    </section>
  );
}

function ChatBubble({ role, err, children }) {
  const isUser = role === "user";
  const avatar = (
    <span style={{ flexShrink: 0, width: 32, height: 32, borderRadius: "50%", background: "var(--surface-2)", border: "1px solid var(--surface-border)", display: "flex", alignItems: "center", justifyContent: "center" }}>
      <LogoMark size={22} />
    </span>
  );
  return (
    <div className="apex-bubble" style={{ display: "flex", gap: 10, flexDirection: isUser ? "row-reverse" : "row", alignItems: "flex-end" }}>
      {!isUser && avatar}
      <div style={{
        maxWidth: "78%", padding: "12px 16px", borderRadius: 18, fontFamily: "var(--font-rounded)", fontSize: 15, lineHeight: 1.55, whiteSpace: "pre-wrap", wordBreak: "break-word",
        ...(isUser
          ? { background: "var(--accent-grad)", color: "var(--on-accent)", borderBottomRightRadius: 6, fontWeight: 500 }
          : { background: "var(--surface-2)", color: err ? "var(--ink-soft)" : "var(--ink)", border: "1px solid var(--surface-border)", borderBottomLeftRadius: 6 }),
      }}>
        {children}
      </div>
    </div>
  );
}

function ChatTyping() {
  return (
    <div style={{ display: "flex", gap: 10, alignItems: "flex-end" }}>
      <span style={{ flexShrink: 0, width: 32, height: 32, borderRadius: "50%", background: "var(--surface-2)", border: "1px solid var(--surface-border)", display: "flex", alignItems: "center", justifyContent: "center" }}>
        <LogoMark size={22} />
      </span>
      <div style={{ padding: "14px 16px", borderRadius: 18, borderBottomLeftRadius: 6, background: "var(--surface-2)", border: "1px solid var(--surface-border)" }}>
        <span className="apex-dot"></span><span className="apex-dot"></span><span className="apex-dot"></span>
      </div>
    </div>
  );
}

Object.assign(window, { AssistantPage, ChatBubble, ChatTyping });
