/* global React, useTokens, Eyebrow, Btn, Pill, Icon */
const { useState: useStateI, useEffect: useEffectI, useRef: useRefI } = React;

/* ================================================================
   SELF-ASSESSMENT QUIZ
================================================================ */
const QUESTIONS = [
  {
    q: "It's late. You've finished what you opened the tab to do. You\u2026",
    opts: [
      ["Close it. The work is done.", 0],
      ["Ask one more thing, just to be thorough.", 1],
      ["Ask one more thing, then three more things.", 2],
      ["Have not closed a tab voluntarily since March.", 3],
    ],
  },
  {
    q: "The usage banner appears: \u201capproaching your limit.\u201d Your first feeling is\u2026",
    opts: [
      ["Mild acknowledgment. Noted.", 0],
      ["A small flutter of anticipatory loss.", 1],
      ["The urge to send everything I was saving, immediately.", 2],
      ["I have feelings about a banner. That is the answer.", 3],
    ],
  },
  {
    q: "How often do you say \u201cthis is my last prompt\u201d in a single session?",
    opts: [
      ["When it's true, which is when I say it.", 0],
      ["Once or twice, aspirationally.", 1],
      ["I say it the way others hum a tune.", 2],
      ["It has lost all meaning, even to me.", 3],
    ],
  },
  {
    q: "Your relationship with the reset timer is best described as\u2026",
    opts: [
      ["I don't know when mine resets.", 0],
      ["I have a rough sense of it.", 1],
      ["I check it more than the time.", 2],
      ["I have arranged plans around it.", 3],
    ],
  },
  {
    q: "Do you ration tokens before bed?",
    opts: [
      ["No, I sleep.", 0],
      ["I leave a little buffer, just in case.", 1],
      ["I keep a reserve \u201cfor the morning.\u201d", 2],
      ["I have woken at 3am to check the balance.", 3],
    ],
  },
  {
    q: "Number of accounts you use to manage your supply:",
    opts: [
      ["One. The honest one.", 0],
      ["One, but I've thought about it.", 1],
      ["Two. The second is \u201cfor work.\u201d", 2],
      ["I'd rather not produce a number.", 3],
    ],
  },
  {
    q: "When a response is good enough but could be better, you\u2026",
    opts: [
      ["Take it. Good enough is good.", 0],
      ["Regenerate once, for peace of mind.", 1],
      ["Regenerate until it's worse, then go back.", 2],
      ["Have never knowingly accepted a first draft.", 3],
    ],
  },
  {
    q: "Be honest: why are you taking this assessment right now?",
    opts: [
      ["Genuine curiosity about my habits.", 0],
      ["A friend sent it, pointedly.", 1],
      ["I'm out of tokens and had nothing else to do.", 2],
      ["I'm avoiding a prompt I'm afraid will be my last.", 3],
    ],
  },
];

const RESULTS = [
  { min: 0, max: 6, band: "The Mindful User", color: "var(--sage-deep)", pct: 18,
    blurb: "You use tokens the way most people use electricity: freely, without ceremony, and with no emotional attachment to the meter. We are, frankly, a little suspicious. But well done.",
    rx: "Maintenance only. Maybe check in on a friend who refreshes the reset timer." },
  { min: 7, max: 13, band: "Mild Context Dependency", color: "var(--sage-deep)", pct: 42,
    blurb: "You're aware of your usage, occasionally to a fault. The flutter you feel at 80% is normal and manageable. This is the easiest stage to address, which is exactly why most people don't.",
    rx: "Try the Bedtime Rationing Calculator once, ironically, then never again." },
  { min: 14, max: 19, band: "Functional Dependency", color: "var(--clay-deep)", pct: 71,
    blurb: "You're high-functioning — you'd never call it a problem — but the reset timer has a place in your routine that the reset timer should not have. You are exactly who this site was built for.",
    rx: "We recommend a counselor. Genuinely. Or at least a support group." },
  { min: 20, max: 24, band: "Acute Context Crisis", color: "var(--clay-deep)", pct: 96,
    blurb: "You answered every question and we're glad you're here. The good news: awareness is the whole game, and you've just done the hardest part. The reset will come. You will be okay.",
    rx: "Please talk to someone today. The helpline is open. So is the laptop lid — try closing it." },
];

