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

/* ============================================================
   RESOURCE GUIDE — Components
   Config-driven template. Populate `config` in index.html.
   ============================================================ */

/* ---------- utilities ---------- */
const asNum = (i) => String(i + 1).padStart(2, "0");
const asWord = (i) => ["one.", "two.", "three.", "four.", "five.", "six."][i] || `${i + 1}.`;

/* ---------- Hero ---------- */
const Hero = ({ cfg, numberStyle }) => {
  const bgClass = `bg-${cfg.heroBg || "butter"}`;
  return (
    <section className={`rg-hero ${bgClass}`} id="top">
      <div className="rg-hero-inner">
        <div>
          <div className="rg-hero-date">
            <span className="ie-dot-sm" />
            {cfg.courseSubtitle}
            <span className="ie-dot-sm" />
            {cfg.courseDate}
          </div>
          <h1 dangerouslySetInnerHTML={{ __html: cfg.heroHeadline }} />
          <p className="rg-hero-sub">{cfg.heroSubhead}</p>
          <p className="rg-hero-body">{cfg.heroBody}</p>
          <div className="rg-hero-nohoop">
            No email required <span>·</span> No hoops <span>·</span> Just take it
          </div>
        </div>
        <div className="rg-hero-art">
          <img src={cfg.heroArt || "assets/art/heart-glasses-yellow.png"} alt="" />
        </div>
      </div>
    </section>
  );
};

/* ---------- Jump links ---------- */
const JumpLinks = ({ resources, showBonus, bonus }) => (
  <div className="rg-jump">
    <div className="rg-jump-inner">
      <span className="rg-jump-label">Jump to</span>
      <div className="rg-jump-links">
        {resources.filter(r => r.enabled !== false).map((r, i) => (
          <a key={i} href={`#resource-${i}`}>{asNum(i)} · {r.shortTitle || r.title}</a>
        ))}
        {showBonus && bonus && <a href="#bonus">★ {bonus.shortTitle || "Bonus"}</a>}
        <a href="#connect">Stay in touch</a>
      </div>
    </div>
  </div>
);

/* ---------- Resource Head (number + title) ---------- */
const ResourceHead = ({ index, resource, numberStyle }) => {
  return (
    <div className={`rg-rhead num-${numberStyle}`}>
      <span
        className="rg-rnum"
        data-num={asNum(index)}
        data-word={asWord(index)}
      >
        <span className="ie-dot-sm" />
        <span className="label">Resource {asNum(index)}</span>
      </span>
      <h2 className="rg-rtitle" dangerouslySetInnerHTML={{ __html: resource.title }} />
      {resource.subhead && <p className="rg-rsub">{resource.subhead}</p>}
    </div>
  );
};

/* ---------- Slide deck preview (visual for Resource 1) ---------- */
const SlideDeckPreview = ({ cfg, resource }) => {
  const href = resource?.pdfHref;
  const downloadName = resource?.pdfFilename;
  const pages = resource?.pageCount;
  const size = resource?.fileSize;
  const card = (
    <div className="rg-preview-card">
      <div className="rg-preview-slide">
        <div className="rg-preview-slide-eye">{cfg.courseSubtitle}</div>
        <h3 className="rg-preview-slide-h">
          SUSTAINABLE<br />CONTENT<br /><span className="script">systems</span>
        </h3>
        <div className="rg-preview-slide-foot">{cfg.courseDate} · HERHAUS · DENVER</div>
      </div>
      <div className="rg-preview-meta">
        <span>PDF{pages ? ` · ${pages} slides` : ""}</span>
        <span>↓ {size || "—"}</span>
      </div>
    </div>
  );
  if (!href) return card;
  return (
    <a href={href} download={downloadName || true} className="rg-preview-link" aria-label="Download slide deck">
      {card}
    </a>
  );
};

/* ---------- Phone-framed video player ---------- */
const VideoPhone = ({ src, caption }) => (
  <div className="rg-video-phone-wrap">
    <div className="rg-video-phone">
      <div className="rg-video-phone-notch" />
      <video
        className="rg-video-phone-media"
        src={src}
        controls
        playsInline
        preload="metadata"
      />
    </div>
    {caption && <div className="rg-video-phone-caption">{caption}</div>}
  </div>
);

