"use client";

import {
  useEffect,
  useMemo,
  useRef,
  useState,
  useSyncExternalStore,
  type CSSProperties,
} from "react";
import { createPortal } from "react-dom";
import { getCurrentUserID, getToken } from "@enode/core/api/storage";
import {
  getIsOnlineSnapshot,
  subscribeToConnectivity,
} from "@enode/core/connectivity/store";
import { useTranslation } from "@enode/core/translations/hooks";
import { AthleteAvatar } from "@enode/ui/athlete-avatar";
import { overlayPortalHost } from "@enode/ui/containment";
import { toast } from "@enode/ui/feedback/toast-store";
import { CloseXIcon, SpinnerIcon } from "@enode/ui/icons";
import { Sheet } from "@enode/ui/sheet";
import { syncReminders } from "../../../reminders/sync";
import {
  acceptsHostDelivery,
  deliverWellness,
  hostAuthCommand,
  wellnessTotal,
} from "../questionnaire-delivery";
import {
  QUESTIONNAIRE_LOAD_TIMEOUT_MS,
  useQuestionnaireFrameState,
} from "../questionnaire-frame-state";
import { QuestionnaireUnavailable } from "../questionnaire-unavailable";
import { markCheckInSubmitted } from "./check-in-status";
import { setCheckedIn } from "./check-in-store";
import { buildQuestionnaireUrl, resolveServiceOrigin } from "./service-url";
import { HEADER_ICON_BUTTON } from "@enode/ui/header-button";

// The check-in as it appears before training: a full-screen sheet on a phone, a
// centred card over a dimmed page on a tablet (`tablet:`), that the athlete
// fills in, ending in their own summary and a Submit. Completing it is what lets
// the workout start (`onCompleted`).
//
// The questionnaire itself is NO LONGER part of this app — it is served by the
// questionnaire service and rendered in the iframe below (see
// apps/portal/src/questionnaire-service/). Only the chrome is local, which is
// why the screen looks exactly as it did when the flow lived here.
//
// Closing the sheet (X, Escape, hardware Back) cancels the start: the station
// stays as it was, so the check-in can't trap someone who opened a workout by
// mistake.
//
// ── Why the iframe lives OUTSIDE the Sheet ──────────────────────────────────
// Sheet unmounts its children when closed, and the service is a whole web app:
// loading it on open costs a fetch, ~900KB of JS, and a hydration pass, which
// the athlete would spend staring at an empty drawer. So the frame is mounted
// for the whole session in a hidden, always-present overlay — it loads while
// the athlete is doing something else, and opening the sheet only reveals it.
//
// The overlay is portaled to the same host as Sheet (document.body) so the two
// share a stacking context, and it is offset by the measured header height so
// the sheet's own title stays visible above it. On a tablet both are sized by
// the same `CARD_BOX` and centred the same way, so the questionnaire lands
// exactly inside the card. Moving an iframe in the DOM
// reloads it, which is exactly what this arrangement exists to avoid — so the
// node is never re-parented, only shown and hidden.

/**
 * How long a check-in that stands in front of a workout start waits for the
 * service's `ready` before letting the workout start anyway.
 *
 * FAIL-OPEN, and deliberately so: this sheet gates EVERY start, and the app is
 * built to train offline (see docs/offline-and-sync.md). A questionnaire behind
 * a URL must never be able to stop an athlete from training — losing a check-in
 * is the cheaper failure by a wide margin. Only runs while the sheet is open
 * and the frame has not reported in; a preloaded frame never starts it.
 *
 * A check-in opened on its own has nothing waiting behind it and gets the
 * longer {@link QUESTIONNAIRE_LOAD_TIMEOUT_MS}, then says that it could not
 * load instead of closing.
 */
const START_GATE_TIMEOUT_MS = 4000;

/** The highest total: five measures, five points each. Mirrors the service. */
const MAX_TOTAL = 25;

/**
 * Delay before reloading a used frame, so the blank first paint of the fresh
 * questionnaire can't be seen on the way out. The frame is already hidden by
 * then (`setReady(false)`); this only keeps the remount from landing in the
 * same beat as the close. It used to guard against flashing through the sheet's
 * close animation, which no longer exists (`slideFrom="none"`).
 */
const RELOAD_DELAY_MS = 600;

/**
 * The card's size on a tablet. Shared by the Sheet's card and the iframe
 * overlay — they live in different portals, so matching sizes (both centred in
 * the viewport) is what keeps the questionnaire inside the card.
 */
