// Forage & Forests — landing forms: Kickstarter notify, playtest signup, and
// the always-available feedback widget. All post to the serverless API via
// window.HHApi and degrade gracefully (a failed/un-provisioned backend shows a
// friendly error rather than breaking the page).

/* eslint-disable no-undef */

function useField(initial = "") {
  const [v, setV] = React.useState(initial);
  return [v, (e) => setV(e && e.target ? e.target.value : e)];
}

function emailError(err) {
  return err && err.status === 400
    ? "That doesn't look like a valid email."
    : "Something went wrong — please try again in a moment.";
}

// 1) Kickstarter "notify me" — single email field.
function KickstarterNotify() {
  const [email, onEmail] = useField("");
  const [status, setStatus] = React.useState("idle"); // idle | sending | ok | error
  const [error, setError] = React.useState("");

  async function submit(e) {
    e.preventDefault();
    if (status === "sending") return;
    setStatus("sending");
    setError("");
    try {
      await window.HHApi.post("/api/subscribe", { email, source: "kickstarter-notify" });
      window.HHApi.track("kickstarter_signup");
      setStatus("ok");
    } catch (err) {
      setError(emailError(err));
      setStatus("error");
    }
  }

  return (
    <div className="hh-plate">
      <SmallCaps>Coming to Kickstarter</SmallCaps>
      <p style={{ font: "400 15px/1.55 'EB Garamond', serif", color: "var(--ink-soft)", margin: "6px 0 12px" }}>
        A printed edition is in the works — heavy cardstock, the full botanical
        plate art, a boxed set. Leave your email and we'll send a single note the
        day it launches. Nothing else.
      </p>
      {status === "ok" ? (
        <Notice tone="good">You're on the list — thank you. We'll be in touch.</Notice>
      ) : (
        <form onSubmit={submit} style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
          <input
            className="hh-input--box"
            type="email"
            required
            placeholder="you@example.com"
            value={email}
            onChange={onEmail}
            aria-label="Email address"
            style={{ flex: "1 1 200px" }}
          />
          <button className="hh-btn primary" type="submit" disabled={status === "sending"}>
            {status === "sending" ? "…" : "Notify me"}
          </button>
        </form>
      )}
      {status === "error" && <div style={{ marginTop: 8 }}><Notice tone="warn">{error}</Notice></div>}
    </div>
  );
}

// 2) Playtest signup — emails the print-and-play kit; shows the link on success.
function PlaytestSignup() {
  const [email, onEmail] = useField("");
  const [name, onName] = useField("");
  const [players, setPlayers] = React.useState("");
  const [experience, setExperience] = React.useState("");
  const [status, setStatus] = React.useState("idle");
  const [error, setError] = React.useState("");
  const [downloadUrl, setDownloadUrl] = React.useState("/print-and-play");

  async function submit(e) {
    e.preventDefault();
    if (status === "sending") return;
    setStatus("sending");
    setError("");
    try {
      const r = await window.HHApi.post("/api/playtest", { email, name, players, experience });
      if (r && r.downloadUrl) setDownloadUrl(r.downloadUrl);
      window.HHApi.track("playtest_signup", { players: players || null, experience: experience || null });
      setStatus("ok");
    } catch (err) {
      setError(emailError(err));
      setStatus("error");
    }
  }

  if (status === "ok") {
    return (
      <div className="hh-plate">
        <SmallCaps>You're in — thank you!</SmallCaps>
        <p style={{ font: "400 15px/1.55 'EB Garamond', serif", margin: "6px 0 14px" }}>
          We've emailed your print-and-play kit. You can also open it right now:
        </p>
        <a
          className="hh-btn primary lg"
          href={downloadUrl}
          target="_blank"
          rel="noopener"
          onClick={() => window.HHApi.track("pnp_download", { from: "playtest-success" })}
        >
          Open the print-and-play kit
        </a>
        <p style={{ font: "italic 400 13px/1.5 'EB Garamond', serif", color: "var(--ink-soft)", marginTop: 12, marginBottom: 0 }}>
          Print at 100% scale, double-sided (flip on the short edge). When you've
          played, the feedback button is always in the corner.
        </p>
      </div>
    );
  }

  return (
    <div className="hh-plate">
      <SmallCaps>Playtest with us</SmallCaps>
      <p style={{ font: "400 15px/1.55 'EB Garamond', serif", color: "var(--ink-soft)", margin: "6px 0 12px" }}>
        Print the deck at home and put it through real games. Sign up and we'll
        email you the files and a short feedback form — your notes directly shape
        the printed edition.
      </p>
      <form onSubmit={submit} style={{ display: "grid", gap: 10 }}>
        <input className="hh-input--box" type="email" required placeholder="Email (required)"
          value={email} onChange={onEmail} aria-label="Email" />
        <input className="hh-input--box" type="text" placeholder="Name (optional)"
          value={name} onChange={onName} aria-label="Name" />
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
          <select className="hh-input--box" value={players} onChange={(e) => setPlayers(e.target.value)} aria-label="Usual player count">
            <option value="">Usual players…</option>
            <option>Solo</option>
            <option>2 players</option>
            <option>3 players</option>
            <option>4+ players</option>
          </select>
          <select className="hh-input--box" value={experience} onChange={(e) => setExperience(e.target.value)} aria-label="Board-game experience">
            <option value="">Experience…</option>
            <option>New to hobby games</option>
            <option>Play sometimes</option>
            <option>Hardcore hobbyist</option>
          </select>
        </div>
        <div style={{ display: "flex", gap: 10, alignItems: "center", flexWrap: "wrap" }}>
          <button className="hh-btn primary" type="submit" disabled={status === "sending"}>
            {status === "sending" ? "Sending…" : "Send me the kit"}
          </button>
          <SmallCaps className="muted">free · print at home</SmallCaps>
        </div>
      </form>
      {status === "error" && <div style={{ marginTop: 8 }}><Notice tone="warn">{error}</Notice></div>}
    </div>
  );
}

