/* TASK PREVIEW — AI_OUTPUT_REVIEW: fact-check AI draft against source */

const CLIENT_BRIEF = `A partner needs to fact-check an AI-generated FY24 financial summary for a buy-side diligence memo. Cross-reference the AI draft against the source data, then click any sentence in the draft to flag it as an error.`;

const SOURCE_ROWS = [
{ region: "Northeast", value: "23.9", note: "" },
{ region: "Southeast", value: "19.8", note: "up from 17.1 in FY23" },
{ region: "Midwest", value: "18.5", note: "" },
{ region: "West", value: "11.6", note: "includes $1.8M non-recurring institutional order" },
{ region: "International", value: "2.2", note: "" }];

const SOURCE_NOTE = "Note from management: West FY24 includes a one-time $1.8M order. True run-rate is closer to $9.8M.";

const AI_SENTENCES = [
{
  text: "Redmont Provisions reported $82M in total revenue across five operating regions in FY24, reflecting steady year-over-year growth.",
  isError: true,
  feedback: "Total revenue is $76M, not $82M."
},
{
  text: "The Southeast region declined from $17.1M in FY23 to $14.2M in FY24, signaling softening demand in the company's most competitive geography.",
  isError: true,
  feedback: "Southeast grew from $17.1M to $19.8M. The AI reversed the years."
},
{
  text: "The Midwest posted the strongest growth trajectory, expanding from $14.2M to $19.8M over the three-year window.",
  isError: false,
  feedback: "Midwest figures are accurate."
},
{
  text: "The West region's $11.6M performance includes a one-time $1.8M institutional order, putting true run-rate closer to $9.8M.",
  isError: false,
  feedback: "West figures and the non-recurring caveat are accurately disclosed."
},
{
  text: "International revenue contracted in FY24 following the loss of a single distribution partner.",
  isError: false,
  feedback: "International data is accurate."
}];


