// ActionMinutes — landing, signup, email verification

const { useState: useStateL } = React;

/* ---------- Landing page ---------- */
function LandingPage({ name, navigate }) {
  return (
    <div style={{ background: "#fff", flex: 1, display: "flex", flexDirection: "column" }}>
      <nav className="am-mktnav">
        <div className="am-mktnav-inner">
          <AMLogo name={name} />
          <div className="am-mktnav-links">
            <a href="#how">How it works</a>
            <a href="#clerks">For clerks</a>
            <a href="/start" onClick={(e) => { e.preventDefault(); navigate("/start"); }}>Sign in</a>
            <button className="pi-btn pi-btn-primary" onClick={() => navigate("/start")}>Generate your first minutes free</button>
          </div>
        </div>
      </nav>

      <header className="am-hero">
        <div className="am-dotring" style={{ width: 340, height: 340, right: -120, top: -130 }}></div>
        <div className="am-dotring" style={{ width: 180, height: 180, left: -70, bottom: -60, borderColor: "var(--pi-orange-light)" }}></div>
        <div className="am-mkt-section">
          <div>
            <span className="pi-eyebrow">For city and county clerks and the boards they keep</span>
            <h1>Better meetings <span className="accent">start here.</span></h1>
            <p className="am-hero-sub">
              Point us at your agenda, your meeting recording, and an example of your approved
              minutes. We draft the minutes — in your board's voice, in your format — ready for
              your review.
            </p>
            <div className="am-hero-ctas">
              <button className="pi-btn pi-btn-primary pi-btn-lg" onClick={() => navigate("/start")}>
                Generate your first minutes free <AMIcon name="arrow-right" size={15} />
              </button>
              <button className="pi-btn pi-btn-ghost" onClick={(e) => e.preventDefault()}>See a sample draft</button>
            </div>
            <div className="am-hero-note">
              <AMIcon name="badge-check" size={15} color="var(--pi-events-green)" />
              3 free meeting credits every month · for verified public agencies · no card required
            </div>
          </div>
          <div>
            <EqStrip />
          </div>
        </div>
      </header>

      <section className="am-mkt-band tinted" id="how">
        <div className="am-mkt-section">
          <span className="pi-eyebrow">How it works</span>
          <h2 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 30, margin: "10px 0 0", letterSpacing: "-0.01em" }}>
            No uploads to wrangle. No new software to learn.<br />Just minutes that sound like your board.
          </h2>
          <div className="am-steps">
            <div className="am-step">
              <span className="am-step-num">1</span>
              <h3>Tell us about your board</h3>
              <p>Name your jurisdiction and board. We find your agendas, minutes archive, and meeting videos automatically — Legistar, CivicClerk, Granicus, YouTube, and more.</p>
            </div>
            <div className="am-step">
              <span className="am-step-num">2</span>
              <h3>Share what good looks like</h3>
              <p>Upload one set of your approved minutes. That's our template — your structure, your phrasing, your board's voice. Not a generic transcript summary.</p>
            </div>
            <div className="am-step">
              <span className="am-step-num">3</span>
              <h3>Review your draft</h3>
              <p>We email you when the draft is ready — usually well before you've finished your coffee. Edit, download as Word or PDF, done.</p>
            </div>
          </div>
        </div>
      </section>

      <section className="am-mkt-band" id="clerks">
        <div className="am-mkt-section" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 56, alignItems: "center" }}>
          <div>
            <span className="pi-eyebrow">Why {name}</span>
            <h2 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 26, margin: "10px 0 14px" }}>
              You own the minutes. We do the typing.
            </h2>
            <p style={{ fontSize: 15, lineHeight: 1.6, color: "var(--fg-2)", margin: "0 0 14px" }}>
              Minutes are the official record — they have to be right, and they have to be yours.
              That's why we start from <em>your</em> approved minutes, not a one-size-fits-all format,
              and why every draft is yours to review before anything is final.
            </p>
            <p style={{ fontSize: 15, lineHeight: 1.6, color: "var(--fg-2)", margin: 0 }}>
              {name} is built by PublicInput — the public engagement platform trusted by
              public agencies across the country. When you're ready for more than minutes,
              we're already where you work.
            </p>
          </div>
          <div className="pi-card" style={{ padding: 28 }}>
            <p className="pi-pullquote" style={{ margin: 0 }}>
              "I had draft minutes for our March Planning Commission meeting before I'd finished
              my follow-ups from the meeting itself."
            </p>
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 18 }}>
              <span className="pi-avatar">KA</span>
              <div>
                <div style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 13 }}>Clerk of the Board, a Southern California county</div>
                <div style={{ fontSize: 12, color: "var(--fg-3)" }}>Pilot participant, spring 2026</div>
              </div>
            </div>
          </div>
        </div>
      </section>

      <footer className="am-mkt-footer">
        <div className="am-mkt-section">
          <span>{name} is a PublicInput product · Raleigh, NC</span>
          <span>Privacy · Terms · Accessibility</span>
        </div>
      </footer>
    </div>
  );
}

