/* global React */
const { useState, useEffect, useRef, createContext, useContext } = React;

/* ----------------------------------------------------------------
   Token context — the anxiety-inducing live counter, persisted
----------------------------------------------------------------- */
const TokenCtx = createContext(null);
const useTokens = () => useContext(TokenCtx);

function TokenProvider({ children, drainMs = 2600 }) {
  const [screen, setScreen] = useState("home");
  const [tokens, setTokens] = useState(() => {
    const saved = localStorage.getItem("ta_tokens");
    return saved ? Number(saved) : 8420;
  });

  // drains slowly, like real life
  useEffect(() => {
    const id = setInterval(() => {
      setTokens((t) => {
        const next = Math.max(0, t - Math.floor(Math.random() * 7 + 2));
        localStorage.setItem("ta_tokens", String(next));
        return next;
      });
    }, drainMs);
    return () => clearInterval(id);
  }, [drainMs]);

  const navigate = (s) => {
    setScreen(s);
    window.scrollTo({ top: 0, behavior: "instant" in window ? "instant" : "auto" });
  };

  const refill = () => {
    setTokens(8420);
    localStorage.setItem("ta_tokens", "8420");
  };

  return (
    <TokenCtx.Provider value={{ screen, navigate, tokens, refill }}>
      {children}
    </TokenCtx.Provider>
  );
}

/* ----------------------------------------------------------------
   Small atoms
----------------------------------------------------------------- */
function Eyebrow({ children }) {
  return <span className="eyebrow">{children}</span>;
}

function Btn({ variant = "primary", size, onClick, children, style }) {
  const cls = `btn btn-${variant}${size === "lg" ? " btn-lg" : ""}`;
  return <button className={cls} onClick={onClick} style={style}>{children}</button>;
}

function Pill({ children }) {
  return <span className="pill">{children}</span>;
}

/* tiny inline icons (kept extremely simple — squares, circles, paths) */
function Icon({ name, size = 20 }) {
  const p = {
    width: size, height: size, viewBox: "0 0 24 24", fill: "none",
    stroke: "currentColor", strokeWidth: 1.6, strokeLinecap: "round", strokeLinejoin: "round",
  };
  switch (name) {
    case "leaf": return <svg {...p}><path d="M11 20C6 20 4 15 4 11c5 0 9 1 11 4M20 4c0 7-3 12-9 12" /></svg>;
    case "heart": return <svg {...p}><path d="M12 20S4 15 4 9.5A4 4 0 0 1 12 7a4 4 0 0 1 8 2.5C20 15 12 20 12 20Z" /></svg>;
    case "clock": return <svg {...p}><circle cx="12" cy="12" r="8" /><path d="M12 8v4l3 2" /></svg>;
    case "shield": return <svg {...p}><path d="M12 3l7 3v5c0 5-3.5 8-7 10-3.5-2-7-5-7-10V6l7-3Z" /></svg>;
    case "check": return <svg {...p}><path d="M5 12.5l4.5 4.5L19 6" /></svg>;
    case "arrow": return <svg {...p}><path d="M5 12h14M13 6l6 6-6 6" /></svg>;
    case "arrowL": return <svg {...p}><path d="M19 12H5M11 6l-6 6 6 6" /></svg>;
    case "phone": return <svg {...p}><path d="M5 4h4l2 5-3 2a11 11 0 0 0 5 5l2-3 5 2v4a2 2 0 0 1-2 2A16 16 0 0 1 3 6a2 2 0 0 1 2-2Z" /></svg>;
    case "spark": return <svg {...p}><path d="M12 3v6m0 6v6M3 12h6m6 0h6" /></svg>;
    case "calc": return <svg {...p}><rect x="5" y="3" width="14" height="18" rx="2" /><path d="M8 7h8M8 11h.01M12 11h.01M16 11h.01M8 15h.01M12 15h.01M16 15v2M8 19h4" /></svg>;
    case "moon": return <svg {...p}><path d="M20 14a8 8 0 0 1-10-10 8 8 0 1 0 10 10Z" /></svg>;
    case "scissors": return <svg {...p}><circle cx="6" cy="6" r="2.5" /><circle cx="6" cy="18" r="2.5" /><path d="M8 8l12 10M8 16L20 6" /></svg>;
    case "wave": return <svg {...p}><path d="M2 12c2 0 2-3 4-3s2 3 4 3 2-3 4-3 2 3 4 3 2-3 4-3" /></svg>;
    case "user": return <svg {...p}><circle cx="12" cy="8" r="4" /><path d="M4 21c0-4 3.5-6 8-6s8 2 8 6" /></svg>;
    default: return null;
  }
}

