// Reusable primitives + global helpers

const Btn = ({ children, variant = "dark", href, onClick, type = "button", style }) => {
  const cls = `btn btn-${variant}`;
  if (href) return <a className={cls} href={href} onClick={onClick} style={style}>{children}</a>;
  return <button type={type} className={cls} onClick={onClick} style={style}>{children}</button>;
};

const Eyebrow = ({ children, light }) => (
  <div className={"eyebrow" + (light ? " eyebrow-light" : "")}>{children}</div>
);

const Wordmark = ({ size = 26 }) => (
  <span className="brand-wordmark" style={{ fontSize: size }}>Aligned Attachments</span>
);

const navTo = (to) => (e) => {
  if (e) e.preventDefault();
  window.location.hash = "#/" + (to === "home" ? "" : to);
  window.scrollTo({ top: 0, behavior: "instant" });
};

const useRoute = () => {
  const get = () => {
    const h = (window.location.hash || "#/").replace(/^#\//, "");
    return h.split("/").filter(Boolean);
  };
  const [parts, setParts] = React.useState(get());
  React.useEffect(() => {
    const onChange = () => { setParts(get()); window.scrollTo({ top: 0, behavior: "instant" }); };
    window.addEventListener("hashchange", onChange);
    return () => window.removeEventListener("hashchange", onChange);
  }, []);
  return parts;
};

const AnnounceBar = () => (
  <div className="announce-bar">Discover Your Attachment Style In A Free Consultation Today!</div>
);

// Sends a plain object of fields to Web3Forms, which emails the result to Brittney.
async function submitWeb3Form(fields) {
  const key = (window.AA_CONFIG && window.AA_CONFIG.web3formsAccessKey) || "";
  if (!key || key.indexOf("REPLACE_WITH") === 0) throw new Error("config-missing");
  const res = await fetch("https://api.web3forms.com/submit", {
    method: "POST",
    headers: { "Content-Type": "application/json", Accept: "application/json" },
    body: JSON.stringify({ access_key: key, ...fields }),
  });
  const data = await res.json().catch(() => ({}));
  if (!data.success) throw new Error(data.message || "submit-failed");
  return data;
}

const contactEmail = () => (window.AA_CONFIG && window.AA_CONFIG.contactEmail) || "";

// Inline fallback shown under a form when a submission can't be sent.
const FormError = () => (
  <div style={{ marginTop: 10, fontFamily: "var(--aa-font-body)", fontSize: 13, color: "#b4441f", lineHeight: 1.5 }}>
    This form couldn't send just now. Please email me directly at{" "}
    <a href={"mailto:" + contactEmail()} style={{ color: "inherit", textDecoration: "underline" }}>{contactEmail()}</a>{" "}
    — I read and reply to every message personally.
  </div>
);

const NewsletterForm = ({ onSubmitMsg = "You're in — check your inbox to confirm." }) => {
  const [status, setStatus] = React.useState("idle"); // idle | sending | done | error

  const onSubmit = async (e) => {
    e.preventDefault();
    const fd = new FormData(e.target);
    if (fd.get("botcheck")) return;
    setStatus("sending");
    try {
      await submitWeb3Form({
        subject: "New newsletter signup — Aligned Attachments",
        from_name: "Aligned Attachments Website",
        form_type: "Newsletter signup",
        email: fd.get("email"),
      });
      setStatus("done");
    } catch (err) {
      setStatus("error");
    }
  };

  if (status === "done") {
    return (
      <div style={{ marginTop: 4, fontFamily: "var(--aa-font-body)", fontSize: 14, color: "var(--aa-teal-700)" }}>
        {onSubmitMsg}
      </div>
    );
  }

  return (
    <div>
      <form className="subscribe-row" onSubmit={onSubmit}>
        <input type="email" name="email" placeholder="Enter your email address" required aria-label="Email address"/>
        <input type="checkbox" name="botcheck" tabIndex={-1} autoComplete="off" style={{ display: "none" }} aria-hidden="true"/>
        <button type="submit" disabled={status === "sending"}>
          {status === "sending" ? "Signing up…" : "Sign Up Now"}
        </button>
      </form>
      {status === "error" ? <FormError/> : null}
    </div>
  );
};

Object.assign(window, { Btn, Eyebrow, Wordmark, navTo, useRoute, AnnounceBar, NewsletterForm, submitWeb3Form, FormError, contactEmail });

// Reveal-on-scroll observer (singleton)
(() => {
  if (window.__aaReveal) return;
  const io = new IntersectionObserver((entries) => {
    entries.forEach((en) => {
      if (en.isIntersecting) {
        en.target.classList.add("is-visible");
        io.unobserve(en.target);
      }
    });
  }, { threshold: 0.12, rootMargin: "0px 0px -40px 0px" });
  const scan = () => {
    document.querySelectorAll(".reveal:not(.is-visible)").forEach((el) => io.observe(el));
  };
  // run after each render
  const mo = new MutationObserver(() => scan());
  mo.observe(document.body, { childList: true, subtree: true });
  scan();
  window.__aaReveal = { io, mo };
})();
