/* eslint-disable */
// Long-form module reader — renders all the section kinds in data.js.

const { useState: rUseState, useEffect: rUseEffect, useRef: rUseRef } = React;

function ModuleReader({ module: mod, onComplete, onBack, completion, setCompletion }) {
  const [readPct, setReadPct] = rUseState(0);
  const ref = rUseRef(null);

  rUseEffect(() => {
    function onScroll() {
      const el = ref.current;
      if (!el) return;
      const top = el.getBoundingClientRect().top;
      const h = el.offsetHeight - window.innerHeight + 200;
      const scrolled = clamp(-top / h, 0, 1);
      setReadPct(Math.round(scrolled * 100));
    }
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, [mod.id]);

  rUseEffect(() => {
    window.scrollTo({ top: 0, behavior: "instant" });
  }, [mod.id]);

  return (
    <div ref={ref} className="module-reader">
      {/* Floating reading-progress rail */}
      <div className="reader-rail">
        <div className="reader-rail-fill" style={{ width: `${readPct}%` }}></div>
      </div>

      {/* HERO */}
      <ModuleHero mod={mod} />

      {/* BODY */}
      <article className="reader" style={{ paddingTop: 64, paddingBottom: 64 }}>
        {mod.sections.map((s, i) => (
          <SectionRenderer key={i} s={s} mod={mod} />
        ))}

        {/* Check-your-thinking */}
        {mod.check && (
          <div style={{ marginTop: 80 }}>
            <DiagDivider label="CHECK YOUR THINKING" />
            <CheckBlock mod={mod} completion={completion} setCompletion={setCompletion} />
          </div>
        )}

        {/* Foot nav */}
        <ModuleFootNav mod={mod} onBack={onBack} onComplete={onComplete} />
      </article>
    </div>
  );
}

/* ---------------------------------------------------------------- */

function ModuleHero({ mod }) {
  return (
    <section className="module-hero">
      <div className="container" style={{ paddingTop: 56, paddingBottom: 56 }}>
        <div className="row" style={{ justifyContent: "space-between", alignItems: "flex-start", flexWrap: "wrap", gap: 32 }}>
          <div className="stack gap-4" style={{ maxWidth: 720 }}>
            <span className="eyebrow">MODULE {mod.num} / 07 · {formatMinutes(mod.timeMin)} READ</span>
            <h1 className="display display-lg fade-up">{mod.title}</h1>
            <p className="lead fade-up d1" style={{ maxWidth: 620 }}>{mod.subtitle}</p>
          </div>

          <div className="hero-word fade-up d2" aria-hidden>
            <span>{mod.hero}</span>
          </div>
        </div>

        <div style={{ marginTop: 48 }}>
          <ImgSlot
            label={`module ${mod.num} hero — landscape, on-site imagery`}
            src={mod.cover}
            aspect="21 / 9"
            style={{ borderRadius: 4 }}
          />
        </div>
      </div>
    </section>
  );
}

/* ---------------------------------------------------------------- */

function SectionRenderer({ s, mod }) {
  switch (s.kind) {
    case "h2":
      return <h2 className="section-h2">{s.text}</h2>;
    case "p":
      return <p className="section-p">{s.text}</p>;
    case "p-bold":
      return <p className="section-p section-p-bold">{s.text}</p>;
    case "list":
      return (
        <ul className="section-list">
          {s.items.map((it, i) => <li key={i}><span className="dash">—</span>{it}</li>)}
        </ul>
      );
    case "numbered":
      return (
        <ol className="section-numbered">
          {s.items.map((it, i) => (
            <li key={i}>
              <span className="num mono">{String(i + 1).padStart(2, "0")}</span>
              <span>{it}</span>
            </li>
          ))}
        </ol>
      );
    case "pullquote":
      return (
        <blockquote className="section-pullquote">
          <span className="quote-mark">"</span>
          <p>{s.text}</p>
        </blockquote>
      );
    case "takeaway":
      return (
        <div className="section-takeaway corner-frame">
          <span className="eyebrow">KEY TAKEAWAY · MODULE {mod.num}</span>
          <p>{s.text}</p>
        </div>
      );
    case "twoCol":
      return (
        <div className="section-twocol">
          <div className="col">
            <span className="eyebrow eyebrow-dim">SERVING</span>
            <p className="display display-sm">{s.left.text}</p>
            <span className="mute body-sm">{s.left.label} customer</span>
          </div>
          <div className="col col-accent">
            <span className="eyebrow">CARING</span>
            <p className="display display-sm">{s.right.text}</p>
            <span className="accent body-sm">{s.right.label} customer</span>
          </div>
        </div>
      );
    case "compareTable":
      return <CompareTable rows={s.rows} />;
    case "readGrid":
      return <ReadGrid groups={s.groups} />;
    case "languages":
      return <LanguageStrip items={s.items} />;
    case "layers":
      return <Layers items={s.items} />;
    case "swap":
      return <SwapRows rows={s.rows} />;
    case "tripleBig":
      return <TripleBig items={s.items} />;
    case "autopilotPairs":
      return <AutopilotPairs items={s.items} />;
    case "scenarioPlayer":
      return <ScenarioPlayer scenarios={mod.scenarios} />;
    case "commitmentPicker":
      return <CommitmentPicker />;
    default:
      return null;
  }
}

/* ---------------------------------------------------------------- */

function CompareTable({ rows }) {
  return (
    <div className="compare-table">
      <div className="compare-head">
        <div className="compare-c0"><span className="eyebrow eyebrow-dim">SITUATION</span></div>
        <div className="compare-c1"><span className="eyebrow eyebrow-dim">SERVING</span></div>
        <div className="compare-c2"><span className="eyebrow">CARING</span></div>
      </div>
      {rows.map((r, i) => (
        <div className="compare-row" key={i}>
          <div className="compare-c0">{r.situation}</div>
          <div className="compare-c1">{r.serving}</div>
          <div className="compare-c2">{r.caring}</div>
        </div>
      ))}
    </div>
  );
}

function ReadGrid({ groups }) {
  return (
    <div className="read-grid">
      {groups.map((g, i) => (
        <div className="read-group" key={i}>
          <div className="read-group-head">
            <span className="mono num">{String(i + 1).padStart(2, "0")}</span>
            <span className="display display-sm" style={{ fontSize: 24 }}>{g.label}</span>
          </div>
          <ul>
            {g.items.map((it, j) => <li key={j}>{it}</li>)}
          </ul>
        </div>
      ))}
    </div>
  );
}

function LanguageStrip({ items }) {
  const [pressed, setPressed] = rUseState(null);
  return (
    <div className="lang-strip">
      {items.map((it, i) => (
        <button
          key={i}
          className={`lang-card ${pressed === i ? "pressed" : ""}`}
          onClick={() => setPressed(i)}
        >
          <span className="eyebrow eyebrow-dim">{it.lang}</span>
          <span className="display display-sm" style={{ fontSize: 28 }}>{it.phrase}</span>
          <span className="mute body-sm">{it.note}</span>
          <span className="say-hint mono">{pressed === i ? "✓ TRY IT" : "TAP"}</span>
        </button>
      ))}
    </div>
  );
}

function Layers({ items }) {
  return (
    <div className="layers">
      {items.map((it, i) => (
        <div className="layer" key={i}>
          <div className="layer-num">
            <span className="mono">{it.num}</span>
            <div className="layer-line"></div>
          </div>
          <div className="layer-body">
            <span className="eyebrow">{it.label.toUpperCase()}</span>
            <p>{it.text}</p>
          </div>
        </div>
      ))}
    </div>
  );
}

function SwapRows({ rows }) {
  return (
    <div className="swap-rows">
      {rows.map((r, i) => (
        <div className="swap-row" key={i}>
          <div className="swap-from">
            <span className="eyebrow eyebrow-dim">DELETE</span>
            <p style={{ textDecoration: "line-through", textDecorationColor: "var(--err)" }}>{r.from}</p>
          </div>
          <div className="swap-arrow mono">→</div>
          <div className="swap-to">
            <span className="eyebrow">REPLACE WITH</span>
            <p>{r.to}</p>
          </div>
        </div>
      ))}
    </div>
  );
}

function TripleBig({ items }) {
  return (
    <div className="triple-big">
      {items.map((it, i) => (
        <div className="triple-cell" key={i}>
          <div className="triple-num mono">{it.num}</div>
          <div className="triple-word">{it.word}</div>
          <p className="triple-desc">{it.text}</p>
        </div>
      ))}
    </div>
  );
}

function AutopilotPairs({ items }) {
  return (
    <div className="autopilot-pairs">
      {items.map((it, i) => (
        <div className="autopilot-pair" key={i}>
          <div className="autopilot-q">
            <span className="eyebrow eyebrow-dim">CUSTOMER</span>
            <p className="display display-sm" style={{ fontSize: 22 }}>{it.q}</p>
          </div>
          <div className="autopilot-bodies">
            <div className="autopilot-body autopilot-bad">
              <span className="eyebrow eyebrow-dim">AUTOPILOT</span>
              <p>{it.autopilot}</p>
            </div>
            <div className="autopilot-body autopilot-good">
              <span className="eyebrow">3-SECOND ANSWER</span>
              <p>{it.caring}</p>
            </div>
          </div>
        </div>
      ))}
    </div>
  );
}

/* ---------------------------------------------------------------- */
// CHECK YOUR THINKING — module-specific micro interaction
/* ---------------------------------------------------------------- */

function CheckBlock({ mod, completion, setCompletion }) {
  const checked = completion.checks[mod.id];

  const c = mod.check;
  // Default text check (Module 1)
  if (!c.kind || c.kind === undefined) {
    return <TextCheck c={c} mod={mod} done={checked} setCompletion={setCompletion} />;
  }
  if (c.kind === "mcq") return <McqCheck c={c} mod={mod} done={checked} setCompletion={setCompletion} />;
  if (c.kind === "noticing") return <NoticingCheck mod={mod} done={checked} setCompletion={setCompletion} />;
  if (c.kind === "swap-game") return <SwapGame mod={mod} done={checked} setCompletion={setCompletion} />;
  if (c.kind === "three-sec") return <ThreeSecGame mod={mod} done={checked} setCompletion={setCompletion} />;
  return null;
}

function TextCheck({ c, mod, done, setCompletion }) {
  const [val, setVal] = rUseState("");
  const [submitted, setSubmitted] = rUseState(!!done);
  return (
    <div className="check-block">
      <span className="eyebrow">PAUSE & REFLECT</span>
      <p className="display display-sm" style={{ marginTop: 8 }}>{c.prompt}</p>
      <textarea
        className="check-textarea"
        rows={3}
        value={val}
        placeholder={c.placeholder}
        onChange={(e) => setVal(e.target.value)}
        disabled={submitted}
      />
      {!submitted ? (
        <button
          className="btn btn-primary"
          disabled={val.trim().length < 8}
          onClick={() => {
            setSubmitted(true);
            setCompletion((p) => ({ ...p, checks: { ...p.checks, [mod.id]: true } }));
          }}
        >
          SUBMIT REFLECTION <span className="arr">→</span>
        </button>
      ) : (
        <div className="check-feedback">
          <span className="eyebrow">SAMPLE ANSWER</span>
          <p>{c.sampleAnswer || "Thank you for taking a moment to reflect."}</p>
        </div>
      )}
    </div>
  );
}

function McqCheck({ c, mod, done, setCompletion }) {
  const [picked, setPicked] = rUseState(null);
  return (
    <div className="check-block">
      <span className="eyebrow">CHECK YOUR THINKING</span>
      <p className="display display-sm" style={{ marginTop: 8 }}>{c.prompt}</p>
      <div className="mcq-grid">
        {c.options.map((o) => {
          const active = picked === o.id;
          const correct = o.id === c.correct;
          const showFeedback = picked !== null;
          let state = "";
          if (showFeedback) {
            if (correct) state = "right";
            else if (active && !correct) state = "wrong";
          }
          return (
            <button
              key={o.id}
              className={`mcq-opt ${active ? "picked" : ""} ${state}`}
              onClick={() => {
                if (picked) return;
                setPicked(o.id);
                if (o.id === c.correct) {
                  setCompletion((p) => ({ ...p, checks: { ...p.checks, [mod.id]: true } }));
                }
              }}
            >
              <span className="mcq-letter mono">{o.id.toUpperCase()}</span>
              <span>{o.text}</span>
              {state === "right" && <span className="mcq-mark">✓</span>}
              {state === "wrong" && <span className="mcq-mark wrong">✕</span>}
            </button>
          );
        })}
      </div>
      {picked && (
        <div className="check-feedback">
          <span className="eyebrow">{picked === c.correct ? "EXACTLY" : "NOT QUITE"}</span>
          <p>{picked === c.correct
            ? "Attention to the person — not just the task — is the heart of caring."
            : "The right answer is paying attention to the person, not just the task. Caring takes the same time as serving — it just sees the human."}</p>
        </div>
      )}
    </div>
  );
}

function NoticingCheck({ mod, done, setCompletion }) {
  // Hand-tuned positions so labels don't collide. `up: true` puts the label
  // above the dot (use for cues near the bottom of the image).
  const cues = [
    { id: "passport", text: "Passport in bag",         x: 14, y: 24 },
    { id: "camera",   text: "Camera around neck",      x: 42, y: 12 },
    { id: "lang",     text: "Family speaking Tagalog", x: 78, y: 22 },
    { id: "badge",    text: "Birthday badge",          x: 22, y: 44 },
    { id: "ring",     text: "Fresh wedding band",      x: 56, y: 42 },
    { id: "limp",     text: "Slight limp",             x: 36, y: 64, up: true },
    { id: "tired",    text: "Tired toddler",           x: 74, y: 66, up: true },
    { id: "stroller", text: "Folded stroller",         x: 18, y: 80, up: true },
  ];
  const [picked, setPicked] = rUseState({});
  const got = Object.values(picked).filter(Boolean).length;
  return (
    <div className="check-block">
      <span className="eyebrow">CHECK YOUR EYE</span>
      <p className="display display-sm" style={{ marginTop: 8 }}>You see this family approaching. What would you notice in 5 seconds?</p>

      <div className="notice-stage">
        <ImgSlot label="family approaching · 5-second-glance composition" src="assets/m03-notice.jpeg" aspect="16 / 7" />
        <div className="notice-overlay">
          {cues.map((c, i) => (
            <button
              key={c.id}
              className={`notice-cue ${picked[c.id] ? "on" : ""} ${c.up ? "notice-cue-up" : ""}`}
              style={{ left: `${c.x}%`, top: `${c.y}%` }}
              onClick={() => {
                setPicked((p) => ({ ...p, [c.id]: !p[c.id] }));
                setCompletion((pp) => ({ ...pp, checks: { ...pp.checks, [mod.id]: true } }));
              }}
            >
              <span className="notice-dot"></span>
              <span className="notice-label">{c.text}</span>
            </button>
          ))}
        </div>
      </div>

      <div className="notice-foot">
        <span className="eyebrow eyebrow-dim">SPOTTED · <span className="accent">{got}</span> / {cues.length}</span>
        <span className="body-sm mute">There are no wrong picks — caring starts with noticing.</span>
      </div>
    </div>
  );
}

function SwapGame({ mod, done, setCompletion }) {
  const pairs = [
    { id: 1, from: "\"I do not know.\"", to: "\"Let me find that out for you right now.\"" },
    { id: 2, from: "\"That's not my section.\"", to: "\"My colleague there will know. Let me walk you over.\"" },
    { id: 3, from: "\"You'll have to ask someone else.\"", to: "\"Give me one moment — I want to tell you the right thing.\"" },
  ];
  const [picked, setPicked] = rUseState({}); // {fromId: toId}
  const [active, setActive] = rUseState(null);

  const correct = pairs.every((p) => picked[p.id] === p.id);
  rUseEffect(() => {
    if (correct) setCompletion((pp) => ({ ...pp, checks: { ...pp.checks, [mod.id]: true } }));
  }, [correct]);

  function pickTo(toId) {
    if (active == null) return;
    setPicked((p) => ({ ...p, [active]: toId }));
    setActive(null);
  }

  const usedTos = new Set(Object.values(picked));

  return (
    <div className="check-block">
      <span className="eyebrow">CHECK YOUR PHRASES</span>
      <p className="display display-sm" style={{ marginTop: 8 }}>Match each closed door with the open one.</p>

      <div className="swap-game">
        <div className="swap-col">
          <span className="eyebrow eyebrow-dim">CLOSED</span>
          {pairs.map((p) => {
            const linked = picked[p.id];
            return (
              <button
                key={p.id}
                className={`swap-chip ${active === p.id ? "active" : ""} ${linked ? "linked" : ""} ${linked && linked === p.id ? "right" : linked ? "wrong" : ""}`}
                onClick={() => setActive(p.id)}
              >
                <span className="mono num">{String(p.id).padStart(2, "0")}</span>
                {p.from}
              </button>
            );
          })}
        </div>
        <div className="swap-col">
          <span className="eyebrow">OPEN</span>
          {pairs.map((p) => {
            const used = usedTos.has(p.id);
            return (
              <button
                key={p.id}
                className={`swap-chip swap-chip-to ${used ? "used" : ""}`}
                onClick={() => pickTo(p.id)}
              >
                {p.to}
                <span className="mono num">{String(p.id).padStart(2, "0")}</span>
              </button>
            );
          })}
        </div>
      </div>

      {correct && (
        <div className="check-feedback">
          <span className="eyebrow">DOOR OPEN</span>
          <p>Every closed-door phrase has an open-door version that costs the same effort. Memorise these four.</p>
        </div>
      )}
    </div>
  );
}

function ThreeSecGame({ mod, done, setCompletion }) {
  const steps = [
    { num: "01", word: "SCAN", correct: "see", options: [
      { id: "see", text: "What do I see about this person or group?" },
      { id: "fix", text: "What's the policy on this?" },
      { id: "next", text: "What's next on my checklist?" },
    ]},
    { num: "02", word: "THINK", correct: "need", options: [
      { id: "need", text: "What might they need that they haven't asked for?" },
      { id: "rule", text: "What does the manual say?" },
      { id: "fast", text: "How fast can I finish this?" },
    ]},
    { num: "03", word: "ACT", correct: "extra", options: [
      { id: "extra", text: "What is one small thing I can offer beyond their question?" },
      { id: "min", text: "How can I give the minimum required answer?" },
      { id: "pass", text: "Who can I pass this customer to?" },
    ]},
  ];
  const [picks, setPicks] = rUseState({});
  const allRight = steps.every((s) => picks[s.num] === s.correct);
  rUseEffect(() => {
    if (allRight) setCompletion((pp) => ({ ...pp, checks: { ...pp.checks, [mod.id]: true } }));
  }, [allRight]);
  return (
    <div className="check-block">
      <span className="eyebrow">CHECK THE RULE</span>
      <p className="display display-sm" style={{ marginTop: 8 }}>Pick the right question for each step.</p>
      <div className="three-sec-game">
        {steps.map((s) => (
          <div className="three-sec-step" key={s.num}>
            <div className="three-sec-head">
              <span className="mono num">{s.num}</span>
              <span className="display display-sm" style={{ color: "var(--accent)", fontSize: 32 }}>{s.word}</span>
            </div>
            <div className="three-sec-opts">
              {s.options.map((o) => {
                const picked = picks[s.num] === o.id;
                const right = picked && o.id === s.correct;
                const wrong = picked && o.id !== s.correct;
                return (
                  <button
                    key={o.id}
                    className={`three-sec-opt ${right ? "right" : ""} ${wrong ? "wrong" : ""}`}
                    onClick={() => setPicks((p) => ({ ...p, [s.num]: o.id }))}
                  >
                    {o.text}
                  </button>
                );
              })}
            </div>
          </div>
        ))}
      </div>
      {allRight && (
        <div className="check-feedback">
          <span className="eyebrow">YOU GOT IT</span>
          <p>Three seconds is all it takes. The tiny pause between a robot and a human.</p>
        </div>
      )}
    </div>
  );
}

/* ---------------------------------------------------------------- */

function ModuleFootNav({ mod, onBack, onComplete }) {
  return (
    <div className="module-foot">
      <button className="btn btn-ghost" onClick={onBack}>
        <span className="arr" style={{ transform: "rotate(180deg)" }}>→</span> BACK TO CURRICULUM
      </button>
      <button className="btn btn-primary btn-lg" onClick={onComplete}>
        COMPLETE MODULE {mod.num} <span className="arr">→</span>
      </button>
    </div>
  );
}

Object.assign(window, { ModuleReader });
