/* Buy section: the single self-paced Course offering → boxed detail panel.
   (Paid human services and the bundle were removed - only the $39 course is sold.) */

const PLANS = [
  {
    id: "course", icon: "code", name: "Course", price: "$39", per: "CAD · one-time",
    tagline: "Learn the whole playbook yourself, at your own pace.",
    highlights: ["All 6 program modules", "Templates, scripts & city guides", "Lifetime access + updates"],
  },
];

const COURSE = {
  icon: "code", tag: "Self-paced course", name: "Course", price: "$39", per: "CAD · one-time",
  cta: "Get the course", kind: "primary", title: "The complete playbook - six modules, zero filler",
  blurb: "Six modules that answer the questions nobody else does: why your applications vanish, how to get a referral when you know nobody in Canada, and how to negotiate when you feel you have no leverage.",
  points: ["All 6 modules - Foundation to signed offer", "Templates, scripts & city salary guides", "Lifetime access + all future updates"],
};

function Offerings() {
  const [modal, setModal] = useState(null);
  const user = useUser();
  const paid = !!(user && user.paid);
  // The "Course" plan opens the real all-modules reader instead of a modal.
  const open = (id) => {
    if (id === "course") { window.navigate("/learn"); return; }
    setModal(id);
  };
  const close = () => setModal(null);

  useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") close(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  useEffect(() => {
    document.body.style.overflow = modal ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [modal]);

  return (
    <section className="po-buy section" id="pricing">
      <div className="po-buy-glow" aria-hidden="true"></div>
      <div className="wrap">
        <div className="po-head reveal">
          <span className="eyebrow" style={{whiteSpace:"nowrap"}}><Icon name="spark" size={15} /> Ready to start</span>
          <h2>One payment. Everything you need.</h2>
          <p>No subscription - one payment, lifetime access. Tap the card to see what's inside.</p>
          <div className="po-buy-cta" style={{ display: "flex", gap: 12, flexWrap: "wrap", justifyContent: "center", marginTop: 18 }}>
            {!paid && <a href="/checkout" className="btn btn-primary"><Icon name="badge" size={16} /> Enroll - $39 CAD</a>}
            <a href="/learn/module-1" className="btn btn-ghost"><Icon name="play" size={16} /> Look inside - Module 1 is free</a>
          </div>
        </div>

        <div className="po-pcards reveal" role="list" aria-label="Plans">
          {PLANS.map((p) => (
            <button key={p.id} role="listitem"
              className={"po-pcard" + (modal === p.id ? " is-on" : "") + (p.best ? " is-best" : "")}
              onClick={() => open(p.id)}>
              {p.best && <span className="po-pcard-flag">Best value</span>}
              <span className="po-pcard-ic"><Icon name={p.icon} size={22} /></span>
              <h3 className="po-pcard-name">{p.name}</h3>
              <p className="po-pcard-tag">{p.tagline}</p>
              <div className="po-pcard-price">
                {p.oldPrice && <s>{p.oldPrice}</s>}<b>{p.price}</b><span>{p.per}</span>
              </div>
              <ul className="po-pcard-feats">
                {p.highlights.map((h) => (
                  <li key={h}><Icon name="check" size={15} stroke={2.6} /><span>{h}</span></li>
                ))}
              </ul>
              <span className="po-pcard-pick">
                {p.best
                  ? <><Icon name="spark" size={15} /> Get the course</>
                  : <>See what's inside <Icon name="arrow" size={15} /></>}
              </span>
            </button>
          ))}
        </div>
      </div>

      {modal && (
        <div className="po-modal-wrap" role="dialog" aria-modal="true">
          <div className="po-modal-bg" onClick={close} aria-hidden="true"></div>
          <div className="po-modal">
            <button className="po-modal-close" onClick={close} aria-label="Close">
              <Icon name="close" size={18} />
            </button>
            <div className="po-modal-body">
              {modal === "course" && <OfferingPanel o={COURSE}><CourseSyllabus /></OfferingPanel>}
            </div>
          </div>
        </div>
      )}
    </section>
  );
}