const CARD_BOX =
  "tablet:h-[min(56rem,calc(100dvh-4rem))] tablet:w-[min(40rem,calc(100vw-4rem))]";

/** Fallback offset for the first frame after opening, before the real header is
 *  measured — close to the header's natural height, so nothing jumps. */
const HEADER_FALLBACK_PX = 84;

// The check-in frame is a browser-only thing: the app is a static export, so
// the prerendered page has no overlay, and the first client render must not
// have one either or React reports a hydration mismatch on every load. A store
// with a false server snapshot gives both renders the same answer and flips
// right after hydration.
const subscribeNever = () => () => {};
const isClient = () => true;
const isServer = () => false;

// Mirrors the service's own contract (questionnaire-service/host-bridge.ts).
type ServiceEvent =
  | { event: "ready" }
  | { event: "authenticated"; userId: string; delivery?: string }
  | { event: "submitted"; id: string; payload: unknown }
  | { event: "saved"; id: string }
  | { event: "save-failed"; id: string; queued: boolean }
  | { event: "cancelled" };

/** Why a check-in in front of a workout start was skipped. */
export type CheckInUnavailableReason = "offline" | "failed";

export function WellnessCheckInSheet({
  open,
  enabled,
  startsWorkout,
  subject,
  onCancel,
  onCompleted,
  onUnavailable,
}: {
  open: boolean;
  /**
   * Whether this account uses the check-in at all. Only then is the
   * questionnaire loaded ahead of time; everyone else never requests it (the
   * frame is a whole web app). Opening the sheet loads it regardless, so a
   * deep link still works.
   */
  enabled: boolean;
  /**
   * Whether a workout start is waiting behind the sheet. Then a questionnaire
   * that does not arrive must not hold the training up: `onUnavailable` is
   * called and the sheet shows nothing of its own. Without a start behind it,
   * the sheet stays and says what happened.
   */
  startsWorkout: boolean;
  /**
   * Whose check-in this is. Omit for the signed-in user; pass a participant to
   * let a coach answer for an athlete who never logs in.
   *
   * The coach's token still authorises the write — this only selects the
   * subject, which the backend attributes the measurements to.
   */
  subject?: { id: string; name?: string | null } | null;
  onCancel: () => void;
  onCompleted: () => void;
  /** The questionnaire did not arrive while a workout start was waiting. */
  onUnavailable: (reason: CheckInUnavailableReason) => void;
}) {
  const { t, locale } = useTranslation();
  const mounted = useSyncExternalStore(subscribeNever, isClient, isServer);
  const frameRef = useRef<HTMLIFrameElement | null>(null);
  const subjectId = subject?.id ?? getCurrentUserID() ?? "";
  // Only when answering for someone else — the header names them, because
  // mis-attribution is this feature's failure mode and is otherwise invisible.
  const subjectName = subject?.name?.trim() || null;

  // Bumped after a finished check-in so the next workout gets a fresh
  // questionnaire — and, because the frame reloads immediately, a preloaded one.
  const [generation, setGeneration] = useState(0);
  const [ready, setReady] = useState(false);
  const [headerHeight, setHeaderHeight] = useState(HEADER_FALLBACK_PX);

  const serviceOrigin = useMemo(
    () => new URL(resolveServiceOrigin()).origin,
    [],
  );

  // Built once the page has hydrated — NOT gated on `open` for an account that
  // uses the check-in, which is what makes the frame preload.
  const loadFrame = mounted && (enabled || open);
  const src = useMemo(
    () =>
      loadFrame
        ? buildQuestionnaireUrl({
            id: "wellness",
            audience: "athlete",
            locale,
            // The questionnaire paints the sheet's colour, so header and
            // questions read as one surface.
            surface: "drawer",
          })
        : null,
    [loadFrame, locale],
  );

  // Whether the loaded service agreed to let this app send the answers — see
  // questionnaire-delivery.ts.
  const hostDeliversRef = useRef(false);
  // Latest callback, so the listener below subscribes once per frame.
  const completedRef = useRef(onCompleted);
  const unavailableRef = useRef(onUnavailable);
  useEffect(() => {
    completedRef.current = onCompleted;
    unavailableRef.current = onUnavailable;
  });

  // Says where the check-in went, once that is known. The words belong to the
  // moment of the submit — whose check-in, and its total — because the frame
  // is reloaded and the subject may change before the answer is in.
  const announceRef = useRef<((queued: boolean) => void) | null>(null);

  // The service's half of the contract. Mounted for the session, not just while
  // the sheet is open, so a `ready` that arrives during preload is not missed.
  useEffect(() => {
    function onMessage(event: MessageEvent) {
      // The only thing standing between a forged message and a started workout.
      if (event.origin !== serviceOrigin) return;
      const message = event.data as ServiceEvent | undefined;
      if (!message?.event) return;

      // Whether THIS frame's service agreed to let the app send the answers.
      // Checked against the frame, not just the origin: the other
      // questionnaire's frame shares the origin and this window.
      if (event.source === frameRef.current?.contentWindow) {
        if (message.event === "ready") hostDeliversRef.current = false;
        if (message.event === "authenticated") {
          hostDeliversRef.current = acceptsHostDelivery(message);
          return;
        }
      }

      if (message.event === "ready") {
        // The session rating's frame shares this origin and this window, and
        // this sheet's own frame may not be mounted at all (an account that
        // doesn't use the check-in) — so only its own frame can make it ready.
        if (event.source !== frameRef.current?.contentWindow) return;
        setReady(true);
        // Hand over the session so the service can act as this user. Sent only
        // after `ready`, and only to the service's origin — never as a URL
        // parameter, which would leak it into history and access logs.
        const token = getToken();
        if (token) {
          // Two different things: the TOKEN authorises the write (always the
          // signed-in user), the USER ID selects whose check-in it is. The
          // backend attributes the measurements to the id, which is what lets a
          // coach answer for an athlete who has no login.
          frameRef.current?.contentWindow?.postMessage(
            hostAuthCommand(token, subjectId),
            serviceOrigin,
          );
        }
        return;
      }

      if (message.event === "submitted" && message.id === "wellness") {
        // Note the check-in for the reminder. The server is what actually
        // decides (see check-in-status.ts) — this only bridges the gap until the
        // submit reaches it. Deliberately here and not in `onCompleted`: the
        // fail-open timeout below also completes the sheet, and a check-in that
        // never happened must not suppress tomorrow's reminder.
        // Recorded against the SUBJECT, not the signed-in user — otherwise a
        // coach checking in an athlete would clear their own badge and leave
        // the athlete's showing.
        //
        // When the service left the answers to this app, they are stored on
        // the device first and sent from there. Fire-and-forget — the workout
        // must not wait on it.
        const total = wellnessTotal(message.payload);
        const announce = (queued: boolean) => {
          if (subjectName) {
            toast.success(
              queued
                ? t(
                    "Check-in for {name} saved on this device — sent when you're back online",
                    { name: subjectName },
                  )
                : t("Check-in saved for {name}", { name: subjectName }),
            );
          } else if (queued) {
            toast.success(
              t("Check-in saved on this device — sent when you're back online"),
            );
          } else {
            toast.success(
              total === null
                ? t("Check-in saved")
                : t("Check-in saved · {total} of {max}", {
                    total,
                    max: MAX_TOTAL,
                  }),
            );
          }
        };
        if (hostDeliversRef.current && subjectId) {
          announceRef.current = null;
          void deliverWellness(message.payload, subjectId).then(
            (outcome) => {
              // Nothing usable was handed over, so nothing was saved and
              // nothing may be claimed.
              if (outcome !== "unusable") announce(outcome === "queued");
            },
            (err) => console.error("check-in could not be stored:", err),
          );
        } else {
          // An older service sends the answers itself and reports the outcome
          // in a later event.
          announceRef.current = announce;
        }
        if (subjectId) {
          // Two consumers, told directly rather than through each other: the
          // reminder's session hint, and the training view's badge store. The
          // submit goes through an outbox, so a refetch would race the write
          // and leave the badge showing.
          markCheckInSubmitted(subjectId);
          setCheckedIn(subjectId);
          void syncReminders();
        }
        completedRef.current();
        // Hide it straight away, then reload once the sheet has animated out.
        setReady(false);
        window.setTimeout(
          () => setGeneration((value) => value + 1),
          RELOAD_DELAY_MS,
        );
        return;
      }

      if (
        (message.event === "saved" || message.event === "save-failed") &&
        message.id === "wellness"
      ) {
        // A check-in the service could neither send nor keep is not announced:
        // there is nothing the athlete could do about it here.
        const queued = message.event === "save-failed";
        if (message.event === "saved" || message.queued) {
          announceRef.current?.(queued);
        }
        announceRef.current = null;
      }
    }

    window.addEventListener("message", onMessage);
    return () => window.removeEventListener("message", onMessage);
    // `subjectId` is a dependency: the handler posts it on `ready`, so a stale
    // closure would authorise the frame as the previous athlete.
  }, [serviceOrigin, subjectId, subjectName, t]);

  // Only on the clock while the athlete is actually waiting — a frame that
  // preloaded successfully is already `ready`.
  const frameState = useQuestionnaireFrameState({
    waiting: open,
    ready,
    attempt: generation,
    timeoutMs: startsWorkout
      ? START_GATE_TIMEOUT_MS
      : QUESTIONNAIRE_LOAD_TIMEOUT_MS,
  });
  const unavailable =
    frameState === "offline" || frameState === "failed" ? frameState : null;

  // Fail-open for a workout start: hand back at once, with the reason, so the
  // page can start the training and say why nothing was asked.
  useEffect(() => {
    if (!(open && startsWorkout && unavailable)) return;
    unavailableRef.current(unavailable);
    // And load it afresh behind the closed sheet, so the attempt that just
    // failed is not what the next start finds.
    const timer = window.setTimeout(
      () => setGeneration((value) => value + 1),
      RELOAD_DELAY_MS,
    );
    return () => window.clearTimeout(timer);
  }, [open, startsWorkout, unavailable]);

  // A frame that was requested without a connection holds the browser's error
  // page and will never report in. Load it again when the connection is back.
  const readyRef = useRef(ready);
  useEffect(() => {
    readyRef.current = ready;
  });
  useEffect(() => {
    if (!loadFrame) return;
    let wasOnline = getIsOnlineSnapshot();
    return subscribeToConnectivity(() => {
      const online = getIsOnlineSnapshot();
      if (online && !wasOnline && !readyRef.current) {
        setGeneration((value) => value + 1);
      }
      wasOnline = online;
    });
  }, [loadFrame]);

  function retry() {
    setReady(false);
    setGeneration((value) => value + 1);
  }

  // Leaving a sheet whose questionnaire never arrived drops that attempt, so
  // the next opening starts a fresh load instead of showing the old failure.
  function leave() {
    if (unavailable) retry();
    onCancel();
  }

  const showFrame = open && ready;

  return (
    <>
      <Sheet
        open={open}
        onClose={leave}
        // No enter animation. The questionnaire below is portalled into a
        // separate, non-animated overlay, so a sliding surface meant the header
        // travelled up alone past an already-stationary questionnaire — which
        // read as the title animating in on its own.
        slideFrom="none"
        ariaLabel={t("Daily check-in")}
        zIndex={50}
        // On a tablet the surface becomes the dim layer behind a centred card.
        // Not tap-to-dismiss: this sheet stands in front of a workout start,
        // and a stray tap beside the card must not cancel it.
        // The sheet colour (`bg-surface-drawer`), like every other sheet — the
        // connect sheet's BottomSheetCard included — not the page's black.
        className="flex flex-col bg-surface-drawer pt-[env(safe-area-inset-top)] tablet:items-center tablet:justify-center tablet:bg-black/40 tablet:pt-0"
      >
        <div
          className={`flex min-h-0 flex-1 flex-col tablet:flex-none tablet:overflow-hidden tablet:rounded-3xl tablet:bg-surface-drawer tablet:shadow-xl ${CARD_BOX}`}
        >
          <header
            // Measured in a ref callback rather than an effect: the overlay below
            // is a sibling of this element (different portal), so it can't inherit
            // the offset through layout.
            //
            // HEIGHT, not `bottom`: a height is the one measurement that stays
            // meaningful wherever the surface happens to be, which kept this
            // correct back when the Sheet still slid in from `translate-y-full`
            // and the element was off-screen at mount. The safe-area inset it sits
            // below is added back on the overlay itself, which is the one thing a
            // height can't carry across the portal boundary.
            ref={(node) => {
              if (node) setHeaderHeight(node.getBoundingClientRect().height);
            }}
            className="flex shrink-0 items-center justify-between gap-3 px-5 pt-4 pb-2"
          >
            {/* Title only. How to answer is the service's to say — it puts that
              line under the first question, where it is read. */}
            <div className="flex min-w-0 items-center gap-3">
              {/* Answering for someone else is the one case that must never be
                ambiguous — the answers are attributed to them, and nothing else
                on screen would say so. Their face says it faster than the
                name. */}
              {subjectName && (
                <AthleteAvatar
                  userID={subject?.id}
                  name={subjectName}
                  size={48}
                  className="heading-small"
                />
              )}
              <div className="min-w-0">
                <h1 className="heading-normal">{t("Daily check-in")}</h1>
                {subjectName && (
                  <p className="body-prominent truncate text-foreground-default">
                    {t("For {name}", { name: subjectName })}
                  </p>
                )}
              </div>
            </div>
            <button
              type="button"
              onClick={leave}
              aria-label={t("Close")}
              className={HEADER_ICON_BUTTON}
            >
              <CloseXIcon className="size-5" />
            </button>
          </header>

          {/* Only seen when the frame wasn't preloaded in time — normally the
            questionnaire is already there when the sheet opens. In front of a
            workout start the spinner stays through a failure too: the sheet is
            about to close and the training to start. */}
          {ready ? null : unavailable && !startsWorkout ? (
            <QuestionnaireUnavailable
              reason={unavailable}
              title={
                unavailable === "offline"
                  ? t("You're offline")
                  : t("Couldn't load the check-in")
              }
              body={
                unavailable === "offline"
                  ? t(
                      "The check-in needs a connection to load. Do it when you're back online — your training isn't affected.",
                    )
                  : t(
                      "The questions didn't arrive. Try again, or do it later — your training isn't affected.",
                    )
              }
              onRetry={retry}
              onLater={leave}
            />
          ) : (
            <div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-3">
              <SpinnerIcon className="size-6 animate-spin text-foreground-muted" />
              <span className="body-small text-foreground-muted">
                {t("Loading your check-in…")}
              </span>
            </div>
          )}
        </div>
      </Sheet>

      {src
        ? createPortal(
            <div
              // Transparent and inset below the header, so the sheet's title
              // shows through above the questionnaire. Hidden — not unmounted —
              // whenever the sheet is closed or the frame isn't ready: a hidden
              // iframe still loads, which is the whole point.
              //
              // Phone: the safe-area inset has to be added explicitly. This
              // overlay is `fixed inset-0` from the VIEWPORT top, while the
              // header it sits below is inside a Sheet padded by
              // `pt-[env(safe-area-inset-top)]` — so offsetting by the header
              // height alone starts the questionnaire one status-bar height too
              // high, straight over the title. The bottom inset belongs here
              // too, not inside the frame: the service's footer (Next / Back)
              // is its last flex child, so without it the buttons sit under the
              // iOS home indicator. `env()` is only reliable in the top-level
              // document, which is exactly why the host owns both safe areas.
              //
              // Tablet: the card's box, centred like the card, below its
              // header. The card sits clear of both safe areas, so no insets.
              className={`fixed inset-0 pt-[calc(env(safe-area-inset-top)+var(--check-in-header))] pb-[env(safe-area-inset-bottom)] tablet:inset-auto tablet:top-1/2 tablet:left-1/2 tablet:-translate-x-1/2 tablet:-translate-y-1/2 tablet:overflow-hidden tablet:rounded-b-3xl tablet:pt-[var(--check-in-header)] tablet:pb-0 ${CARD_BOX}`}
              style={{
                zIndex: 51,
                // Custom properties are valid inline styles React's type does
                // not list — the same cast as elsewhere in the app.
                ...({
                  "--check-in-header": `${headerHeight}px`,
                } as CSSProperties),
                visibility: showFrame ? "visible" : "hidden",
                // NEVER on the wrapper. It spans the whole viewport, so its
                // transparent top strip — the part you see the sheet's title and
                // close button THROUGH — would swallow every tap aimed at them,
                // leaving the X visible but dead. Input belongs to the iframe
                // alone, which is the only part that actually renders anything.
                pointerEvents: "none",
              }}
              aria-hidden={!showFrame}
            >
              <iframe
                ref={frameRef}
                // Remounting on `generation` is what reloads a used
                // questionnaire — same URL, fresh document.
                // The SUBJECT is part of the key: retargeting the questionnaire
                // must remount it. Re-posting `auth` alone would leave any
                // answers already entered attached to the new athlete.
                key={`${subjectId}:${generation}`}
                src={src}
                title={t("Daily check-in")}
                className="h-full w-full border-0"
                style={{ pointerEvents: showFrame ? "auto" : "none" }}
              />
            </div>,
            overlayPortalHost(),
          )
        : null}
    </>
  );
}