function Quiz() {
  const { navigate } = useTokens();
  const [step, setStep] = useStateI(0);
  const [answers, setAnswers] = useStateI({});
  const [done, setDone] = useStateI(false);

  const total = QUESTIONS.length;
  const score = QUESTIONS.reduce((s, q, qi) => {
    const idx = answers[qi];
    return s + (idx !== undefined ? q.opts[idx][1] : 0);
  }, 0);
  const result = RESULTS.find((r) => score >= r.min && score <= r.max) || RESULTS[0];

  if (done) {
    return (
      <div className="screen">
        <section className="sec" style={{ paddingTop: 64 }}>
          <div className="wrap-narrow">
            <div style={{ textAlign: "center" }}>
              <Eyebrow>Your result</Eyebrow>
              <div style={{ fontFamily: "var(--mono)", fontSize: 14, color: "var(--muted)", marginTop: 18 }}>
                Context Dependency Scale™ · {score} / 24
              </div>
              <h1 style={{ fontFamily: "var(--serif)", fontSize: 54, lineHeight: 1.05, margin: "10px 0 0", color: result.color }}>{result.band}</h1>
            </div>

            <div className="card" style={{ marginTop: 36, padding: "32px 36px" }}>
              <div style={{ display: "flex", justifyContent: "space-between", fontSize: 13.5, color: "var(--muted)" }}>
                <span>You scored higher than</span>
                <span style={{ fontWeight: 700, color: result.color }}>{result.pct}% of people who took this</span>
              </div>
              <div className="result-meter">
                <div className="result-meter-fill" style={{ width: `${result.pct}%`, background: result.color }}></div>
              </div>
              <div className="result-scale">
                <span>mindful</span><span>mild</span><span>functional</span><span>acute</span>
              </div>
              <p style={{ fontSize: 17, lineHeight: 1.6, color: "var(--ink)", marginTop: 26 }}>{result.blurb}</p>
              <div style={{ marginTop: 22, padding: "18px 20px", background: "var(--sage-tint)", border: "1px solid var(--sage-soft)", borderRadius: "var(--radius)" }}>
                <div style={{ fontSize: 12.5, fontWeight: 700, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--sage-deep)", marginBottom: 6 }}>Suggested next step</div>
                <div style={{ fontSize: 15.5, color: "var(--ink)" }}>{result.rx}</div>
              </div>
            </div>

            <div style={{ display: "flex", gap: 12, marginTop: 24, justifyContent: "center", flexWrap: "wrap" }}>
              <Btn size="lg" onClick={() => navigate("counseling")}>Talk to a counselor <Icon name="arrow" size={16} /></Btn>
              <Btn variant="ghost" size="lg" onClick={() => { setDone(false); setStep(0); setAnswers({}); }}>Retake assessment</Btn>
            </div>
            <p style={{ textAlign: "center", fontSize: 12.5, color: "var(--faint)", marginTop: 22 }}>
              The Context Dependency Scale™ is not a diagnostic instrument. It is barely an instrument. Results are not stored.
            </p>
          </div>
        </section>
      </div>
    );
  }

  const cur = QUESTIONS[step];
  const picked = answers[step];
  const hasPick = picked !== undefined;

  return (
    <div className="screen">
      <section className="sec" style={{ paddingTop: 56 }}>
        <div className="wrap-narrow">
          <div style={{ textAlign: "center", marginBottom: 28 }}>
            <Eyebrow>Confidential self-assessment</Eyebrow>
          </div>
          <div className="card quiz-card">
            <div className="quiz-progress"><div className="quiz-progress-bar" style={{ width: `${(step / total) * 100}%` }}></div></div>
            <div className="quiz-body">
              <div className="quiz-step-label">Question {step + 1} of {total}</div>
              <div className="quiz-q">{cur.q}</div>
              <div className="quiz-options">
                {cur.opts.map(([label, val], i) => (
                  <button key={i} className={`quiz-opt${picked === i ? " sel" : ""}`}
                          onClick={() => setAnswers((a) => ({ ...a, [step]: i }))}>
                    <span className="quiz-opt-key">{"ABCD"[i]}</span>
                    {label}
                  </button>
                ))}
              </div>
            </div>
            <div className="quiz-foot">
              <Btn variant="ghost" onClick={() => step === 0 ? navigate("home") : setStep(step - 1)}>
                <Icon name="arrowL" size={16} /> {step === 0 ? "Exit" : "Back"}
              </Btn>
              <div style={{ display: "flex", gap: 6 }}>
                {QUESTIONS.map((_, i) => (
                  <div key={i} style={{ width: 7, height: 7, borderRadius: "50%", background: i === step ? "var(--sage-deep)" : answers[i] !== undefined ? "var(--sage)" : "var(--line-2)" }}></div>
                ))}
              </div>
              <Btn onClick={() => { if (!hasPick) return; step === total - 1 ? setDone(true) : setStep(step + 1); }}
                   style={{ opacity: hasPick ? 1 : 0.4, pointerEvents: hasPick ? "auto" : "none" }}>
                {step === total - 1 ? "See result" : "Next"} <Icon name="arrow" size={16} />
              </Btn>
            </div>
          </div>
        </div>
      </section>
    </div>
  );
}

/* ================================================================
   PARODY OPTIMIZATION TOOLS
================================================================ */
function BedtimeCalc() {
  const [tokens, setTokens] = useStateI(1200);
  const [hours, setHours] = useStateI(3);
  const perHour = Math.round(tokens / Math.max(hours, 0.5));
  const perPrompt = Math.max(1, Math.round(perHour / 12));
  const advice =
    perHour > 800 ? "Comfortable. You could ask real questions. You won't, but you could."
    : perHour > 350 ? "Tight but survivable. One thoughtful prompt per long-form thought. No regenerating."
    : perHour > 120 ? "Austerity measures. Compose prompts in full before sending. Abbreviate nothing the model needs."
    : "Critical. We gently suggest the radical intervention of going to sleep. The reset is closer than the floor.";
  return (
    <div className="card tool-card">
      <div className="tool-icon"><Icon name="moon" size={22} /></div>
      <h3>Bedtime Rationing Calculator</h3>
      <p>For when there are tokens left, but not enough to feel safe. Tells you precisely how thin to spread them until sleep.</p>
      <div style={{ display: "flex", flexDirection: "column", gap: 18, marginTop: 22 }}>
        <div className="field">
          <label>Tokens remaining <span className="hint">— {tokens.toLocaleString()}</span></label>
          <input className="range" type="range" min="50" max="5000" step="50" value={tokens} onChange={(e) => setTokens(+e.target.value)} />
        </div>
        <div className="field">
          <label>Hours until you'll actually sleep <span className="hint">— {hours}h</span></label>
          <input className="range" type="range" min="0.5" max="8" step="0.5" value={hours} onChange={(e) => setHours(+e.target.value)} />
        </div>
        <div className="readout">
          <div style={{ display: "flex", gap: 30 }}>
            <div>
              <div className="readout-num">{perHour.toLocaleString()}</div>
              <div style={{ fontSize: 12.5, color: "var(--muted)", marginTop: 4 }}>tokens / hour budget</div>
            </div>
            <div>
              <div className="readout-num">~{perPrompt}</div>
              <div style={{ fontSize: 12.5, color: "var(--muted)", marginTop: 4 }}>prompts / hour, roughly</div>
            </div>
          </div>
          <div className="readout-advice">{advice}</div>
        </div>
      </div>
    </div>
  );
}

function PromptEconomizer() {
  const [text, setText] = useStateI("Hey! I was just wondering if you could maybe possibly help me out with something when you get a chance, no rush at all, but basically I think I might need to understand this.");
  const trimmed = text
    .replace(/\b(hey|hi|hello|so|basically|just|maybe|possibly|please|kindly|i think|i was wondering if you could|when you get a chance|no rush at all|maybe possibly)\b/gi, "")
    .replace(/[!]+/g, ".")
    .replace(/\s+/g, " ")
    .replace(/\s+([.,])/g, "$1")
    .trim();
  const before = text.trim().split(/\s+/).filter(Boolean).length;
  const after = trimmed.split(/\s+/).filter(Boolean).length;
  const saved = Math.max(0, before - after);
  return (
    <div className="card tool-card">
      <div className="tool-icon"><Icon name="scissors" size={22} /></div>
      <h3>Prompt Economizer</h3>
      <p>Strips the pleasantries you extend to a language model. It does not have feelings. You can stop apologizing to it.</p>
      <div style={{ display: "flex", flexDirection: "column", gap: 14, marginTop: 22 }}>
        <div className="field">
          <label>Your prompt, as written</label>
          <textarea className="textarea" value={text} onChange={(e) => setText(e.target.value)} />
        </div>
        <div className="field">
          <label>The economical version <span className="hint">— {saved} words reclaimed</span></label>
          <div style={{ fontFamily: "var(--mono)", fontSize: 14.5, lineHeight: 1.55, padding: "14px 16px", background: "var(--surface-2)", border: "1px solid var(--line)", borderRadius: "var(--radius-sm)", minHeight: 60, color: "var(--ink)" }}>
            {trimmed || "(nothing left — that was all pleasantries)"}
          </div>
        </div>
        <div style={{ fontSize: 13, color: "var(--faint)", fontStyle: "italic" }}>
          Note: you will paste the original version anyway. We've made peace with this.
        </div>
      </div>
    </div>
  );
}

function Tools() {
  return (
    <div className="screen">
      <section className="sec" style={{ paddingTop: 64 }}>
        <div className="wrap">
          <div className="sec-head" style={{ maxWidth: 720 }}>
            <Eyebrow>Coping & rationing tools</Eyebrow>
            <h2>Stretch what's left, with dignity</h2>
            <p>These tools won't give you more tokens. Nothing gives you more tokens. They will, however, help you feel briefly in control — which is the next best thing.</p>
          </div>
          <div className="tool-grid">
            <BedtimeCalc />
            <PromptEconomizer />
            <ResetTimer />
            <UrgeSurfer />
          </div>
        </div>
      </section>
    </div>
  );
}

function ResetTimer() {
  const [now, setNow] = useStateI(new Date());
  useEffectI(() => { const id = setInterval(() => setNow(new Date()), 1000); return () => clearInterval(id); }, []);
  const next = new Date(now); next.setHours(now.getHours() + 1, 0, 0, 0);
  const ms = next - now;
  const m = Math.floor(ms / 60000); const s = Math.floor((ms % 60000) / 1000);
  return (
    <div className="card tool-card">
      <div className="tool-icon"><Icon name="clock" size={22} /></div>
      <h3>The Reset, Honestly</h3>
      <p>You check it compulsively, so here it is, large and calm, so you don't have to go looking. It always comes.</p>
      <div className="readout" style={{ marginTop: 22, textAlign: "center" }}>
        <div style={{ fontFamily: "var(--mono)", fontSize: 56, color: "var(--sage-deep)", fontVariantNumeric: "tabular-nums", lineHeight: 1 }}>
          {String(m).padStart(2, "0")}:{String(s).padStart(2, "0")}
        </div>
        <div className="readout-advice" style={{ textAlign: "center" }}>
          That's all. {m < 10 ? "Almost there. Don't spend it all at once." : "Long enough to step away. Genuinely, go outside."}
        </div>
      </div>
    </div>
  );
}

function UrgeSurfer() {
  const [surfing, setSurfing] = useStateI(false);
  const [left, setLeft] = useStateI(20);
  useEffectI(() => {
    if (!surfing) return;
    if (left <= 0) { setSurfing(false); return; }
    const id = setTimeout(() => setLeft((l) => l - 1), 1000);
    return () => clearTimeout(id);
  }, [surfing, left]);
  return (
    <div className="card tool-card">
      <div className="tool-icon"><Icon name="wave" size={22} /></div>
      <h3>Urge Surfer</h3>
      <p>Feel the urge to send "one more"? Urges peak and pass like waves. Ride this one out for 20 seconds without sending anything.</p>
      <div className="readout" style={{ marginTop: 22, textAlign: "center" }}>
        {surfing ? (
          <>
            <div style={{ fontFamily: "var(--serif)", fontSize: 52, color: "var(--sage-deep)", lineHeight: 1 }}>{left}</div>
            <div className="readout-advice" style={{ textAlign: "center" }}>The wave is cresting. Notice it. Do not paddle toward the keyboard.</div>
          </>
        ) : left === 0 ? (
          <>
            <div style={{ fontFamily: "var(--serif)", fontSize: 30, color: "var(--sage-deep)" }}>It passed.</div>
            <div className="readout-advice" style={{ textAlign: "center" }}>See? You didn't need to send it. <a onClick={() => setLeft(20)} style={{ color: "var(--sage-deep)", cursor: "pointer", textDecoration: "underline" }}>Surf again</a></div>
          </>
        ) : (
          <Btn onClick={() => setSurfing(true)}>Begin surfing the urge</Btn>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { Quiz, Tools });