/* Shared boxed detail: header (icon/tag/title + price/CTA) + body (blurb/points + visual) */
function OfferingPanel({ o, children }) {
  return (
    <>
      <div className="po-svc-head">
        <div className="po-svc-id">
          <span className="po-svc-ic"><Icon name={o.icon} size={22} /></span>
          <div>
            <span className={"po-svc-tag" + (o.best ? " is-best" : "")}>{o.tag}</span>
            <h3>{o.name}</h3>
            <p>{o.title}</p>
          </div>
        </div>
        <div className="po-svc-buy">
          <div className="po-svc-price">
            {o.oldPrice && <span className="po-svc-old">{o.oldPrice}</span>}
            <b>{o.price}</b><span>{o.per}</span>
          </div>
          <a href="/checkout" className={"btn btn-" + o.kind}><Icon name={o.icon} size={16} /> {o.cta}</a>
        </div>
      </div>
      <div className="po-svc-body">
        <div className="po-svc-info">
          <p>{o.blurb}</p>
          <ul className="po-detail-points">
            {o.points.map((pt) => (
              <li key={pt}><Icon name="check" size={17} stroke={2.6} /><span>{pt}</span></li>
            ))}
          </ul>
        </div>
        <div className="po-svc-demo">{children}</div>
      </div>
    </>
  );
}

/* ---- Course syllabus visual ---- */
const MODULES = [
  ["Foundation", "Why your applications vanish - and the 3 real reasons you're not getting callbacks"],
  ["Positioning", "The 6 'foreign signals' that auto-reject your resume before a human ever sees it"],
  ["Network", "How to get a referral when you don't know a single person in Canada yet"],
  ["Interview", "What 'culture fit' really means here - and how to show it without overselling yourself"],
  ["Technical", "The patterns & one system-design framework that cover 80% of Canadian tech interviews"],
  ["The offer", "Negotiating when you feel you can't be picky - with real salary data by city and role"],
];
function CourseSyllabus() {
  return (
    <div className="po-syllabus card">
      <div className="po-syllabus-top mono">6 modules · self-paced · lifetime access</div>
      <ol className="po-syllabus-list">
        {MODULES.map((m, i) => (
          <li key={i}>
            <span className="po-syllabus-n mono">{String(i + 1).padStart(2, "0")}</span>
            <span className="po-syllabus-txt"><b>{m[0]}</b><span>{m[1]}</span></span>
          </li>
        ))}
      </ol>
      <a href="/learn/module-1" className="po-syllabus-preview mono">Read Module 1 free <Icon name="arrow" size={15} /></a>
    </div>
  );
}

/* ---- Resume demo (interactive ATS before/after) ---- */
const FIXES = [
  { bad: "Responsible for working on the frontend of the app", good: "Shipped 9 React features that cut page-load time 40%", issue: "No impact / metrics" },
  { bad: "Did backend tasks using various technologies", good: "Built Node/PostgreSQL APIs serving 1.2M requests/day", issue: "Vague, no stack" },
  { bad: "Worked in a team on different projects", good: "Led 4-engineer squad to deliver checkout rebuild on time", issue: "No ownership" },
];

function ResumeDemo() {
  const [after, setAfter] = useState(false);
  const score = after ? 96 : 54;
  return (
    <div className="po-resume-demo card">
      <div className="po-resume-toolbar">
        <span className="po-resume-file mono"><Icon name="doc" size={15} /> resume_v3.pdf</span>
        <div className="po-toggle" role="group" aria-label="Resume version">
          <button className={!after ? "on" : ""} onClick={() => setAfter(false)}>Before</button>
          <button className={after ? "on" : ""} onClick={() => setAfter(true)}>After</button>
        </div>
      </div>
      <div className="po-resume-body">
        <div className="po-resume-score">
          <Ring value={score} />
          <p>ATS match score</p>
          <span className={"po-resume-verdict " + (after ? "good" : "bad")}>
            {after ? "Recruiter-ready" : "Likely auto-rejected"}
          </span>
        </div>
        <ul className="po-resume-lines">
          {FIXES.map((f, i) => (
            <li key={i} className={after ? "fixed" : "broken"}>
              <span className="po-resume-mark"><Icon name={after ? "check" : "close"} size={14} stroke={2.6} /></span>
              <span className="po-resume-text">{after ? f.good : f.bad}</span>
              {!after && <span className="po-resume-issue">{f.issue}</span>}
            </li>
          ))}
        </ul>
      </div>
      <button className="po-resume-run" onClick={() => setAfter((v) => !v)}>
        <Icon name="spark" size={16} /> {after ? "Show the before" : "Run the fix"}
      </button>
    </div>
  );
}