function MiniGame() {
  const [flags, setFlags] = React.useState([false, false, false, false, false]);
  const [submitted, setSubmitted] = React.useState(false);
  const [time, setTime] = React.useState(180); // 3 min
  const [running, setRunning] = React.useState(false);

  const totalErrors = AI_SENTENCES.filter((s) => s.isError).length;
  const flagCount = flags.filter(Boolean).length;

  React.useEffect(() => {
    if (!running || submitted) return;
    if (time <= 0) {
      setRunning(false);
      setSubmitted(true);
      return;
    }
    const t = setTimeout(() => setTime((t) => t - 1), 1000);
    return () => clearTimeout(t);
  }, [running, time, submitted]);

  const mm = String(Math.floor(time / 60)).padStart(2, "0");
  const ss = String(time % 60).padStart(2, "0");

  const start = () => setRunning(true);
  const reset = () => {
    setFlags([false, false, false, false, false]);
    setSubmitted(false);
    setRunning(false);
    setTime(180);
  };
  const toggleFlag = (i) => {
    if (submitted) return;
    // start timer on first interaction if not already running
    if (!running && time === 180) setRunning(true);
    const next = [...flags];
    next[i] = !next[i];
    setFlags(next);
  };
  const submit = () => {
    setSubmitted(true);
    setRunning(false);
  };

  // score: # of errors correctly caught
  const caughtErrors = AI_SENTENCES.reduce((acc, s, i) => acc + (s.isError && flags[i] ? 1 : 0), 0);

  return (
    <section id="preview" data-snap className="relative text-ink border-y-2 border-ink" style={{ background: "#FBF6EC" }}>
      <div className="relative max-w-[1400px] mx-auto px-5 md:px-8 py-20 md:py-28">
        <div className="flex items-center justify-between font-mono text-base md:text-lg mb-10 text-ink-2" aria-hidden="true">
          <span>03 / SIMULATION PREVIEW</span>
          <span>TASK: AI_OUTPUT_REVIEW · TRY IT</span>
        </div>

        {/* TOP ROW: heading + subhead side-by-side */}
        <div className="grid lg:grid-cols-12 gap-8 items-end mb-6">
          <div className="lg:col-span-7">
            <h2 className="font-display font-bold tracking-tight leading-[0.95] text-[52px] md:text-[76px] lg:text-[96px]">
              Try a <span className="text-orange">simulation.</span>
            </h2>
          </div>
          <div className="lg:col-span-5">
            <p className="text-lg md:text-xl text-ink-2">This is a simplified version of one scenario. You'll review an AI-generated analysis, cross-check it against the source data, and flag any errors. About 3 minutes.</p>
          </div>
        </div>

        {/* TASK BRIEF: full width */}
        <div className="mb-6 border-2 border-ink bg-cream text-ink p-6 hs-orange">
          <div className="font-mono text-xs mb-2 opacity-60">TASK BRIEF · CASE #R-204</div>
          <p className="font-mono text-[15px] leading-relaxed">{CLIENT_BRIEF}</p>
        </div>

        {/* SIDE-BY-SIDE: bare table on left, terminal window on right */}
        {!submitted &&
        <div className="grid lg:grid-cols-12 gap-6 items-start">
          {/* LEFT: SOURCE TABLE — no window chrome */}
          <div className="lg:col-span-5">
            <div className="flex items-center justify-between mb-3">
              <div className="font-mono text-xs text-ink font-bold tracking-wider">SOURCE · FY24 · USD MILLIONS</div>
            </div>
            <table className="w-full font-mono text-sm">
              <thead>
                <tr className="text-ink border-b border-ink/30">
                  <th className="text-left font-bold px-2 py-2">Region</th>
                  <th className="text-right font-bold px-2 py-2 w-16">FY24</th>
                </tr>
              </thead>
              <tbody>
                {SOURCE_ROWS.map((r) =>
                <React.Fragment key={r.region}>
                  <tr className={r.note ? "" : "border-b border-ink/15"}>
                    <td className="px-2 pt-2 pb-0.5 text-ink">{r.region}</td>
                    <td className="px-2 pt-2 pb-0.5 text-right text-ink tabular-nums">{r.value}</td>
                  </tr>
                  {r.note &&
                  <tr className="border-b border-ink/15">
                    <td colSpan={2} className="px-2 pb-2 text-ink-2 text-xs italic">⤷ {r.note}</td>
                  </tr>
                  }
                </React.Fragment>
                )}
                <tr>
                  <td className="px-2 py-2 font-bold text-ink">TOTAL</td>
                  <td className="px-2 py-2 text-right font-bold text-ink tabular-nums">76.0</td>
                </tr>
              </tbody>
            </table>
            <div className="mt-4 pt-3 border-t border-ink/20 font-mono text-xs text-ink-2 leading-relaxed">
              <span className="text-orange font-bold">!</span> {SOURCE_NOTE}
            </div>
          </div>

          {/* RIGHT: AI DRAFT TERMINAL WINDOW */}
          <div className="lg:col-span-7 border-2 border-ink hs-orange">
            <div className="flex items-center justify-between bg-cream text-ink px-3 py-2 border-b-2 border-ink">
              <div className="flex items-center gap-2 font-mono text-xs">
                <span className="w-3 h-3 bg-orange border border-ink" />
                <span className="w-3 h-3 bg-lime border border-ink" />
                <span className="w-3 h-3 bg-blue border border-ink" />
                <span className="ml-2">cubicle.exe — AI_OUTPUT_REVIEW</span>
              </div>
              <div className="font-mono text-[10px] text-ink/60">CASE #R-204</div>
            </div>

            <div className="bg-cream p-5 md:p-6">
              <div className="relative z-10">
                <div className="flex items-center justify-between mb-3">
                  <div className="font-mono text-xs text-ink font-bold tracking-wider">AI DRAFT · UNDER REVIEW</div>
                  <div className="font-mono text-[11px] text-ink-2">Click sentences to flag.</div>
                </div>
                <ul className="space-y-2">
                  {AI_SENTENCES.map((s, i) => {
                    const flagged = flags[i];
                    return (
                      <li key={i}>
                        <button
                          onClick={() => toggleFlag(i)}
                          disabled={submitted}
                          aria-pressed={flagged}
                          aria-label={`Flag as error: ${s.text}`}
                          className={`group w-full text-left flex gap-3 font-pixel text-lg leading-snug px-3 py-2.5 border-2 transition-colors cursor-pointer ${
                          flagged ?
                          "border-orange bg-orange/20 text-ink" :
                          "border-ink/25 text-ink hover:border-orange hover:bg-ink/5"}`}>

                          <span className={`shrink-0 mt-0.5 w-5 h-5 border-2 flex items-center justify-center font-mono text-xs leading-none ${flagged ? "border-orange bg-orange text-ink" : "border-ink/40 text-transparent group-hover:border-orange"}`}>
                            ⚑
                          </span>
                          <span className="flex-1">{s.text}</span>
                        </button>
                      </li>);
                  })}
                </ul>
              </div>
            </div>

            <div className="flex items-center justify-between bg-ink/5 text-ink-2 px-3 py-2 font-mono text-xs border-t-2 border-ink">
              <span>flags <span className="text-ink">{flagCount}/{totalErrors}</span></span>
              <button onClick={submit}
                className="font-mono text-xs uppercase border-2 border-ink text-ink hover:bg-ink hover:text-cream px-3 py-1">
                Submit review ↵
              </button>
            </div>
          </div>
        </div>
        }

        {/* RESULTS */}
        {submitted &&
        <div className="up-in bg-cream text-ink border-2 border-ink p-5">
          <div className="flex items-baseline justify-between mb-3">
            <div>
              <div className="font-mono text-[10px] opacity-60">FINAL SCORE · AUTO-EVALUATED</div>
              <div className="font-display font-bold text-3xl md:text-4xl leading-tight">
                <span className="text-orange">{caughtErrors}/{totalErrors}</span> errors caught
              </div>
            </div>
            <div className="hidden sm:flex items-center gap-3 font-mono text-[10px] uppercase tracking-wider">
              <span className="flex items-center gap-1.5"><span className="w-3 h-3 border-2 border-orange bg-orange/30 inline-block" /> Your call</span>
              <span className="flex items-center gap-1.5"><span className="w-3 h-3 border-2 border-ink bg-ink inline-block" /> Correct</span>
            </div>
          </div>

          <ul className="divide-y-2 divide-ink/10 border-2 border-ink/15">
            {AI_SENTENCES.map((s, i) => {
              const flagged = flags[i];
              const correct = s.isError ? flagged : !flagged;
              const youLabel = flagged ? "FLAG" : "OK";
              const correctLabel = s.isError ? "FLAG" : "OK";

              return (
                <li key={i} className={`flex items-center gap-3 px-3 py-2 ${correct ? "" : "bg-orange/10"}`}>
                  <span className={`shrink-0 w-5 h-5 border-2 flex items-center justify-center font-mono text-[11px] leading-none ${correct ? "border-ink/25 text-ink/40" : "border-orange bg-orange text-ink"}`}>
                    {correct ? "✓" : "✗"}
                  </span>
                  <span className="font-mono text-[10px] text-ink-2 shrink-0 w-6">S{i + 1}</span>
                  <span className="flex-1 min-w-0 text-[12px] leading-snug truncate" title={s.text}>{s.text}</span>
                  <span className="shrink-0 flex gap-1 font-mono text-[10px] uppercase tracking-wider">
                    <span className={`px-1.5 py-0.5 border-2 w-14 text-center ${correct ? "border-ink/20 text-ink/60" : "border-orange bg-orange/20 text-ink font-bold"}`}>
                      {youLabel}
                    </span>
                    <span className="px-1.5 py-0.5 border-2 border-ink bg-ink text-cream w-14 text-center font-bold">
                      {correctLabel}
                    </span>
                  </span>
                </li>);

            })}
          </ul>

          <div className="mt-4 flex flex-wrap gap-3">
            <a href="https://form.typeform.com/to/AQnu6FVK" target="_blank" rel="noopener noreferrer"
              className="inline-flex items-center gap-2 font-mono text-xs uppercase tracking-wider bg-orange text-cream border-2 border-ink px-4 py-2.5 hs-sm btn-chunky">
              Book a demo →
            </a>
            <button onClick={reset}
              className="font-mono text-xs uppercase border-2 border-ink px-4 py-2.5 hover:bg-ink hover:text-cream transition-colors">
              ↺ Try again
            </button>
          </div>
        </div>
        }
      </div>
    </section>);

}

window.MiniGame = MiniGame;
