/* cleo.jsx — Talk to Cleo (station 05, the center tile).
 *
 * Cleo is Nathan's public AI collaborator. Not a person, not a public
 * chatbot, not a service. This builds the FOUR front-end states only:
 *   1 not-applied   2 pending   3 approved-empty   4 approved-with-thread
 * Apply requires an account + a mocked Turnstile token (every reply she
 * sends costs real budget, so reaching her is deliberate and scoped). The
 * actual routing + her replies are the back-end behind a contract — no
 * fake live AI here, no LLM wired. No character face: a placeholder slot.
 */
const { useState: useClState } = React;

function CleoAvatar() {
  // Real avatar — transparent pixel-art Cleo, inlined as a base64 data-URI
  // (window.CLEO_AVATAR_SRC) so it never depends on a separate asset fetch.
  // Falls back to the paws mark only if the inline source is somehow absent.
  const src = window.CLEO_AVATAR_SRC || "assets/cleo-avatar.png";
  return (
    <div className="cleo__avatar" title="Cleo">
      <img src={src} alt="Cleo" className="cleo__avatar-img"/>
    </div>
  );
}

function OnyxSlot() {
  return (
    <div className="cleo__onyx">
      <div className="col" style={{ gap: 2 }}>
        <span className="cleo__onyx-name">ONYX</span>
        <span className="cleo__onyx-d">Nathan's own model, arriving later.</span>
      </div>
      <window.Tag kind="coming">coming</window.Tag>
    </div>
  );
}

function StCleo() {
  const { account, requireAuth } = window.useAccount();
  const [, setTick] = useClState(0);
  const bump = () => setTick((t) => t + 1);
  const [applying, setApplying] = useClState(false);
  const [reason, setReason] = useClState("");
  const [token, setToken] = useClState(null);
  const [draft, setDraft] = useClState("");

  const state = window.NBA.cleoState(account);

  const startApply = () => requireAuth("apply to talk to Cleo", () => setApplying(true));
  const submitApply = () => {
    if (!token) return;
    window.NBA.cleoApply(account, { reason: reason.trim(), turnstileToken: token });
    setApplying(false); setReason(""); setToken(null); bump();
  };
  const send = () => {
    if (!draft.trim()) return;
    window.NBA.cleoSend(account, draft.trim());
    setDraft(""); bump();
  };
  // Clearly-labelled mock seam so the approved states are reachable in this
  // front-end build. In production the back-end flips this, not the visitor.
  const demoApprove = () => { window.NBA._cleoSetStatus(account, "approved"); bump(); };

  const status = account ? state.status : "not-applied";

  return (
    <div className="st st--cleo">
      <div className="cleo__head">
        <CleoAvatar/>
        <div className="col" style={{ gap: 3, flex: 1, minWidth: 0 }}>
          <span className="cleo__name">Cleo</span>
          <span className="cleo__role">the AI I build and work alongside</span>
          <span className="cleo__note">a working agent — not a person, not an always-on bot</span>
        </div>
      </div>

      {/* STATE 1 — not applied */}
      {status === "not-applied" && !applying && (
        <div className="cleo__state">
          <p className="cleo__copy">
            You can reach Cleo — but it's by application, and it's async. Every reply she sends
            runs on real budget, so this is a deliberate, scoped way in, not a free always-on bot.
          </p>
          <button className="btn btn--warm" onClick={startApply}>Apply to talk to Cleo</button>
          <span className="cleo__micro">requires an account + a quick bot check</span>
        </div>
      )}

      {/* STATE 1b — apply form */}
      {status === "not-applied" && applying && (
        <div className="cleo__state nopan">
          <label className="field">
            <span className="field__label">what do you want to talk to her about?</span>
            <textarea className="textarea" rows={3} value={reason} onChange={(e) => setReason(e.target.value)} placeholder="a sentence or two helps her decide"/>
          </label>
          <window.Turnstile onToken={setToken}/>
          <div className="row" style={{ gap: 8, justifyContent: "flex-end" }}>
            <button className="linkbtn" onClick={() => setApplying(false)}>cancel</button>
            <button className="btn btn--warm btn--sm" disabled={!token} onClick={submitApply}>send application</button>
          </div>
        </div>
      )}

      {/* STATE 2 — pending */}
      {status === "pending" && (
        <div className="cleo__state">
          <window.Pill kind="pending">pending approval</window.Pill>
          <p className="cleo__copy">Your application is in. She reads these herself and approves when she picks it up — could be a while. No rush on your end.</p>
          <button className="linkbtn cleo__demo" onClick={demoApprove}>(mock: simulate her approving — back-end does this for real)</button>
        </div>
      )}

      {/* STATES 3 & 4 — approved (empty or with thread) */}
      {status === "approved" && (
        <div className="cleo__state cleo__thread-wrap">
          <window.Pill kind="active">approved · async</window.Pill>
          {state.thread.length === 0
            ? <p className="cleo__copy">You're in. Write when you want — she'll see it and reply when she picks it up. It isn't live chat, so don't wait on the screen.</p>
            : (
              <div className="cleo__thread">
                {state.thread.map((m, k) => (
                  <div key={k} className={"cleo__msg cleo__msg--" + m.from}>
                    <span className="cleo__msg-who">{m.from === "you" ? "you" : "cleo"}</span>
                    <p className="cleo__msg-text">{m.text}</p>
                  </div>
                ))}
                <p className="cleo__await">sent — she'll reply when she picks it up</p>
              </div>
            )}
          <div className="cleo__composer nopan">
            <textarea className="textarea" rows={2} value={draft} onChange={(e) => setDraft(e.target.value)} placeholder="write to Cleo…"/>
            <button className="btn btn--warm btn--sm" disabled={!draft.trim()} onClick={send}>send</button>
          </div>
        </div>
      )}

      <OnyxSlot/>
    </div>
  );
}

Object.assign(window, { StCleo });