function Ring({ value }) {
  const r = 46, c = 2 * Math.PI * r;
  const off = c * (1 - value / 100);
  const col = value >= 80 ? "var(--grow)" : "var(--accent)";
  return (
    <div className="po-ring">
      <svg viewBox="0 0 110 110" width="118" height="118">
        <circle cx="55" cy="55" r={r} fill="none" stroke="var(--line)" strokeWidth="9" />
        <circle cx="55" cy="55" r={r} fill="none" stroke={col} strokeWidth="9" strokeLinecap="round"
          strokeDasharray={c} strokeDashoffset={off} transform="rotate(-90 55 55)"
          style={{ transition: "stroke-dashoffset .9s cubic-bezier(.2,.8,.2,1), stroke .4s" }} />
      </svg>
      <span className="po-ring-num" style={{ color: col }}>{value}</span>
    </div>
  );
}

/* ---- Interview question explorer ---- */
const QBANK = {
  Behavioral: [
    { q: "Tell me about a time you disagreed with a teammate.", hint: "STAR: frame the Situation neutrally, focus the Action on how you found common ground, end on the Result and what you'd repeat." },
    { q: "Describe a project that failed. What happened?", hint: "Own the decision, show the data you missed, and land on the concrete process change you made afterward." },
  ],
  "System Design": [
    { q: "Design a URL shortener that scales to 1B links.", hint: "Clarify scale & read/write ratio first, then key generation, storage choice, caching, and how you'd shard." },
    { q: "How would you design a notification service?", hint: "Separate ingestion, fan-out, and delivery. Talk queues, idempotency, and per-channel rate limits." },
  ],
  Frontend: [
    { q: "Explain the browser rendering pipeline.", hint: "Walk DOM → CSSOM → render tree → layout → paint → composite, then where reflow vs. repaint bite performance." },
    { q: "How do you prevent unnecessary React re-renders?", hint: "Memoization, stable references, splitting state, and measuring with the Profiler before optimizing." },
  ],
  "Culture fit": [
    { q: "Why do you want to work in Canada specifically?", hint: "Tie your motivation to the team's work and long-term commitment - concrete beats generic gratitude." },
    { q: "How do you handle ambiguous requirements?", hint: "Show you ask clarifying questions, propose a small scope, and confirm before building." },
  ],
};

function InterviewExplorer() {
  const cats = Object.keys(QBANK);
  const [cat, setCat] = useState(cats[0]);
  const [openQ, setOpenQ] = useState(0);
  return (
    <div className="po-iv-explorer">
      <div className="po-iv-cats">
        {cats.map((c) => (
          <button key={c} className={"po-iv-cat" + (cat === c ? " on" : "")}
            onClick={() => { setCat(c); setOpenQ(0); }}>{c}</button>
        ))}
      </div>
      <div className="po-iv-list" key={cat}>
        {QBANK[cat].map((item, i) => (
          <button key={i} className={"po-iv-q card" + (openQ === i ? " open" : "")} onClick={() => setOpenQ(openQ === i ? -1 : i)}>
            <div className="po-iv-qhead">
              <span className="po-iv-qmark mono">Q{i + 1}</span>
              <span className="po-iv-qtext">{item.q}</span>
              <Icon name="arrowDown" size={18} style={{ transform: openQ === i ? "rotate(180deg)" : "none", transition: "transform .25s", flex: "none" }} />
            </div>
            <div className="po-iv-hint"><span><strong>Coach:</strong> {item.hint}</span></div>
          </button>
        ))}
      </div>
    </div>
  );
}

window.Offerings = Offerings;
window.Ring = Ring;