// 3) Feedback — floating button + modal, mounted app-wide.
function FeedbackWidget({ context = "site" }) {
  const [open, setOpen] = React.useState(false);
  return (
    <React.Fragment>
      <button
        className="hh-feedback-fab"
        onClick={() => { setOpen(true); window.HHApi.track("feedback_open", { context }); }}
        aria-label="Send feedback"
      >
        <PencilIcon size={15} />
        <span>Feedback</span>
      </button>
      {open && <FeedbackModal context={context} onClose={() => setOpen(false)} />}
    </React.Fragment>
  );
}

function FeedbackModal({ context, onClose }) {
  const [message, onMessage] = useField("");
  const [email, onEmail] = useField("");
  const [rating, setRating] = React.useState(0);
  const [status, setStatus] = React.useState("idle");

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

  async function submit(e) {
    e.preventDefault();
    if (status === "sending" || message.trim().length < 2) return;
    setStatus("sending");
    try {
      await window.HHApi.post("/api/feedback", {
        message, email, context, rating: rating || undefined,
      });
      window.HHApi.track("feedback_submit", { context, rating: rating || null });
      setStatus("ok");
    } catch (err) {
      setStatus("error");
    }
  }

  return (
    <div className="hh-modal-backdrop" onClick={onClose}>
      <div className="hh-modal" onClick={(e) => e.stopPropagation()} role="dialog" aria-modal="true" aria-label="Send feedback">
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 10 }}>
          <SmallCaps>Send feedback</SmallCaps>
          <button className="hh-icon-btn" onClick={onClose} aria-label="Close"><CloseIcon /></button>
        </div>
        {status === "ok" ? (
          <Notice tone="good">Thank you — got it. This is exactly how the game gets better.</Notice>
        ) : (
          <form onSubmit={submit} style={{ display: "grid", gap: 11 }}>
            <p style={{ font: "italic 400 13px/1.45 'EB Garamond', serif", color: "var(--ink-soft)", margin: 0 }}>
              What worked, what confused you, what you'd change — about the online
              game or your tabletop playtest.
            </p>
            <div style={{ display: "flex", gap: 6, alignItems: "center" }}>
              <SmallCaps className="muted">Rating</SmallCaps>
              {[1, 2, 3, 4, 5].map((n) => (
                <button
                  type="button"
                  key={n}
                  className="hh-star"
                  aria-label={n + " star" + (n > 1 ? "s" : "")}
                  onClick={() => setRating(n)}
                  style={{ color: n <= rating ? "var(--gold)" : "var(--rule)" }}
                >★</button>
              ))}
            </div>
            <textarea className="hh-textarea" required rows={5} placeholder="Your notes…"
              value={message} onChange={onMessage} aria-label="Feedback message" />
            <input className="hh-input--box" type="email" placeholder="Email (optional — if you'd like a reply)"
              value={email} onChange={onEmail} aria-label="Email" />
            <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
              <button className="hh-btn primary" type="submit" disabled={status === "sending"}>
                {status === "sending" ? "Sending…" : "Send feedback"}
              </button>
              {status === "error" && <SmallCaps style={{ color: "var(--accent)" }}>Try again?</SmallCaps>}
            </div>
          </form>
        )}
      </div>
    </div>
  );
}

// Playtest consent gate — shown when the player clicks "Start the free
// playtest". Declining returns them to the landing page instead of opening the
// game; the parent decides what each choice does.
function PlaytestConsentModal({ onAgree, onDecline }) {
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onDecline(); };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [onDecline]);

  return (
    <div className="hh-modal-backdrop" onClick={onDecline}>
      <div className="hh-modal" onClick={(e) => e.stopPropagation()} role="dialog" aria-modal="true" aria-label="Playtest feedback">
        <SmallCaps>Before you play</SmallCaps>
        <h3 style={{ font: "500 22px/1.25 'EB Garamond', serif", color: "var(--ink)", margin: "8px 0 6px" }}>
          Are you willing to share your feedback on the game?
        </h3>
        <p style={{ font: "400 15px/1.55 'EB Garamond', serif", color: "var(--ink-soft)", margin: "0 0 16px" }}>
          This is a free playtest, so a couple of minutes of feedback afterward is
          all we ask — it directly shapes the game and the printed edition. The
          feedback button stays in the corner the whole time you play.
        </p>
        <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
          <button className="hh-btn primary" onClick={onAgree}>Yes — let's play</button>
          <button className="hh-btn ghost" onClick={onDecline}>Not this time</button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { KickstarterNotify, PlaytestSignup, FeedbackWidget, FeedbackModal, PlaytestConsentModal });