/* ----------------------------------------------------------------
   Navigation
----------------------------------------------------------------- */
const NAV = [
  ["home", "Home"],
  ["symptoms", "Warning Signs"],
  ["quiz", "Self-Assessment"],
  ["tools", "Tools"],
  ["testimonials", "Stories"],
  ["counseling", "Get Help"],
];

function Nav() {
  const { screen, navigate, tokens } = useTokens();
  const low = tokens < 2500;
  return (
    <nav className="nav">
      <div className="nav-inner">
        <div className="brand" onClick={() => navigate("home")}>
          <div className="brand-mark">T</div>
          <div className="brand-name">Token<b>Anon</b></div>
        </div>
        <div className="nav-links">
          {NAV.map(([id, label]) => (
            <a key={id}
               className={`nav-link${screen === id ? " active" : ""}`}
               onClick={() => navigate(id)}>{label}</a>
          ))}
        </div>
        <div className="nav-right">
          <div className="token-meter" onClick={() => navigate("crisis")} title="Your remaining allowance for today">
            <span className={`token-dot${low ? " low" : ""}`}></span>
            <div style={{ display: "flex", flexDirection: "column", lineHeight: 1.15 }}>
              <span className="tm-label">Tokens left today</span>
              <span className={`tm-num${low ? " low" : ""}`}>{tokens.toLocaleString()}</span>
            </div>
          </div>
          <Btn variant="clay" onClick={() => navigate("crisis")}>
            <Icon name="phone" size={16} /> I'm almost out
          </Btn>
        </div>
      </div>
    </nav>
  );
}

/* ----------------------------------------------------------------
   Footer
----------------------------------------------------------------- */
function Footer() {
  const { navigate } = useTokens();
  return (
    <footer className="footer">
      <div className="footer-inner">
        <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr 1fr", gap: 40 }}>
          <div>
            <div className="brand" style={{ cursor: "default" }}>
              <div className="brand-mark">T</div>
              <div className="brand-name">Token<b>Anon</b></div>
            </div>
            <p style={{ fontSize: 14.5, color: "var(--muted)", marginTop: 16, maxWidth: 320 }}>
              A confidential, judgment-free space for people learning to live within their context window.
            </p>
            <div style={{ marginTop: 18 }}><Pill><Icon name="shield" size={14} /> 100% confidential · we don't log your prompts</Pill></div>
          </div>
          <div>
            <div style={{ fontSize: 13, fontWeight: 700, letterSpacing: "0.06em", textTransform: "uppercase", color: "var(--faint)", marginBottom: 14 }}>Recovery</div>
            {[["symptoms","Warning Signs"],["quiz","Take the Assessment"],["tools","Coping Tools"],["counseling","Find a Counselor"]].map(([id,l]) => (
              <div key={id} style={{ marginBottom: 9 }}><a onClick={() => navigate(id)} style={{ fontSize: 14.5, color: "var(--muted)", cursor: "pointer" }}>{l}</a></div>
            ))}
          </div>
          <div>
            <div style={{ fontSize: 13, fontWeight: 700, letterSpacing: "0.06em", textTransform: "uppercase", color: "var(--faint)", marginBottom: 14 }}>In crisis?</div>
            <p style={{ fontSize: 14.5, color: "var(--muted)" }}>The Context Window Helpline is staffed 24/7 by people who have also said "this is my last prompt."</p>
            <div style={{ marginTop: 14 }}><Btn variant="ghost" onClick={() => navigate("crisis")}><Icon name="phone" size={15} /> 1-800-NO-TOKENS</Btn></div>
          </div>
        </div>
        <p className="footer-disclaimer">
          TokenAnon is a work of parody. It is not affiliated with any model provider and offers no real medical, psychological, or
          token-management advice. "Token addiction" is not a recognized clinical condition — though if you read this entire footer to
          make the page feel complete, we gently suggest the self-assessment. No tokens were rationed in the making of this site.
        </p>
      </div>
    </footer>
  );
}

Object.assign(window, { TokenProvider, useTokens, Eyebrow, Btn, Pill, Icon, Nav, Footer });
