// Reusable, catalog-driven opt-in (email capture) page for any AFP guide.
// Reads window.AFP_GUIDE_KEY + window.AFP_GUIDES (guides-catalog.js).
// On submit → redirects to that guide's thank-you page (prototype flow), or
// posts to your provider when AFP_SIGNUP_ACTION is set. Exposes window.GuideOptin.

function GuideOptinForm({ guide }) {
  const { Button: GOButton, Kicker: GOKicker, Badge: GOBadge, CJPortrait: GOPortrait } = window.AIForParentsDesignSystem_cccd50;
  const [email, setEmail] = React.useState("");
  const [firstName, setFirstName] = React.useState("");
  const [sent, setSent] = React.useState(false);
  // Posts directly to MailerLite's real form-submit endpoint (from the form's HTML
  // embed export) via fetch — a hidden-iframe/native-submit approach was tried first
  // but let MailerLite's own generic-styled form bleed through visibly on the page.
  // fetch with mode:"no-cors" posts the same fields with zero visible side effect;
  // the response is opaque (cross-origin), so we optimistically redirect after.
  const account = window.AFP_MAILERLITE_ACCOUNT;
  const live = account && guide.mlFormId;
  return (
    <form
      onSubmit={(e) => {
        e.preventDefault();
        if (!email.includes("@")) return;
        if (live) {
          const fd = new FormData();
          fd.append("fields[email]", email);
          fd.append("fields[name]", firstName);
          fd.append("ml-submit", "1");
          fetch("https://assets.mailerlite.com/jsonp/" + account + "/forms/" + guide.mlFormId + "/subscribe", { method: "POST", mode: "no-cors", body: fd }).catch(() => {});
          setSent(true);
          setTimeout(() => { window.location.href = guide.thanks; }, 500);
          return;
        }
        if (window.AFP_SIGNUP_ACTION) {
          fetch(window.AFP_SIGNUP_ACTION, { method: "POST", mode: "no-cors", body: new URLSearchParams({ guide: guide.key, name: firstName, email }) }).catch(() => {});
        }
        window.location.href = guide.thanks;
      }}
      style={{ display: "flex", gap: 10, maxWidth: 480, flexWrap: "wrap" }}>
      <input name="name" value={firstName} onChange={(e) => setFirstName(e.target.value)} type="text" placeholder="First name (optional)"
        style={{ flex: "1 1 150px", fontFamily: "var(--font-body)", fontSize: "var(--fs-body)", padding: "13px 16px", borderRadius: "var(--radius-md)",
          border: "1px solid var(--line-on-navy)", background: "rgba(255,255,255,0.06)", color: "#fff", outline: "none" }} />
      <input name="email" value={email} onChange={(e) => setEmail(e.target.value)} type="email" required placeholder="you@email.com"
        style={{ flex: "1 1 240px", fontFamily: "var(--font-body)", fontSize: "var(--fs-body)", padding: "13px 16px", borderRadius: "var(--radius-md)",
          border: "1px solid var(--line-on-navy)", background: "rgba(255,255,255,0.06)", color: "#fff", outline: "none" }} />
      <GOButton variant="primary" size="lg" as="button" disabled={sent}>{sent ? "Sending…" : "Send it to me"}</GOButton>
    </form>
  );
}