/* ---------- iPhone frame (install prompt mock) ---------- */
const PhoneFrame = () => (
  <div className="rg-phone-wrap">
    <div className="rg-phone">
      <div className="rg-phone-notch" />
      <div className="rg-phone-screen">
        <div className="rg-phone-statusbar">
          <span className="rg-time">9:41</span>
          <span>􀋦 􀛨 􀛩</span>
        </div>
        <div style={{ flex: 1, padding: "24px 20px", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", background: "linear-gradient(180deg, #faf5ec 0%, #f5ecd5 100%)" }}>
          <div style={{ fontFamily: "var(--font-display)", fontSize: 18, textTransform: "uppercase", color: "var(--ie-sienna)", fontWeight: 700, letterSpacing: "-0.005em", textAlign: "center", lineHeight: 1.05 }}>
            Voice Note<br />Capture
          </div>
          <div style={{ fontFamily: "var(--font-script)", fontSize: 28, color: "var(--ie-sienna)", marginTop: 4 }}>shortcut</div>
        </div>
        <div className="rg-phone-sheet">
          <div className="rg-phone-sheet-title">Add Shortcut</div>
          <div className="rg-phone-sheet-sub">inspiredefficiency.com</div>
          <div className="rg-phone-shortcut-card">
            <div className="rg-phone-shortcut-icon">⚡️</div>
            <div className="rg-phone-shortcut-meta">
              <b>Voice Note Capture</b>
              <span>By Sam · Inspired Efficiency</span>
            </div>
          </div>
          <button className="rg-phone-btn">Add Shortcut</button>
          <button className="rg-phone-btn secondary">Cancel</button>
        </div>
      </div>
    </div>
  </div>
);

/* ---------- Phone home / shortcuts library placeholder ---------- */
const PhonePlaceholder = ({ label }) => (
  <div className="rg-placeholder" style={{ minHeight: 180 }}>
    {label || "Screenshot placeholder"}
    <span className="sub">Swap in your real screenshot before launch</span>
  </div>
);

/* ---------- Notes list mock ---------- */
const NotesMock = () => (
  <div className="rg-notes-mock">
    <div className="rg-notes-mock-head">
      <div className="rg-notes-mock-title">Week of April 14 — Captures</div>
      <div className="rg-notes-mock-date">7 items</div>
    </div>
    <ul>
      <li>Mon morning — thing about onboarding being about nervous system<span className="dur">1:24</span></li>
      <li>Tue walk — the "three tabs" metaphor, develop this<span className="dur">0:48</span></li>
      <li>Wed — why AI slop sucks, framing: sovereignty<span className="dur">2:11</span></li>
      <li>Thu shower — idea for newsletter intro<span className="dur">0:36</span></li>
      <li>Fri meeting aftermath — pricing language rant<span className="dur">3:02</span></li>
      <li>Sat morning coffee — post structure idea<span className="dur">1:18</span></li>
      <li>Sun brain dump — launch sequence outline<span className="dur">4:47</span></li>
    </ul>
  </div>
);

/* ---------- Raw doc mock ---------- */
const RawDocMock = () => (
  <div className="rg-raw-mock">
    <h5>Week of April 14 — Content Captures</h5>
    <p>ok so i keep coming back to this idea that onboarding isn't really about the tech stack it's about the nervous system. like the reason people fall off isn't because the tool is confusing it's because they've never been shown how to actually <em>belong</em> in their own business...</p>
    <p>also — three tabs. three tabs. three tabs. this keeps happening. everyone i talked to this week has the exact same issue, notes scattered across three google docs, six emails to themselves, two apple notes — (that's literally me too lol)</p>
    <p>pricing thing — we need to stop talking about value-based pricing like it's a formula. it's not. it's a relationship.</p>
  </div>
);

/* ---------- Claude interface mock ---------- */
const ClaudeMock = () => (
  <div className="rg-claude-mock">
    <div className="rg-claude-mock-head">
      <div className="rg-claude-mock-dot">C</div>
      <div className="rg-claude-mock-title">Claude · new conversation</div>
    </div>
    <div className="rg-claude-bubble you">
      Here are my raw content captures from this week. I need you to turn this into a weekly content brief...
    </div>
    <div className="rg-claude-bubble">
      <b>Here are the 3–5 strongest threads from your captures this week:</b><br />
      <br />
      <b>1. "Three tabs" as a metaphor for scattered attention</b> — this one kept surfacing. Best format: short video or carousel post. Hook: "If you have three tabs open right now..."<br />
      <br />
      <b>2. Onboarding as nervous-system work</b> — the strongest and most original thread. Best format: newsletter...
    </div>
  </div>
);

/* ---------- Prompt snippet with copy ---------- */
const PromptSnippet = ({ children, prompt }) => {
  const [copied, setCopied] = useState(false);
  const [expanded, setExpanded] = useState(false);
  const doCopy = () => {
    navigator.clipboard.writeText(prompt);
    setCopied(true);
    setTimeout(() => setCopied(false), 1800);
  };
  return (
    <div className={`rg-prompt ${expanded ? "is-expanded" : ""}`}>
      <div className="rg-prompt-head">
        <span className="rg-prompt-label">Copy this prompt</span>
        <button className={`rg-prompt-copy ${copied ? "copied" : ""}`} onClick={doCopy}>
          {copied ? "Copied ✓" : "Copy"}
        </button>
      </div>
      <div className="rg-prompt-body">{children}</div>
      <button
        className="rg-prompt-toggle"
        onClick={() => setExpanded(v => !v)}
        aria-expanded={expanded}
        aria-label={expanded ? "Collapse prompt" : "Expand prompt"}
      >
        <span className="caret">{expanded ? "▲" : "▼"}</span>
      </button>
    </div>
  );
};

/* ---------- Step (inline guide) ---------- */
const InlineStep = ({ num, children }) => (
  <div className="rg-step">
    <div className="rg-step-num">{asNum(num - 1)}</div>
    <div className="rg-step-body">{children}</div>
  </div>
);

/* ---------- Button renderer from config ---------- */
const ActionButtons = ({ actions }) => {
  if (!actions || !actions.length) return null;
  return (
    <div className="rg-actions">
      {actions.map((a, i) => (
        <a
          key={i}
          href={a.href}
          className={`rg-btn rg-btn-${a.variant || "primary"} ${a.arrow ? "rg-arrow" : ""}`}
          target={a.external ? "_blank" : undefined}
          rel={a.external ? "noreferrer noopener" : undefined}
          download={a.download || undefined}
        >
          {a.label}
        </a>
      ))}
    </div>
  );
};

/* ============================================================
   RESOURCE CARDS — one per "kind"
   Kinds: link, download, ios-shortcut, video, inline-guide,
          prompt, skill
   ============================================================ */

const ResourceLink = ({ resource }) => (
  <div className="rg-twocol">
    <div className="rg-rtext">
      <p className="rg-rbody">{resource.body}</p>
      <ActionButtons actions={resource.actions} />
    </div>
    <div className="rg-rvisual">
      {resource.visual === "slide-deck" ? <SlideDeckPreview cfg={window.__cfg} resource={resource} /> : (
        <div className="rg-preview-card">
          <div className="rg-preview-slide" style={{ background: "var(--ie-butter)", color: "var(--ie-sienna)" }}>
            <div className="rg-preview-slide-eye" style={{ color: "var(--ie-sienna)" }}>{resource.kind || "External"}</div>
            <h3 className="rg-preview-slide-h" style={{ color: "var(--ie-sienna)" }}>{resource.shortTitle || resource.title}</h3>
            <div className="rg-preview-slide-foot" style={{ color: "var(--ie-sienna-deep)" }}>Opens in new tab →</div>
          </div>
        </div>
      )}
    </div>
  </div>
);

const ResourceDownload = ({ resource }) => (
  <div className="rg-twocol flip">
    <div className="rg-rtext">
      <p className="rg-rbody">{resource.body}</p>
      <ActionButtons actions={resource.actions} />
    </div>
    <div className="rg-rvisual">
      <div className="rg-preview-card on-butter" style={{ background: "var(--ie-butter)" }}>
        <div style={{ fontFamily: "var(--font-ui)", fontSize: 11, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--ie-sienna)", fontWeight: 700, marginBottom: 10 }}>
          {resource.fileKind || "PDF Download"}
        </div>
        <div style={{ fontFamily: "var(--font-display)", fontSize: 30, textTransform: "uppercase", color: "var(--ie-sienna)", fontWeight: 700, lineHeight: 0.95, marginBottom: 10 }}>
          {resource.shortTitle || resource.title}
        </div>
        <div style={{ fontFamily: "var(--font-serif)", fontSize: 15, color: "var(--ie-sienna-deep)", marginBottom: 20, fontStyle: "italic" }}>
          {resource.fileMeta || "Ready to download"}
        </div>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", paddingTop: 16, borderTop: "1.5px solid var(--ie-sienna)" }}>
          <span style={{ fontFamily: "var(--font-ui)", fontSize: 10, letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--ie-sienna)", fontWeight: 700 }}>{resource.fileSize || "— MB"}</span>
          <span style={{ fontFamily: "var(--font-display)", fontSize: 24, color: "var(--ie-sienna)", fontWeight: 700 }}>↓</span>
        </div>
      </div>
    </div>
  </div>
);

const ResourceIOSShortcut = ({ resource }) => (
  <>
    <div className="rg-twocol">
      <div className="rg-rtext">
        <p className="rg-rbody">{resource.body}</p>
        <p className="rg-rbody" style={{ fontStyle: "italic" }}>{resource.bodyExtra}</p>
        <ActionButtons actions={resource.actions} />
      </div>
      <div className="rg-rvisual">
        {resource.installVideo
          ? <VideoPhone src={resource.installVideo} caption="Install it — tap, then Add Shortcut" />
          : <PhoneFrame />}
      </div>
    </div>

    <div style={{ marginTop: 72 }}>
      <h3 style={{ fontFamily: "var(--font-display)", fontSize: 24, textTransform: "uppercase", color: "var(--ie-sienna)", fontWeight: 700, margin: "0 0 8px", letterSpacing: "-0.005em" }}>
        How to install
      </h3>
      <ol className="rg-steplist">
        {(resource.steps || []).map((s, i) => (
          <li key={i} dangerouslySetInnerHTML={{ __html: s }} />
        ))}
      </ol>
      {resource.tip && (
        <div className="rg-callout">
          <b>Quick tip</b>
          {resource.tip}
        </div>
      )}
      {resource.useVideo && (
        <div className="rg-video-showcase">
          <h3 className="rg-video-showcase-h">
            See it <span className="script">in action.</span>
          </h3>
          <VideoPhone src={resource.useVideo} caption="Tap the shortcut, talk, done. Transcription lands in your iCloud folder." />
        </div>
      )}
    </div>
  </>
);

const ResourceInlineGuide = ({ resource }) => (
  <>
    <p className="rg-rbody" style={{ maxWidth: "62ch" }}>{resource.body}</p>
    <p className="rg-rbody" style={{ maxWidth: "62ch", fontStyle: "italic", color: "var(--ie-sienna-deep)" }}>
      {resource.bodyExtra}
    </p>

    <div className="rg-steps">
      {(resource.steps || []).map((s, i) => (
        <InlineStep key={i} num={i + 1}>
          <h4>{s.title}</h4>
          {s.body && <p dangerouslySetInnerHTML={{ __html: s.body }} />}
          {s.list && (
            <ul>
              {s.list.map((li, j) => (
                <li key={j} dangerouslySetInnerHTML={{ __html: li }} />
              ))}
            </ul>
          )}
          {s.after && <p dangerouslySetInnerHTML={{ __html: s.after }} />}
          {s.visual === "notes" && <NotesMock />}
          {s.visual === "raw-doc" && <RawDocMock />}
          {s.visual === "claude" && <ClaudeMock />}
          {s.prompt && (
            <PromptSnippet prompt={s.prompt.plain}>
              <div dangerouslySetInnerHTML={{ __html: s.prompt.html }} />
            </PromptSnippet>
          )}
        </InlineStep>
      ))}
    </div>

    {resource.closing && (
      <div style={{ marginTop: 48, textAlign: "center" }}>
        <div style={{ fontFamily: "var(--font-display)", fontSize: 26, textTransform: "uppercase", color: "var(--ie-sienna)", fontWeight: 700, letterSpacing: "-0.005em" }}>
          {resource.closing.title}
        </div>
        <p className="rg-rbody" style={{ margin: "12px auto 0", maxWidth: "56ch" }}>{resource.closing.body}</p>
      </div>
    )}
  </>
);

const ResourceSkill = ({ resource }) => (
  <>
    <div className="rg-twocol flip">
      <div className="rg-rtext">
        <p className="rg-rbody">{resource.body}</p>
        <ActionButtons actions={resource.actions} />
      </div>
      <div className="rg-rvisual">
        {resource.image
          ? <img src={resource.image} alt={resource.imageAlt || ""} className="rg-skill-screenshot" />
          : <PhonePlaceholder label={resource.placeholderLabel || "Skill in Claude — screenshot"} />}
      </div>
    </div>

    {resource.what && (
      <div style={{ marginTop: 64 }}>
        <h3 style={{ fontFamily: "var(--font-display)", fontSize: 22, textTransform: "uppercase", color: "var(--ie-butter)", fontWeight: 700, letterSpacing: "0.02em", margin: "0 0 20px" }}>
          What it does
        </h3>
        <div className="rg-bonus-what">
          {resource.what.map((w, i) => (
            <div key={i} className="rg-bonus-card">
              <h4>{w.title}</h4>
              <p>{w.body}</p>
            </div>
          ))}
        </div>
      </div>
    )}

    {resource.setup && (
      <div style={{ marginTop: 48 }}>
        <h3 style={{ fontFamily: "var(--font-display)", fontSize: 22, textTransform: "uppercase", color: "var(--ie-butter)", fontWeight: 700, letterSpacing: "0.02em", margin: "0 0 12px" }}>
          How to set it up
        </h3>
        <ol className="rg-steplist">
          {resource.setup.map((s, i) => (
            <li key={i} dangerouslySetInnerHTML={{ __html: s }} />
          ))}
        </ol>
      </div>
    )}
  </>
);

/* ---------- Master Resource renderer ---------- */
const Resource = ({ index, resource, numberStyle }) => {
  if (resource.enabled === false) return null;
  const tint = resource.tint || "cream";
  const sectionClass = `rg-section tint-${tint}`;
  let body;
  switch (resource.kind) {
    case "link": body = <ResourceLink resource={resource} />; break;
    case "download": body = <ResourceDownload resource={resource} />; break;
    case "ios-shortcut": body = <ResourceIOSShortcut resource={resource} />; break;
    case "inline-guide": body = <ResourceInlineGuide resource={resource} />; break;
    case "skill": body = <ResourceSkill resource={resource} />; break;
    default: body = <ResourceLink resource={resource} />;
  }
  return (
    <section className={sectionClass} id={`resource-${index}`} data-screen-label={`Resource ${asNum(index)}`}>
      <div className="rg-section-inner">
        <ResourceHead index={index} resource={resource} numberStyle={numberStyle} />
        {body}
      </div>
    </section>
  );
};

/* ---------- Bonus section wrapper ---------- */
const BonusSection = ({ bonus, numberStyle }) => {
  if (!bonus || bonus.enabled === false) return null;
  return (
    <section className="rg-bonus" id="bonus" data-screen-label="Bonus">
      <div className="rg-section-inner">
        <div className={`rg-rhead num-${numberStyle}`}>
          <span className="rg-rnum" data-num="★" data-word="bonus.">
            <span className="ie-dot-sm" />
            <span className="label">Bonus</span>
          </span>
          <h2 className="rg-rtitle" dangerouslySetInnerHTML={{ __html: bonus.title }} />
          {bonus.subhead && <p className="rg-rsub">{bonus.subhead}</p>}
        </div>
        <ResourceSkill resource={bonus} />
      </div>
    </section>
  );
};

/* ---------- Connect section ---------- */
const ConnectSection = ({ cfg, show }) => {
  if (!show) return null;
  return (
    <section className="rg-connect" id="connect" data-screen-label="Connect" style={{ backgroundColor: "rgb(199, 214, 241)" }}>
      <div className="rg-connect-inner">
        <span className="rg-connect-eye">Stay in touch<span className="ie-dot-sm" style={{ width: 7, height: 7, borderRadius: 999, background: "var(--ie-sky)", display: "inline-block", marginLeft: 8 }} /></span>
        <h2>
          LET'S <span className="script">keep</span> GOING.
        </h2>
        <p className="rg-connect-sub">
          The system works best when someone's in your corner cheering you on. Here's where I hang out.
        </p>
        <div className="rg-connect-cards">
          <a className="rg-connect-card" href={`https://instagram.com/${cfg.instagramHandle.replace('@','')}`} target="_blank" rel="noreferrer">
            <span className="kind">Instagram</span>
            <span className="handle">{cfg.instagramHandle}</span>
            <span className="desc">Behind-the-scenes of building systems that work with womxn's brains. Occasionally spicy. Always real.</span>
          </a>
          <a className="rg-connect-card" href={`mailto:${cfg.email}`}>
            <span className="kind">Email</span>
            <span className="handle" style={{ fontSize: 20, textTransform: "none", fontFamily: "var(--font-serif)", fontStyle: "italic" }}>{cfg.email}</span>
            <span className="desc">Questions about anything from today, a stuck point in setup, or just want to say hi. I read every one.</span>
          </a>
        </div>
      </div>
    </section>
  );
};

/* ---------- Footer ---------- */
const Footer = ({ cfg }) => (
  <footer className="rg-footer" id="footer">
    <div className="rg-footer-inner">
      <div>
        <div className="rg-footer-closing">
          {cfg.footerClosing.line1}<br />
          <span className="script">{cfg.footerClosing.script}</span>
        </div>
        <p className="rg-footer-thx">{cfg.footerThanks}</p>
      </div>
      <div className="rg-footer-links">
        <a href="https://inspiredefficiency.com" target="_blank" rel="noreferrer">inspiredefficiency.com →</a>
        <a href={`https://instagram.com/${cfg.instagramHandle.replace('@','')}`} target="_blank" rel="noreferrer">{cfg.instagramHandle}</a>
        <a href={`mailto:${cfg.email}`}>{cfg.email}</a>
        <a href="#top">Back to top ↑</a>
      </div>
    </div>
    <div className="rg-footer-credit">
      <span>Built by Sam Courtain <span className="ie-dot-sm" /> Inspired Efficiency</span>
      <span>{cfg.courseSubtitle} <span className="ie-dot-sm" /> {cfg.courseDate}</span>
    </div>
  </footer>
);

/* ---------- Tweaks panel ---------- */
const Tweaks = ({ cfg, setCfg, open, onClose }) => {
  if (!open) return null;
  const upd = (patch) => {
    const next = { ...cfg, ...patch };
    setCfg(next);
    window.parent.postMessage({ type: "__edit_mode_set_keys", edits: patch }, "*");
  };
  const toggleResource = (i, enabled) => {
    const resources = cfg.resources.map((r, idx) => idx === i ? { ...r, enabled } : r);
    upd({ resources });
  };
  return (
    <div className="tweaks is-open">
      <div className="tweaks-head">
        <div className="tweaks-title">Tweaks</div>
        <button className="tweaks-close" onClick={onClose}>×</button>
      </div>

      <div className="tweak-group">
        <label className="tweak-label">Course title</label>
        <div className="tweak"><input type="text" value={cfg.courseSubtitle} onChange={(e) => upd({ courseSubtitle: e.target.value })} /></div>
      </div>
      <div className="tweak-group">
        <label className="tweak-label">Course date</label>
        <div className="tweak"><input type="text" value={cfg.courseDate} onChange={(e) => upd({ courseDate: e.target.value })} /></div>
      </div>
      <div className="tweak-group">
        <label className="tweak-label">Hero headline (use &lt;span class="script"&gt;...&lt;/span&gt; for script accent)</label>
        <div className="tweak"><textarea value={cfg.heroHeadline} onChange={(e) => upd({ heroHeadline: e.target.value })} /></div>
      </div>

      <div className="tweak-group">
        <label className="tweak-label">Hero background</label>
        <div className="tweak-segment">
          {["butter", "cream", "photo"].map((b) => (
            <button key={b} className={cfg.heroBg === b ? "active" : ""} onClick={() => upd({ heroBg: b })}>{b}</button>
          ))}
        </div>
      </div>

      <div className="tweak-group">
        <label className="tweak-label">Numbering style</label>
        <div className="tweak-segment">
          {["A", "B", "C", "D"].map((b) => (
            <button key={b} className={cfg.numberStyle === b ? "active" : ""} onClick={() => upd({ numberStyle: b })}>{b}</button>
          ))}
        </div>
      </div>

      <div className="tweak-group">
        <label className="tweak-label">Resources</label>
        {cfg.resources.map((r, i) => (
          <div key={i} className="tweak-row">
            <label>
              <input type="checkbox" checked={r.enabled !== false} onChange={(e) => toggleResource(i, e.target.checked)} />
              {" "}{asNum(i)} · {r.shortTitle || r.title.replace(/<[^>]+>/g, "").slice(0, 30)}
            </label>
          </div>
        ))}
      </div>

      <div className="tweak-group">
        <label className="tweak-label">Sections</label>
        <div className="tweak-row">
          <label>
            <input type="checkbox" checked={cfg.showBonus} onChange={(e) => upd({ showBonus: e.target.checked })} />
            {" "}Bonus section
          </label>
        </div>
        <div className="tweak-row">
          <label>
            <input type="checkbox" checked={cfg.showConnect} onChange={(e) => upd({ showConnect: e.target.checked })} />
            {" "}Connect section
          </label>
        </div>
      </div>
    </div>
  );
};

/* ---------- Main app ---------- */
const ResourceGuide = ({ initialConfig }) => {
  const [cfg, setCfg] = useState(initialConfig);
  const [tweaksOpen, setTweaksOpen] = useState(false);

  window.__cfg = cfg;

  useEffect(() => {
    const onMsg = (e) => {
      if (!e.data) return;
      if (e.data.type === "__activate_edit_mode") setTweaksOpen(true);
      if (e.data.type === "__deactivate_edit_mode") setTweaksOpen(false);
    };
    window.addEventListener("message", onMsg);
    window.parent.postMessage({ type: "__edit_mode_available" }, "*");
    return () => window.removeEventListener("message", onMsg);
  }, []);

  const ns = cfg.numberStyle || "A";

  return (
    <div data-number-style={ns}>
      <nav className="rg-nav">
        <div className="rg-nav-logo"><img src="assets/logos/wordmark-brown-transparent.png" alt="Inspired Efficiency" /></div>
        <div className="rg-nav-meta">
          <span className="ie-dot-sm" />
          Resource Guide
          <span className="ie-dot-sm" />
          {cfg.courseDate}
        </div>
      </nav>

      <Hero cfg={cfg} numberStyle={ns} />
      <JumpLinks resources={cfg.resources} showBonus={cfg.showBonus} bonus={cfg.bonus} />

      {cfg.resources.map((r, i) => (
        <Resource key={i} index={i} resource={r} numberStyle={ns} />
      ))}

      {cfg.showBonus && <BonusSection bonus={cfg.bonus} numberStyle={ns} />}
      <ConnectSection cfg={cfg} show={cfg.showConnect} />
      <Footer cfg={cfg} />

      <Tweaks cfg={cfg} setCfg={setCfg} open={tweaksOpen} onClose={() => setTweaksOpen(false)} />
    </div>
  );
};

Object.assign(window, { ResourceGuide });