/* ---------- Signup with agency-domain gate ---------- */
const PERSONAL_DOMAINS = ["gmail.com", "yahoo.com", "outlook.com", "hotmail.com", "aol.com", "icloud.com", "proton.me"];
const KNOWN_AGENCY_DOMAINS = {
  "alpinetx.gov": "City of Alpine, TX",
  "raleighnc.gov": "City of Raleigh, NC",
  "wakegov.com": "Wake County, NC",
  "cityofmadison.com": "City of Madison, WI",
};

function classifyEmail(email) {
  const at = email.indexOf("@");
  if (at < 1 || at === email.length - 1) return { kind: "incomplete" };
  const domain = email.slice(at + 1).toLowerCase().trim();
  if (!domain.includes(".")) return { kind: "incomplete" };
  if (PERSONAL_DOMAINS.includes(domain)) return { kind: "personal", domain };
  if (KNOWN_AGENCY_DOMAINS[domain]) return { kind: "known", domain, org: KNOWN_AGENCY_DOMAINS[domain] };
  if (domain.endsWith(".gov") || domain.endsWith(".us")) return { kind: "gov", domain };
  return { kind: "unknown", domain };
}

function SignupPage({ name, navigate }) {
  const [form, setForm] = useStateL({ name: "", email: "", jurisdiction: "", role: "" });
  const [loading, setLoading] = useStateL(false);
  const [error, setError] = useStateL(null);
  const [routedToSales, setRoutedToSales] = useStateL(false);
  const [submittedEmail, setSubmittedEmail] = useStateL("");

  const cls = classifyEmail(form.email);
  const recognized = cls.kind === "known" || cls.kind === "gov" || cls.kind === "unknown";
  const ready = form.name.trim() && form.jurisdiction.trim() && form.role && recognized && !loading;

  const set = (k) => (e) => {
    const v = e.target.value;
    setForm((f) => {
      const next = { ...f, [k]: v };
      if (k === "email") {
        const c = classifyEmail(v);
        if (c.kind === "known" && !f.jurisdiction) next.jurisdiction = c.org;
      }
      return next;
    });
  };

  const handleSubmit = async () => {
    if (!ready) return;
    setLoading(true);
    setError(null);
    try {
      const res = await AM_API.auth.signup({
        name: form.name,
        email: form.email,
        jurisdiction: form.jurisdiction,
        role: form.role,
      });
      if (res.routedToSales) {
        setRoutedToSales(true);
        setSubmittedEmail(form.email);
      } else {
        setSubmittedEmail(form.email);
        navigate("/verify?pending=1&email=" + encodeURIComponent(form.email));
      }
    } catch (err) {
      setError(err.message || "Something went wrong. Please try again.");
    } finally {
      setLoading(false);
    }
  };

  if (routedToSales) {
    return (
      <div style={{ flex: 1, display: "flex", flexDirection: "column" }}>
        <div className="am-focus">
          <div className="am-focus-card">
            <AMLogo name={name} large />
            <h2>Let's talk</h2>
            <p className="lead">
              Your organization isn't on our self-serve list yet, but we'd love to work with you.
              Someone from PublicInput will reach out to {submittedEmail} shortly.
            </p>
            <div className="am-domain-note ok">
              <span className="ico"><AMIcon name="check" size={15} /></span>
              <span>We've received your request. Keep an eye on your inbox.</span>
            </div>
            <div style={{ marginTop: 20 }}>
              <a href="/" onClick={(e) => { e.preventDefault(); navigate("/"); }} style={{ fontSize: 13, color: "var(--fg-3)" }}>
                &larr; Back to home
              </a>
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div style={{ flex: 1, display: "flex", flexDirection: "column" }}>
      <div className="am-focus">
        <div className="am-dotring" style={{ width: 420, height: 420, right: "8%", top: -180 }}></div>
        <div className="am-focus-card">
          <AMLogo name={name} large />
          <h2>Generate your first minutes free</h2>
          <p className="lead">Three meeting credits a month, on us. Tell us who you are and we'll start finding your board's agendas and recordings while you finish signing up.</p>
          <div className="am-form">
            {error && (
              <div className="am-domain-note warn">
                <span className="ico"><AMIcon name="triangle-alert" size={15} /></span>
                <span>{error}</span>
              </div>
            )}
            <div className="pi-field">
              <label className="pi-field-label">Your name</label>
              <input type="text" value={form.name} onChange={set("name")} placeholder="e.g. Karen Aldridge" />
            </div>
            <div className="pi-field">
              <label className="pi-field-label">Work email</label>
              <input type="email" value={form.email} onChange={set("email")} placeholder="you@youragency.gov" />
              {cls.kind === "known" && (
                <div className="am-domain-note ok">
                  <span className="ico"><AMIcon name="badge-check" size={15} /></span>
                  <span><strong>{cls.org}</strong> — recognized public agency. You're all set for the free plan.</span>
                </div>
              )}
              {cls.kind === "gov" && (
                <div className="am-domain-note ok">
                  <span className="ico"><AMIcon name="badge-check" size={15} /></span>
                  <span><strong>{cls.domain}</strong> — verified government domain.</span>
                </div>
              )}
              {cls.kind === "personal" && (
                <div className="am-domain-note warn">
                  <span className="ico"><AMIcon name="triangle-alert" size={15} /></span>
                  <span>{name} is for public agencies, so we need your work email to verify your organization. Not with an agency? <a href="#" onClick={(e) => e.preventDefault()} style={{ color: "inherit", fontWeight: 600 }}>Talk to our team</a> instead.</span>
                </div>
              )}
              {cls.kind === "unknown" && (
                <div className="am-domain-note warn">
                  <span className="ico"><AMIcon name="search" size={15} /></span>
                  <span>We don't recognize <strong>{cls.domain}</strong> yet. You can continue — we'll verify your agency before your first minutes are delivered.</span>
                </div>
              )}
            </div>
            <div className="pi-field">
              <label className="pi-field-label">Jurisdiction</label>
              <input type="text" value={form.jurisdiction} onChange={set("jurisdiction")} placeholder="e.g. City of Alpine, TX or Wake County, NC" />
            </div>
            <div className="pi-field">
              <label className="pi-field-label">Your role</label>
              <select value={form.role} onChange={set("role")}>
                <option value="">Choose one…</option>
                <option>City / Town Clerk</option>
                <option>County Clerk</option>
                <option>Clerk of the Board</option>
                <option>Deputy Clerk</option>
                <option>Board or Commission Secretary</option>
                <option>City / County Administrator</option>
                <option>Other</option>
              </select>
            </div>
            <button
              className="pi-btn pi-btn-primary pi-btn-lg"
              style={{ justifyContent: "center", opacity: ready ? 1 : 0.45, pointerEvents: ready ? "auto" : "none" }}
              onClick={handleSubmit}
            >
              {loading ? "Submitting…" : <>Continue <AMIcon name="arrow-right" size={15} /></>}
            </button>
            <div style={{ textAlign: "center", fontSize: 11.5, color: "var(--fg-3)" }}>
              No credit card. We'll email you a verification link.
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ---------- Verification email page ---------- */
function VerifyPage({ name, navigate }) {
  const params = new URLSearchParams(window.location.search);
  const tokenParam = params.get("token");
  const emailParam = params.get("email") || "";
  const isPending = params.get("pending") === "1";

  const [status, setStatus] = useStateL(tokenParam ? "verifying" : "pending");
  const [error, setError] = useStateL(null);
  const [resendEmail, setResendEmail] = useStateL(emailParam);
  const [resendSent, setResendSent] = useStateL(false);
  const [resendLoading, setResendLoading] = useStateL(false);

  useEffect(() => {
    if (!tokenParam) return;
    AM_API.auth.verify(tokenParam).then((res) => {
      AM_API.setToken(res.accessToken);
      if (res.hasBoards) {
        navigate("/home");
      } else {
        navigate("/setup/board");
      }
    }).catch((err) => {
      setStatus("error");
      setError(err.message || "Verification failed. The link may have expired.");
    });
  }, []);

  const handleResend = async () => {
    if (!resendEmail || resendLoading) return;
    setResendLoading(true);
    try {
      await AM_API.auth.resend(resendEmail);
      setResendSent(true);
    } catch (err) {
      setError(err.message || "Could not resend. Please try again.");
    } finally {
      setResendLoading(false);
    }
  };

  if (status === "verifying") {
    return (
      <div style={{ flex: 1, display: "flex", alignItems: "center", justifyContent: "center" }}>
        <div style={{ textAlign: "center", padding: 40 }}>
          <span className="am-spin" style={{ width: 32, height: 32, borderColor: "rgba(3,149,255,0.2)", borderTopColor: "var(--pi-blue)", display: "inline-block" }}></span>
          <p style={{ marginTop: 16, color: "var(--fg-2)" }}>Verifying your email…</p>
        </div>
      </div>
    );
  }

  if (status === "error") {
    return (
      <div style={{ flex: 1, display: "flex", flexDirection: "column" }}>
        <div className="am-focus">
          <div className="am-focus-card">
            <AMLogo name={name} large />
            <h2>That link has expired</h2>
            <p className="lead" style={{ color: "var(--fg-2)" }}>{error}</p>
            {resendSent ? (
              <div className="am-domain-note ok">
                <span className="ico"><AMIcon name="check" size={15} /></span>
                <span>New verification link sent — check your inbox.</span>
              </div>
            ) : (
              <div className="am-form">
                <div className="pi-field">
                  <label className="pi-field-label">Email address</label>
                  <input type="email" value={resendEmail} onChange={(e) => setResendEmail(e.target.value)} placeholder="you@youragency.gov" />
                </div>
                <button className="pi-btn pi-btn-primary pi-btn-lg" style={{ justifyContent: "center" }} onClick={handleResend} disabled={resendLoading}>
                  {resendLoading ? "Sending…" : "Resend verification email"}
                </button>
              </div>
            )}
          </div>
        </div>
      </div>
    );
  }

  // Pending — "check your email" view
  const displayEmail = emailParam || "your inbox";
  return (
    <div style={{ flex: 1, display: "flex", flexDirection: "column" }}>
      <div className="am-focus">
        <EmailFrame
          subject={`Verify your email to start your first minutes`}
          from={`${name} <hello@${name.toLowerCase().replace(/\s+/g, "")}.ai>`}
          to={displayEmail}
        >
          <p>Hi there,</p>
          <p>
            You're one click away. Verify your email and we'll set up your first board —
            we've already started looking for your jurisdiction's agendas and meeting recordings.
          </p>
          <p style={{ margin: "24px 0" }}>
            <span style={{ display: "inline-flex", alignItems: "center", gap: 8, padding: "10px 22px", background: "var(--pi-blue)", color: "#fff", borderRadius: 999, fontSize: 14, fontFamily: "var(--font-display)", fontWeight: 600 }}>
              Verify my email <AMIcon name="arrow-right" size={15} color="#fff" />
            </span>
          </p>
          <p>— The {name} team at PublicInput</p>
          <p className="fineprint">
            Didn't sign up for {name}? You can safely ignore this email.
            This link expires in 24 hours.
          </p>
        </EmailFrame>
        <p style={{ marginTop: 16, fontSize: 13, color: "var(--fg-3)", textAlign: "center" }}>
          We sent a verification link to <strong>{displayEmail}</strong>. Check your spam folder if it doesn't arrive within a minute.
        </p>
      </div>
    </div>
  );
}

Object.assign(window, { LandingPage, SignupPage, VerifyPage, classifyEmail });