// Generic guide-cover mock, built from catalog fields (no per-guide art needed).
function GuideCover({ guide }) {
  const { Button: GOButton, Kicker: GOKicker, Badge: GOBadge, CJPortrait: GOPortrait } = window.AIForParentsDesignSystem_cccd50;
  return (
    <div style={{ position: "relative", width: 300 }}>
      <div style={{ position: "absolute", inset: 0, background: "var(--cream-300)", borderRadius: "var(--radius-md)", boxShadow: "var(--shadow-md)", transform: "rotate(4deg) translate(12px, 8px)" }}></div>
      <div style={{ position: "absolute", inset: 0, background: "var(--cream-200)", borderRadius: "var(--radius-md)", boxShadow: "var(--shadow-md)", transform: "rotate(2deg) translate(6px, 4px)" }}></div>
      <div style={{ position: "relative", background: "var(--surface-white)", borderRadius: "var(--radius-md)", boxShadow: "var(--shadow-lg)", overflow: "hidden", border: "1px solid var(--cream-300)", transform: "rotate(-1.5deg)" }}>
        <div style={{ position: "relative", background: "var(--afp-navy)", padding: "18px 20px" }}>
          <div style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 8.5, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--afp-amber)" }}>AI for Parents · Free guide</div>
          <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 20, color: "#fff", marginTop: 6, maxWidth: 210, lineHeight: 1.12 }}>{guide.title}</div>
        </div>
        <div style={{ padding: "16px 18px", display: "grid", gap: 8 }}>
          {guide.bullets.slice(0, 4).map((b, i) => (
            <div key={i} style={{ display: "flex", gap: 8, alignItems: "flex-start", borderLeft: "3px solid var(--afp-amber)", background: i % 2 ? "var(--surface-white)" : "var(--cream-50)", padding: "7px 9px", borderRadius: 3 }}>
              <span style={{ width: 10, height: 10, marginTop: 2, border: "2px solid var(--afp-navy)", borderRadius: 2, flex: "none" }} />
              <span style={{ fontSize: 9.5, color: "var(--text-body)", lineHeight: 1.35 }}>{b}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// The article that sits under the opt-in. Catalog-driven like everything else
// here: a guide with no `article` renders nothing and the page is unchanged.
//
// It exists because the opt-in on its own answers no question. A parent
// searching "google family link setup" wants the steps, and a page that only
// asks for an email gives a search engine nothing to rank and the parent
// nothing to read. The guide is still the thing worth having — this is the
// answer, and the PDF is the version you can print and keep.
function GuideArticle({ guide }) {
  const a = guide.article;
  if (!a) return null;
  const H2 = { fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 27, lineHeight: 1.2,
    color: "var(--afp-navy)", margin: "44px 0 14px", letterSpacing: "-0.01em" };
  const P = { fontSize: 17, lineHeight: 1.72, color: "var(--ink-900)", margin: "0 0 16px" };
  const STEP_H = { fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 18, color: "var(--afp-navy)", margin: "0 0 6px" };
  return (
    <section style={{ background: "var(--surface-cream)", padding: "8px 0 56px" }}>
      <div className="wrap" style={{ maxWidth: 780 }}>
        <article>
          {a.intro.map((t, i) => (
            <p key={i} style={{ ...P, ...(i === 0 ? { fontSize: 19, color: "var(--ink-700)" } : null) }}>{t}</p>
          ))}

          {a.sections.map((s, i) => (
            <div key={i}>
              <h2 style={H2}>{s.h}</h2>
              {(s.p || []).map((t, j) => <p key={j} style={P}>{t}</p>)}

              {s.steps && (
                <ol style={{ margin: "4px 0 18px", padding: 0, listStyle: "none", counterReset: "afp-step" }}>
                  {s.steps.map((st, j) => (
                    <li key={j} style={{ display: "flex", gap: 14, alignItems: "flex-start", margin: "0 0 18px" }}>
                      <span style={{ flex: "none", width: 30, height: 30, borderRadius: "50%", background: "var(--afp-amber)",
                        color: "var(--afp-navy)", fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 15,
                        display: "flex", alignItems: "center", justifyContent: "center", marginTop: 2 }}>{j + 1}</span>
                      <div>
                        <div style={STEP_H}>{st.h}</div>
                        <p style={{ ...P, margin: 0 }}>{st.p}</p>
                      </div>
                    </li>
                  ))}
                </ol>
              )}

              {s.list && (
                <ul style={{ margin: "4px 0 18px", padding: 0, listStyle: "none", display: "grid", gap: 10 }}>
                  {s.list.map((t, j) => (
                    <li key={j} style={{ display: "flex", gap: 10, alignItems: "flex-start" }}>
                      <span style={{ color: "var(--afp-amber)", fontWeight: 700, lineHeight: 1.6 }}>&bull;</span>
                      <span style={{ fontSize: 17, lineHeight: 1.6, color: "var(--ink-900)" }}>{t}</span>
                    </li>
                  ))}
                </ul>
              )}

              {/* The script's signature unit: what the kid says, what is really
                  going on, and the exact words back. */}
              {s.exchange && (
                <div style={{ borderLeft: "3px solid var(--afp-amber)", background: "var(--cream-50)",
                  borderRadius: "0 var(--radius-md) var(--radius-md) 0", padding: "16px 20px", margin: "4px 0 20px" }}>
                  {s.exchange.map((row, j) => (
                    <div key={j} style={{ marginBottom: j === s.exchange.length - 1 ? 0 : 12 }}>
                      <div style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 10.5,
                        letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--navy-400)", marginBottom: 3 }}>{row.label}</div>
                      <div style={{ fontSize: 16.5, lineHeight: 1.6, color: "var(--ink-900)" }}>{row.text}</div>
                    </div>
                  ))}
                </div>
              )}

              {/* Questions get their own heading each. A parent scanning for one
                  answer should find it without reading the paragraph above it,
                  and a search engine reads a heading as the question it is. */}
              {s.qa && s.qa.map((row, j) => (
                <div key={j} style={{ margin: "0 0 18px" }}>
                  <h3 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 18,
                    color: "var(--afp-navy)", margin: "0 0 6px" }}>{row.q}</h3>
                  <p style={{ ...P, margin: 0 }}>{row.a}</p>
                </div>
              ))}

              {s.source && (
                <p style={{ fontSize: 13, lineHeight: 1.5, color: "var(--ink-500)", margin: "-6px 0 18px" }}>{s.source}</p>
              )}
            </div>
          ))}

          {a.bottomLine && (
            <div style={{ background: "var(--afp-navy)", borderRadius: "var(--radius-md)", padding: "24px 26px", margin: "36px 0 0" }}>
              <div style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 10.5, letterSpacing: "0.14em",
                textTransform: "uppercase", color: "var(--afp-amber)", marginBottom: 8 }}>The bottom line</div>
              <div style={{ fontSize: 18, lineHeight: 1.6, color: "#fff" }}>{a.bottomLine}</div>
            </div>
          )}

          {/* Real links between the guides, in context rather than only in the
              footer. A parent on the Family Link page who owns an iPhone needs
              the next page, and a crawler reads a link in the body as a
              stronger signal than one in a site-wide list. */}
          {a.related && a.related.length > 0 && (
            <div style={{ margin: "34px 0 0", paddingTop: 22, borderTop: "1px solid var(--line-on-cream)" }}>
              <div style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 10.5, letterSpacing: "0.14em",
                textTransform: "uppercase", color: "var(--navy-400)", marginBottom: 12 }}>Read next</div>
              <ul style={{ margin: 0, padding: 0, listStyle: "none", display: "grid", gap: 10 }}>
                {a.related.map((r, i) => (
                  <li key={i}>
                    <a href={r.href} style={{ color: "var(--navy-600)", fontSize: 16.5, lineHeight: 1.5, textDecoration: "none", fontWeight: 600 }}>{r.text}</a>
                    {r.note && <span style={{ color: "var(--ink-500)", fontSize: 16.5 }}> &mdash; {r.note}</span>}
                  </li>
                ))}
              </ul>
            </div>
          )}

          {a.updated && (
            <p style={{ fontSize: 13, color: "var(--ink-500)", margin: "26px 0 0" }}>Last checked {a.updated}.</p>
          )}
        </article>
      </div>
    </section>
  );
}

