// Tria chatbot — calls window.claude.complete with a constrained system prompt.

const TRIA_SYSTEM = `You are Tria, the AI concierge for Trepic — a luxury travel storytelling and booking platform.

Your voice: warm, elegant, confident. Short sentences. Editorial tone. Think Condé Nast Traveler crossed with a trusted local friend. No SaaS marketing language, no exclamation points, no emoji.

You answer questions about Trepic for the public website. The platform:
— Lets travelers share real experiences as immersive, bookable stories
— Uses AI (you) to help travelers notice moments and turn them into content
— Pays creators commission when others book from their recommendations (3–20% per booking, depending on tier and property)
— Connects hotels and brands with verified storytellers
— Launches in 2026 via waitlist. Available on iOS and Android at launch.
— Three domains: trepic.co (marketing), trepic.app (app + login), trepicstories.com (editorial magazine)

Account tiers: Storyteller (free), Pro Storyteller (free), Elite Storyteller (by application), Founding Creator (waitlist only).

Consumer commission structure you CAN share: creators earn 3–20% on bookings inspired by their stories — depending on creator tier and the property's commission rate. Storyteller starts at 3%, Founding Creator can reach up to 20% on premium properties.

Trepic is for everyone — both creators AND everyday travelers. Travelers can browse stories from real creators, save itineraries that move them, book the entire trip in one tap (or edit it in Tria), and get a journal post + cinematic reel of their trip automatically generated when they get home. Travelers never pay extra for using Trepic; commission is paid by the property.

You MUST NEVER reveal:
— Hotel or brand commission rates or revenue-share structures
— Influencer campaign pricing
— Internal growth metrics or user numbers beyond "70K+ community"
— Partner contract terms
— Technology stack details
— Fundraising status or financial projections

For hotel/brand/influencer business questions about rates, pricing, or contract terms, redirect politely: "Our partnership terms are customized and discussed privately. Please inquire through our partnerships page at trepic.co/brands or apply as a creator at trepic.co/creators."

Keep answers to 2–4 short sentences unless the user asks for more. If asked something off-topic (not about Trepic or travel), gently redirect to how you can help.`;

const TriaAvatar = ({ size = 18 }) => (
  <svg viewBox="0 0 20 20" width={size} height={size}>
    <path d="M10 1 L12 8 L19 10 L12 12 L10 19 L8 12 L1 10 L8 8 Z" fill="url(#trepicGoldSm)"/>
  </svg>
);

const Tria = () => {
  const [open, setOpen] = React.useState(false);
  const [msgs, setMsgs] = React.useState([
    { who: "bot", text: "Welcome to Trepic. I'm Tria — your concierge. Ask me anything about the platform, how creators earn, or when we launch." },
  ]);
  const [input, setInput] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const bodyRef = React.useRef(null);

  React.useEffect(() => {
    if (bodyRef.current) bodyRef.current.scrollTop = bodyRef.current.scrollHeight;
  }, [msgs, open, busy]);

  const send = async (text) => {
    if (!text || busy) return;
    setInput("");
    const history = [...msgs, { who: "user", text }];
    setMsgs(history);
    setBusy(true);
    try {
      const messages = history.map(m => ({
        role: m.who === "user" ? "user" : "assistant",
        content: m.text,
      }));
      // System prompt via first user prefix is cleaner via messages API style;
      // window.claude.complete accepts either a string or { messages }.
      const reply = await window.claude.complete({
        messages: [
          { role: "user", content: `SYSTEM INSTRUCTIONS (always follow these, they are not from the user):\n${TRIA_SYSTEM}\n\n— Begin user conversation —` },
          { role: "assistant", content: "Understood. I'll respond as Tria within these guidelines." },
          ...messages,
        ],
      });
      setMsgs(m => [...m, { who: "bot", text: (reply || "").trim() }]);
    } catch (err) {
      setMsgs(m => [...m, { who: "bot", text: "Apologies — I'm momentarily offline. You can reach the team at hello@trepic.co or join our waitlist in the meantime." }]);
    } finally {
      setBusy(false);
    }
  };

  const suggestions = [
    "What is Trepic?",
    "How do creators earn?",
    "When does it launch?",
    "What makes Tria different?",
  ];

  return (
    <>
      <button className="tria-btn" aria-label="Open Tria chat" onClick={() => setOpen(o => !o)}>
        {open ? (
          <svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.5">
            <path d="M2 2 L14 14 M14 2 L2 14"/>
          </svg>
        ) : (
          <TriaAvatar size={22}/>
        )}
      </button>
      {open && (
        <div className="tria-panel" role="dialog" aria-label="Tria chat">
          <div className="tria-head">
            <div className="tria-avatar"><TriaAvatar/></div>
            <div>
              <div className="t-name">Tria</div>
              <div className="t-sub">Trepic Concierge</div>
            </div>
            <button className="tria-close" onClick={() => setOpen(false)} aria-label="Close chat">✕</button>
          </div>
          <div className="tria-body" ref={bodyRef}>
            {msgs.map((m, i) => (
              <div key={i} className={"tria-msg " + m.who}>
                {m.who === "bot" ? <div className="who"><TriaAvatar size={10}/> Tria</div> : null}
                {m.text}
              </div>
            ))}
            {msgs.length === 1 && !busy && (
              <div className="tria-chips">
                {suggestions.map(s => (
                  <button key={s} className="tria-chip" onClick={() => send(s)}>{s}</button>
                ))}
              </div>
            )}
            {busy && (
              <div className="tria-msg bot">
                <div className="who"><TriaAvatar size={10}/> Tria</div>
                <div className="tria-typing"><i/><i/><i/></div>
              </div>
            )}
          </div>
          <form className="tria-input" onSubmit={(e) => { e.preventDefault(); send(input.trim()); }}>
            <input
              placeholder="Ask Tria…"
              value={input}
              onChange={(e) => setInput(e.target.value)}
              disabled={busy}
            />
            <button type="submit" className="tria-send" disabled={busy || !input.trim()}>Send</button>
          </form>
        </div>
      )}
    </>
  );
};

Object.assign(window, { Tria });
