"use client";

import { takePortalReturnTo } from "./return-to";
import { useEffect, useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import { getToken } from "@enode/core/api/storage";
import {
  DEFAULT_PRO_LICENSE_BASE_ID,
  type AuthFlavorConfig,
} from "@enode/core/auth/flavor-config";
import { useAuthFlow } from "@enode/core/auth/use-auth-flow";
import { useTranslation } from "@enode/core/translations/hooks";
import { AuthSteps } from "@enode/ui/auth/auth-steps";
import { Button } from "@enode/ui/button";
import {
  WELCOME_LANGUAGE_MENU_ENABLED,
  WelcomeLanguageMenu,
} from "@enode/ui/language-picker";

// The Portal's auth entry. Both One and Pro users may sign in (One users mainly
// come here to migrate their legacy data); registration is Pro-only. The shared
// flow + steps live in @enode/core + @enode/ui — this page supplies the Portal
// config and the decorative chrome. Deliberately a sibling of the tracking app's
// page (same flow, different config + post-auth destination).
const HOME_ROUTE = "/dashboard";

// The portal demo is a separate deployment (the portal built with
// NEXT_PUBLIC_DEMO=1, see docs/demo.md). The demo build itself never shows the
// entry: it is already the demo.
const DEMO_PORTAL_URL = "https://demo.portal.enode.ai";
const IS_DEMO_BUILD = process.env.NEXT_PUBLIC_DEMO === "1";
const REGISTER_LICENSE_BASE_ID =
  process.env.NEXT_PUBLIC_PRO_LICENSE_BASE_ID ?? DEFAULT_PRO_LICENSE_BASE_ID;

export default function WelcomePage() {
  const router = useRouter();
  const { t } = useTranslation();
  const [hydrated, setHydrated] = useState(false);
  const [hasToken, setHasToken] = useState(false);

  const config = useMemo<AuthFlavorConfig>(
    () => ({
      flavor: "portal",
      registerLicenseBaseID: REGISTER_LICENSE_BASE_ID,
      allowOneLogin: true,
      enableLegacyMigration: true,
      onAuthenticated: () => router.replace(takePortalReturnTo() ?? HOME_ROUTE),
    }),
    [router],
  );
  const controller = useAuthFlow(config);

  // Cold-start: if a token is already stored, jump straight into the portal
  // instead of flashing the welcome screen. The hydration gate inherently needs
  // an effect, so set-state-in-effect is suppressed.
  /* eslint-disable react-hooks/set-state-in-effect */
  useEffect(() => {
    if (getToken()) {
      router.replace(takePortalReturnTo() ?? HOME_ROUTE);
      setHasToken(true);
      return;
    }
    setHydrated(true);
  }, [router]);
  /* eslint-enable react-hooks/set-state-in-effect */

  // Don't render anything until we've decided whether to redirect, so the user
  // never sees the welcome screen flash before being moved on.
  if (!hydrated || hasToken) return null;

  return (
    <main className="relative flex min-h-screen w-full flex-col md:flex-row">
      {/* Left pane (mobile: top) — a brand panel that follows the theme: a light
          platinum-green→light gradient in light mode, dark teal→near-black in
          dark mode, so it harmonises with the form pane. */}
      <section className="relative flex flex-col items-center justify-center gap-10 bg-linear-to-b from-welcome-brand-from to-welcome-brand-to-portal to-[82%] px-6 pt-16 pb-8 max-sm:flex-row max-sm:justify-start max-sm:gap-0 max-sm:py-4 text-foreground-default md:w-1/2 md:px-12 md:py-16">
        <DotPattern className="absolute inset-0" />
        {/* Language before sign-in — stored on this device, wins over the
            account setting after sign-in (locale-choice.ts). */}
        {WELCOME_LANGUAGE_MENU_ENABLED ? (
          <WelcomeLanguageMenu className="absolute right-3 top-3 z-10 md:right-6 md:top-6" />
        ) : null}
        <EnodeWordmark className="relative h-7 w-auto sm:h-10 md:h-12" />
        <DecorationLines className="relative -mx-6 self-stretch md:-mx-12 max-sm:hidden" />
        <p className="relative hidden text-center text-foreground-muted md:block md:max-w-sm">
          {t(
            "Our cutting-edge technology used weekly by thousands of professional athletes is now available to everyone.",
          )}
        </p>
      </section>

      {/* Right pane (mobile: bottom) — the shared auth flow. */}
      <section className="flex flex-1 flex-col items-stretch bg-surface-base px-6 py-16 max-sm:py-8 text-foreground-default md:border-l md:border-surface-stroke md:px-12 md:py-16">
        <div className="mx-auto flex w-full max-w-sm flex-1 flex-col justify-center gap-6">
          <AuthSteps controller={controller} flavor="portal" />
          {controller.state.step === "welcome" && !IS_DEMO_BUILD ? (
            <DemoEntry />
          ) : null}
        </div>
      </section>
    </main>
  );
}

// Leads visitors without an account to the demo portal (a sample club, no
// sign-in). Leaves this site, so it is a full navigation, not a router push.
function DemoEntry() {
  const { t } = useTranslation();
  return (
    <div className="space-y-3 border-t border-surface-stroke pt-6">
      <p className="body-normal text-foreground-muted">
        {t("Just looking around? Explore the portal with a sample club — no account needed.")}
      </p>
      <Button
        variant="tertiary"
        size="large"
        onClick={() => window.location.assign(DEMO_PORTAL_URL)}
      >
        {t("Try the demo")}
      </Button>
    </div>
  );
}

// ─── Decoration ───────────────────────────────────────────────────────────

// Three horizontal lines (the enodeColors/lollipop accent palette) with
// end-dots, mirroring the iOS welcome decoration. Rendered as HTML so the
// vertical spacing between lines is a CSS gap that stays static regardless of
// width.
function DecorationLines({ className }: { className?: string }) {
  return (
    <div aria-hidden="true" className={`flex flex-col gap-4 ${className ?? ""}`}>
      <Lollipop color="var(--color-lollipop-first)" widthPct={78} />
      <Lollipop color="var(--color-lollipop-middle)" widthPct={58} />
      <Lollipop color="var(--color-lollipop-last)" widthPct={42} />
    </div>
  );
}

function Lollipop({ color, widthPct }: { color: string; widthPct: number }) {
  return (
    <div className="relative h-2.5 shrink-0" style={{ width: `${widthPct}%` }}>
      <div
        className="absolute inset-y-1/2 left-0 right-2.5 h-[2px] -translate-y-1/2 rounded-full"
        style={{ backgroundColor: color }}
      />
      <div
        className="absolute right-0 top-0 size-2.5 rounded-full"
        style={{ backgroundColor: color }}
      />
    </div>
  );
}

// Iconic Enode dot cloud, rendered as a tiled CSS radial gradient. A radial mask
// fades the dots out toward the form pane so the centre of the graphic side
// feels lighter, matching the iOS reference.
function DotPattern({ className }: { className?: string }) {
  return (
    <div
      aria-hidden="true"
      className={`pointer-events-none ${className ?? ""}`}
      style={{
        backgroundImage:
          "radial-gradient(circle, rgba(255,255,255,0.18) 1px, transparent 1.5px)",
        backgroundSize: "14px 14px",
        WebkitMaskImage:
          "radial-gradient(ellipse at top left, black 0%, transparent 80%)",
        maskImage: "radial-gradient(ellipse at top left, black 0%, transparent 80%)",
      }}
    />
  );
}

// Enode wordmark — square pictogram + word, recoloured via currentColor.
function EnodeWordmark({ className }: { className?: string }) {
  return (
    <svg
      viewBox="0 0 185 40"
      fill="none"
      xmlns="http://www.w3.org/2000/svg"
      className={className}
      aria-label="enode"
      role="img"
    >
      <path
        d="M75.1184 8.4733H80.3904V11.503C82.0157 9.61587 84.916 8.03369 88.9131 8.03369C95.3274 8.03369 98.9305 12.5129 98.9305 18.9664V31.5228H93.6585V19.8456C93.6585 15.7624 91.5501 12.8634 87.2877 12.8634C82.8057 12.8634 80.3904 15.6733 80.3904 19.9327V31.5248H75.1184V8.4733Z"
        fill="currentColor"
      />
      <path
        d="M127.69 20.0218C127.69 27.1782 121.848 32.0079 114.554 32.0079C107.261 32.0079 101.375 27.1782 101.375 20.0218C101.375 12.8653 107.218 8.03564 114.554 8.03564C121.891 8.03564 127.69 12.8653 127.69 20.0218ZM122.638 20.0218C122.638 15.3248 119.037 12.5564 114.554 12.5564C110.072 12.5564 106.428 15.3228 106.428 20.0218C106.428 24.7208 110.029 27.4871 114.554 27.4871C119.08 27.4871 122.638 24.7208 122.638 20.0218Z"
        fill="currentColor"
      />
      <path
        d="M141.997 32.0099C134.047 32.0099 129.345 26.5644 129.345 20.0238C129.345 13.4832 134.045 8.03762 141.997 8.03762C146.214 8.03762 149.291 9.6198 150.96 11.4178V0H156.232V31.5267H150.96V28.6297C149.291 30.4297 146.214 32.0099 141.997 32.0099ZM142.746 12.4257C138.22 12.4257 134.354 15.1485 134.354 20.0218C134.354 24.8951 138.22 27.6178 142.746 27.6178C147.533 27.6178 151.225 24.4119 151.225 20.198V19.8475C151.225 15.6317 147.535 12.4277 142.746 12.4277V12.4257Z"
        fill="currentColor"
      />
      <path
        d="M66.972 24.2158C65.5842 26.2297 63.1313 27.5287 59.9974 27.5287C55.6916 27.5287 52.3973 25.2455 51.6925 21.5584H72.3845V19.7149C72.3845 13.0832 67.5956 8.03564 59.9955 8.03564C52.3953 8.03564 46.6838 13.2614 46.6838 20.0218C46.6838 27.1366 52.3062 32.0079 59.9955 32.0079C64.9982 32.0079 68.7973 29.802 70.8146 27.0554L66.97 24.2139L66.972 24.2158ZM59.7341 12.4238C64.0836 12.4238 66.9403 15.1901 67.2907 17.604H51.9143C52.9239 14.2238 56.0895 12.4238 59.7341 12.4238Z"
        fill="currentColor"
      />
      <path
        d="M179.491 24.2158C178.103 26.2297 175.648 27.5287 172.516 27.5287C168.211 27.5287 164.916 25.2455 164.212 21.5584H184.904V19.7149C184.904 13.0832 180.117 8.03564 172.515 8.03564C164.912 8.03564 159.203 13.2614 159.203 20.0218C159.203 27.1366 164.825 32.0079 172.515 32.0079C177.517 32.0079 181.316 29.802 183.334 27.0554L179.489 24.2139L179.491 24.2158ZM172.253 12.4238C176.603 12.4238 179.457 15.1901 179.81 17.604H164.431C165.441 14.2238 168.607 12.4238 172.253 12.4238Z"
        fill="currentColor"
      />
      <path
        d="M5.83621 29.1663H4.16731V26.6673C30.0125 26.6673 36.6822 24.1683 36.6822 20C36.6822 15.8317 30.0125 13.3327 4.16731 13.3327V10.8337H5.83621C34.1818 10.8337 40.02 5.83366 40.02 0H18.3421C18.3421 10 0 5.00198 0 12.0614C0 18.3347 14.1748 15 14.1748 20C14.1748 25 0 21.6673 0 27.9406C0 35.002 18.3421 30.002 18.3421 40H40.02C40.02 34.1683 34.1838 29.1683 5.83819 29.1683L5.83621 29.1663Z"
        fill="currentColor"
      />
    </svg>
  );
}
