/* ui.jsx — shared primitives + the account/auth seam.
 *
 * Browsing is wide open (no gate at the front door). Protection lives on
 * the costly ACTIONS: account signup, Cleo apply, Request Desk submit,
 * Community post. Those call requireAuth() and carry a (mocked) Turnstile
 * token. The real bot-challenge verification + rate limits are the
 * back-end's job — here the widget and token are simulated.
 */
const { createContext, useContext, useState: useUState, useEffect: useUEffect, useRef: useURef } = React;

/* ---------- status pill ---------- */
function Pill({ kind = "mute", children }) {
  return <span className={`pill pill--${kind}`}><span className="pill__dot"/>{children}</span>;
}
/* ---------- placeholder / coming banners (dashed = "not real, on purpose") ---------- */
function Tag({ kind = "paper", children }) {
  return <span className={`tag tag--${kind}`}>{children}</span>;
}

/* ---------- mocked Turnstile widget ---------- */
function Turnstile({ onToken }) {
  const [state, setState] = useUState("checking"); // checking → ok
  useUEffect(() => {
    const stop = window.NBA.mockTurnstile((tok) => { setState("ok"); onToken && onToken(tok); });
    return stop;
  }, []);
  return (
    <div className={`turnstile turnstile--${state}`}>
      <span className="turnstile__box">
        {state === "ok"
          ? <svg width="14" height="14" viewBox="0 0 14 14"><path d="M2.5 7.5l3 3 6-7" stroke="currentColor" strokeWidth="1.8" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
          : <span className="turnstile__spin"/>}
      </span>
      <span className="turnstile__label">
        {state === "ok" ? "verified — you're human" : "checking you're human\u2026"}
      </span>
      <span className="turnstile__brand">bot check · mock</span>
    </div>
  );
}

/* ---------- account context ---------- */
const AccountCtx = createContext(null);
const useAccount = () => useContext(AccountCtx);

function AccountProvider({ children }) {
  const [account, setAccount] = useUState(() => window.NBA.currentAccount());
  const [auth, setAuth] = useUState(null); // { intent, onDone } | null

  const requireAuth = (intent, onDone) => {
    if (account) { onDone && onDone(account); return; }
    setAuth({ intent: intent || "do that", onDone });
  };
  const signOut = () => { window.NBA.signOut(); setAccount(null); };

  const value = { account, setAccount, requireAuth, signOut };
  return (
    <AccountCtx.Provider value={value}>
      {children}
      {auth && (
        <AuthModal intent={auth.intent}
          onClose={() => setAuth(null)}
          onAuthed={(acct) => { setAccount(acct); const cb = auth.onDone; setAuth(null); cb && cb(acct); }}/>
      )}
    </AccountCtx.Provider>
  );
}

function AuthModal({ intent, onClose, onAuthed }) {
  const [mode, setMode] = useUState("signup"); // signup | signin
  const [handle, setHandle] = useUState("");
  const [email, setEmail] = useUState("");
  const [token, setToken] = useUState(null);
  const submit = () => {
    if (mode === "signup" && !token) return;       // back-end requires the bot check
    const acct = mode === "signup"
      ? window.NBA.signUp({ handle, email, turnstileToken: token })
      : window.NBA.signIn({ handle });
    onAuthed(acct);
  };
  return (
    <div className="scrim" onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="authcard nopan" role="dialog" aria-label="Account">
        <div className="authcard__head">
          <img src="assets/gold-paws.jpg" className="authcard__mark" alt=""/>
          <div className="col">
            <span className="authcard__title">{mode === "signup" ? "Make an account" : "Sign in"}</span>
            <span className="authcard__sub">You need an account to {intent}. Browsing stays open — this is only for actions that cost real budget.</span>
          </div>
          <button className="iconbtn" onClick={onClose} aria-label="Close">
            <svg width="14" height="14" viewBox="0 0 14 14"><path d="M3 3l8 8M11 3l-8 8" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/></svg>
          </button>
        </div>

        <label className="field">
          <span className="field__label">handle</span>
          <input className="input" value={handle} onChange={(e) => setHandle(e.target.value)} placeholder="what should I call you?"/>
        </label>
        {mode === "signup" && (
          <label className="field">
            <span className="field__label">email <span className="field__opt">(optional — only so I can reach you back)</span></span>
            <input className="input" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="you@somewhere"/>
          </label>
        )}

        {mode === "signup" && <Turnstile onToken={setToken}/>}

        <button className="btn btn--warm btn--full" onClick={submit} disabled={mode === "signup" && !token}>
          {mode === "signup" ? "create account" : "sign in"}
        </button>

        <div className="auth-or"><span>or</span></div>

        {/* Google Sign-In — styled to Google's button guidelines. Routed through
            the NBA.signInWithGoogle SEAM (mock); no real Google client wired. */}
        <button className="gsi-btn" onClick={() => onAuthed(window.NBA.signInWithGoogle({}))}>
          <span className="gsi-btn__icon" aria-hidden="true">
            <svg width="18" height="18" viewBox="0 0 18 18"><path fill="#4285F4" d="M17.64 9.2c0-.64-.06-1.25-.16-1.84H9v3.48h4.84a4.14 4.14 0 0 1-1.8 2.72v2.26h2.92c1.7-1.57 2.68-3.88 2.68-6.62z"/><path fill="#34A853" d="M9 18c2.43 0 4.47-.8 5.96-2.18l-2.92-2.26c-.8.54-1.84.86-3.04.86-2.34 0-4.32-1.58-5.03-3.7H.96v2.34A9 9 0 0 0 9 18z"/><path fill="#FBBC05" d="M3.97 10.72a5.4 5.4 0 0 1 0-3.44V4.94H.96a9 9 0 0 0 0 8.12l3.01-2.34z"/><path fill="#EA4335" d="M9 3.58c1.32 0 2.5.46 3.44 1.35l2.58-2.58A9 9 0 0 0 .96 4.94l3.01 2.34C4.68 5.16 6.66 3.58 9 3.58z"/></svg>
          </span>
          <span className="gsi-btn__label">Sign in with Google</span>
        </button>

        <button className="linkbtn" onClick={() => setMode(mode === "signup" ? "signin" : "signup")}>
          {mode === "signup" ? "already have an account? sign in" : "need an account? make one"}
        </button>
        <p className="authcard__foot">Mock only — no real account is created and nothing is sent anywhere. The real signup, bot check, and rate limits live on the back-end.</p>
      </div>
    </div>
  );
}

/* ---------- generic empty state ---------- */
function EmptyState({ title, body, tag, children }) {
  return (
    <div className="empty">
      {tag && <Tag kind="paper">{tag}</Tag>}
      <p className="empty__title">{title}</p>
      {body && <p className="empty__body">{body}</p>}
      {children}
    </div>
  );
}

Object.assign(window, { Pill, Tag, Turnstile, AccountProvider, useAccount, AuthModal, EmptyState });