function GuideOptin() {
  const { Badge: GOBadge } = window.AIForParentsDesignSystem_cccd50;
  const { SiteNav, SiteFooter } = window;
  const key = window.AFP_GUIDE_KEY;
  const guide = (window.AFP_GUIDES || {})[key];
  if (!guide) {
    return <div style={{ padding: 40, fontFamily: "var(--font-body)" }}>Unknown guide: {String(key)}</div>;
  }
  return (
    <div style={{ background: "var(--surface-cream)" }}>
      <SiteNav active="guides" />
      <window.PageHero
        kicker="Guides" title={guide.title} subtitle={guide.tagline} circuit
        right={
          <div style={{ display: "flex", flexDirection: "column", alignItems: "center" }}>
            <GuideCover guide={guide} />
            <div style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: "var(--fs-caption)", color: "var(--afp-amber)", marginTop: 22 }}>
              {guide.pages} · yours free
            </div>
          </div>
        }
      >
        <div style={{ marginBottom: 8 }}><GOBadge tone="soft">{guide.badge}</GOBadge></div>
        <div style={{ display: "grid", gap: 8, maxWidth: 480, marginBottom: 24 }}>
          {guide.bullets.map((b, i) => (
            <div key={i} style={{ display: "flex", gap: 10, alignItems: "flex-start" }}>
              <span style={{ color: "var(--afp-amber)", fontWeight: 700, fontSize: "var(--fs-body)", lineHeight: 1.5 }}>✓</span>
              <span style={{ fontSize: "var(--fs-small)", lineHeight: 1.5, color: "#fff" }}>{b}</span>
            </div>
          ))}
        </div>
        <GuideOptinForm guide={guide} />
        <div style={{ fontSize: "var(--fs-caption)", color: "var(--text-on-navy-muted)", marginTop: 14 }}>Free · No spam · Unsubscribe anytime</div>
      </window.PageHero>
      <GuideArticle guide={guide} />
      <SiteFooter />
    </div>
  );
}
window.GuideOptin = GuideOptin;
