// /#/manage?token=...                      → intel-tip deletion (default)
// /#/manage?action=unsubscribe&token=...    → pulse subscription unsubscribe
// /#/manage?action=resubscribe&token=...    → re-enable a previously unsubscribed pulse
//
// Both flows are token-based. No accounts, no email confirmation roundtrip:
// possession of the token is the authentication. Tokens are 24-byte
// base64-encoded random — unguessable, URL-safe.

const { useState: useStateM, useEffect: useEffectM } = React;

const SUPABASE_PUBLISHABLE_KEY_M = "sb_publishable_0zNSihwdiVEKHD_HQj7Oqw_wEGGPFf6";

function ManagePage({ onNav }) {
  const [token, setToken] = useStateM("");
  const [action, setAction] = useStateM("delete");
  const [status, setStatus] = useStateM("idle"); // idle / working / done / error
  const [outcome, setOutcome] = useStateM(null);

  useEffectM(() => {
    const h = window.location.hash || "";
    const tok = h.match(/[?&]token=([A-Za-z0-9_+/=%-]+)/);
    if (tok) setToken(decodeURIComponent(tok[1]));
    const act = h.match(/[?&]action=([a-z_-]+)/);
    if (act) setAction(act[1]);
  }, []);

  const isUnsub = action === "unsubscribe";
  const isResub = action === "resubscribe";
  const isDeleteRating = action === "delete-rating";
  const isPulseAction = isUnsub || isResub;

  async function callRpc(rpc, body) {
    const url = `${window.SI_DB.SUPABASE_URL}/rest/v1/rpc/${rpc}`;
    const res = await fetch(url, {
      method: "POST",
      headers: {
        apikey: SUPABASE_PUBLISHABLE_KEY_M,
        Authorization: `Bearer ${SUPABASE_PUBLISHABLE_KEY_M}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify(body),
    });
    return res.ok ? res.json() : null;
  }

  async function performAction() {
    if (!token || !window.SI_DB) return;
    setStatus("working");

    try {
      if (isUnsub) {
        const data = await callRpc("pulse_unsubscribe", { p_token: token });
        const row = Array.isArray(data) && data[0] ? data[0] : null;
        setOutcome({ kind: "pulse_unsub", row });
      } else if (isResub) {
        const data = await callRpc("pulse_resubscribe", { p_token: token });
        const row = Array.isArray(data) && data[0] ? data[0] : null;
        setOutcome({ kind: "pulse_resub", row });
      } else if (isDeleteRating) {
        const data = await callRpc("delete_facility_rating_by_token", { p_token: token });
        const row = Array.isArray(data) && data[0] ? data[0] : null;
        setOutcome({ kind: "rating", outcome: row && row.outcome });
      } else {
        const data = await callRpc("delete_intel_by_token", { p_token: token });
        const row = Array.isArray(data) ? data[0] : data;
        setOutcome({ kind: "intel", ...row });
      }
      setStatus("done");
    } catch (e) {
      setStatus("error");
      setOutcome({ kind: "error", message: e.message });
    }
  }

  const headline = isUnsub ? "Unsubscribe from Pulse."
                  : isResub ? "Re-enable your Pulse."
                  : isDeleteRating ? "Delete your facility ratings."
                  : "Delete a tip you submitted.";

  const description = isUnsub ? (
    <>One click and the daily Pulse stops. The address comes off the active list immediately. No re-confirmation, no retention period.</>
  ) : isResub ? (
    <>This puts your address back on the active list for the metro you originally signed up for.</>
  ) : isDeleteRating ? (
    <>This hard-deletes every dimension you rated in that submission. Aggregate scores recompute immediately. No retention.</>
  ) : (
    <>Use the token from the confirmation URL we showed when you submitted. If your tip was sealed (the default) or hasn't been published yet, deletion is complete and immediate. If your tip became published journalism with a carrier response, your link to it is severed but the published reporting remains in the public record.</>
  );

  const buttonLabel = isUnsub ? "Unsubscribe me"
                    : isResub ? "Re-subscribe me"
                    : isDeleteRating ? "Delete my ratings"
                    : "Delete my submission";

  return (
    <div style={{ maxWidth: 720, margin: "0 auto", padding: "64px 24px" }}>
      <a onClick={() => onNav("home")} style={{ cursor: "pointer", color: "var(--ink-soft)", fontSize: 13 }}>← Back home</a>
      <div className="section-eyebrow" style={{ marginTop: 24 }}>
        {isPulseAction ? "Manage Pulse subscription" : "Manage your submission"}
      </div>
      <h1 className="section-title">{headline}</h1>
      <p style={{ color: "var(--ink-soft)", fontSize: 16, lineHeight: 1.55, marginTop: 12 }}>
        {description}
      </p>

      {status === "idle" && (
        <div style={{ marginTop: 32 }}>
          <label style={{ display: "block", fontSize: 13, color: "var(--ink-soft)", marginBottom: 6, fontFamily: "var(--font-mono)", letterSpacing: "0.1em", textTransform: "uppercase" }}>Your token</label>
          <input
            type="text"
            value={token}
            onChange={(e) => setToken(e.target.value)}
            placeholder="paste your token here"
            style={{ width: "100%", padding: "12px 14px", fontSize: 14, border: "1px solid var(--rule)", borderRadius: 6, fontFamily: "var(--font-mono)", boxSizing: "border-box" }}
          />
          <button
            onClick={performAction}
            className="btn-primary"
            disabled={!token}
            style={{ marginTop: 16, padding: "12px 22px" }}
          >
            {buttonLabel}
          </button>
        </div>
      )}

      {status === "working" && (
        <div style={{ marginTop: 32, color: "var(--ink-soft)" }}>Working…</div>
      )}

      {status === "done" && outcome && (
        <div style={{ marginTop: 32, padding: 24, background: outcome.row || outcome.outcome === "hard_deleted" || outcome.outcome === "anonymized_story_remains" ? "oklch(0.96 0.04 145)" : "oklch(0.96 0.04 60)", borderRadius: 6 }}>
          {/* Pulse unsubscribe outcomes */}
          {outcome.kind === "pulse_unsub" && outcome.row && (
            <>
              <div style={{ fontFamily: "var(--font-serif)", fontSize: 22, marginBottom: 8 }}>✓ Unsubscribed.</div>
              <p style={{ margin: 0, color: "var(--ink-soft)" }}>
                You're off the {outcome.row.city_name} Pulse list. No more daily emails.{" "}
                <a
                  style={{ color: "var(--ink)", textDecoration: "underline", cursor: "pointer" }}
                  onClick={() => {
                    window.location.hash = `#/manage?action=resubscribe&token=${encodeURIComponent(token)}`;
                    setAction("resubscribe");
                    setStatus("idle");
                    setOutcome(null);
                  }}
                >Changed your mind?</a>
              </p>
            </>
          )}
          {outcome.kind === "pulse_unsub" && !outcome.row && (
            <>
              <div style={{ fontFamily: "var(--font-serif)", fontSize: 22, marginBottom: 8 }}>Already unsubscribed.</div>
              <p style={{ margin: 0, color: "var(--ink-soft)" }}>
                That token isn't on the active list — either you've already unsubscribed, or the token is invalid.
              </p>
            </>
          )}
          {outcome.kind === "pulse_resub" && outcome.row && (
            <>
              <div style={{ fontFamily: "var(--font-serif)", fontSize: 22, marginBottom: 8 }}>✓ You're back on.</div>
              <p style={{ margin: 0, color: "var(--ink-soft)" }}>
                The {outcome.row.city_name} Pulse will resume tomorrow morning.
              </p>
            </>
          )}
          {outcome.kind === "pulse_resub" && !outcome.row && (
            <>
              <div style={{ fontFamily: "var(--font-serif)", fontSize: 22, marginBottom: 8 }}>Token not found.</div>
              <p style={{ margin: 0, color: "var(--ink-soft)" }}>We couldn't find a subscription for that token.</p>
            </>
          )}

          {/* Facility rating deletion outcomes */}
          {outcome.kind === "rating" && outcome.outcome === "hard_deleted" && (
            <>
              <div style={{ fontFamily: "var(--font-serif)", fontSize: 22, marginBottom: 8 }}>✓ Deleted.</div>
              <p style={{ margin: 0, color: "var(--ink-soft)" }}>
                Your ratings have been removed. Aggregate scores recompute now.
              </p>
            </>
          )}
          {outcome.kind === "rating" && outcome.outcome === "not_found" && (
            <>
              <div style={{ fontFamily: "var(--font-serif)", fontSize: 22, marginBottom: 8 }}>Token not found.</div>
              <p style={{ margin: 0, color: "var(--ink-soft)" }}>
                We couldn't find ratings for that token — they may have already been deleted.
              </p>
            </>
          )}
          {outcome.kind === "rating" && outcome.outcome === "invalid_token" && (
            <>
              <div style={{ fontFamily: "var(--font-serif)", fontSize: 22, marginBottom: 8 }}>Invalid token.</div>
              <p style={{ margin: 0, color: "var(--ink-soft)" }}>Check that you copied the full token from the confirmation URL.</p>
            </>
          )}

          {/* Intel deletion outcomes */}
          {outcome.kind === "intel" && outcome.outcome === "hard_deleted" && (
            <>
              <div style={{ fontFamily: "var(--font-serif)", fontSize: 22, marginBottom: 8 }}>✓ Deleted.</div>
              <p style={{ margin: 0, color: "var(--ink-soft)" }}>
                Your tip has been removed from the database. Your identifying data is gone.
              </p>
            </>
          )}
          {outcome.kind === "intel" && outcome.outcome === "anonymized_story_remains" && (
            <>
              <div style={{ fontFamily: "var(--font-serif)", fontSize: 22, marginBottom: 8 }}>✓ Withdrawn.</div>
              <p style={{ margin: 0, color: "var(--ink-soft)" }}>
                Your link to the published story has been severed and your identifying data is gone. The published reporting remains in the public record per journalism standards, with a note that the original reporter has withdrawn.
              </p>
            </>
          )}
          {outcome.kind === "intel" && outcome.outcome === "not_found" && (
            <>
              <div style={{ fontFamily: "var(--font-serif)", fontSize: 22, marginBottom: 8 }}>Token not found.</div>
              <p style={{ margin: 0, color: "var(--ink-soft)" }}>
                We couldn't find a submission with that token. It may have already been deleted, or the token may have a typo.
              </p>
            </>
          )}
          {outcome.kind === "intel" && outcome.outcome === "invalid_token" && (
            <>
              <div style={{ fontFamily: "var(--font-serif)", fontSize: 22, marginBottom: 8 }}>Invalid token format.</div>
              <p style={{ margin: 0, color: "var(--ink-soft)" }}>Check that you copied the full token from the confirmation URL.</p>
            </>
          )}
        </div>
      )}

      {status === "error" && (
        <div style={{ marginTop: 32, padding: 24, background: "oklch(0.96 0.04 25)", borderRadius: 6 }}>
          <div style={{ fontFamily: "var(--font-serif)", fontSize: 22, marginBottom: 8 }}>Something went wrong.</div>
          <p style={{ margin: 0, color: "var(--ink-soft)" }}>{outcome?.message || "Try again or contact support."}</p>
        </div>
      )}
    </div>
  );
}

window.ManagePage = ManagePage;
