// MFM Chat — Auth surface (state machine).
// Views: "signin" (Google-first) → "magic-request" → "magic-sent",
// plus the "no-account" permission error. All share one shell: logo
// top-left, centered content, decorative illustration along the bottom.

// Official multi-colour Google "G". Sits on a white chip so it stays legible
// on the brand-filled button.
const GoogleG = ({ size = 18 }) => (
  <svg width={size} height={size} viewBox="0 0 18 18" aria-hidden="true">
    <path fill="#4285F4" d="M17.64 9.205c0-.639-.057-1.252-.164-1.841H9v3.481h4.844a4.14 4.14 0 0 1-1.796 2.716v2.259h2.908c1.702-1.567 2.684-3.875 2.684-6.615z"/>
    <path fill="#34A853" d="M9 18c2.43 0 4.467-.806 5.956-2.18l-2.908-2.259c-.806.54-1.837.86-3.048.86-2.344 0-4.328-1.583-5.036-3.711H.957v2.332A8.997 8.997 0 0 0 9 18z"/>
    <path fill="#FBBC05" d="M3.964 10.71A5.41 5.41 0 0 1 3.682 9c0-.593.102-1.17.282-1.71V4.958H.957A8.996 8.996 0 0 0 0 9c0 1.452.348 2.827.957 4.042l3.007-2.332z"/>
    <path fill="#EA4335" d="M9 3.58c1.321 0 2.508.454 3.44 1.345l2.582-2.58C13.463.891 11.426 0 9 0A8.997 8.997 0 0 0 .957 4.958L3.964 7.29C4.672 5.163 6.656 3.58 9 3.58z"/>
  </svg>
);

// Simple envelope glyph (the kit has no mail icon).
const EnvelopeIcon = ({ size = 22 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
    <rect x="2.5" y="4.5" width="19" height="15" rx="2.5" />
    <path d="M3 6.5l8.4 6.1a1 1 0 0 0 1.2 0L21 6.5" />
  </svg>
);

const GoogleSignInButton = ({ onClick }) => (
  <button
    type="button"
    onClick={onClick}
    className="btn-fill-hover flex h-12 w-full items-center justify-center gap-3 rounded-md bg-primary px-4 text-[15px] font-medium text-primary-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"
  >
    <span className="flex h-6 w-6 items-center justify-center rounded-full bg-white">
      <GoogleG size={16} />
    </span>
    Sign in with Google
  </button>
);

// Back-to-sign-in text link, shared by the secondary views.
const BackLink = ({ onClick }) => (
  <button
    type="button"
    onClick={onClick}
    className="inline-flex items-center gap-1.5 text-sm font-normal text-foreground transition-colors hover:text-[color:var(--brand)]"
  >
    <span style={{ display: "inline-flex", transform: "rotate(-90deg)" }}><ArrowUpIcon size={13} /></span>
    Back to sign in
  </button>
);

// Heading block reused across views.
const AuthHeading = ({ title, children }) => (
  <div className="flex flex-col items-center justify-center gap-1.5 px-4 text-center sm:px-12">
    <h3 className="text-xl font-semibold text-foreground">{title}</h3>
    <p className="text-sm leading-relaxed text-muted-foreground">{children}</p>
  </div>
);

// Round icon medallion atop the status views.
const AuthMedallion = ({ tone = "brand", children }) => {
  const styles =
    tone === "brand"
      ? { background: "color-mix(in oklab, var(--brand) 14%, transparent)", color: "var(--brand)" }
      : { background: "var(--secondary)", color: "var(--muted-foreground)" };
  return (
    <span className="flex h-14 w-14 items-center justify-center rounded-full" style={styles}>
      {children}
    </span>
  );
};

// ── View: sign in (Google-first) ──────────────────────────────────────
const SignInView = ({ onGoogle, onMagic }) => (
  <div className="flex w-full max-w-md flex-col gap-10">
    <AuthHeading title="Sign in to IRIS">Continue with your MFM Google account.</AuthHeading>
    <div className="flex flex-col items-center gap-5 px-4 sm:px-12">
      <GoogleSignInButton onClick={onGoogle} />
      <Button
        variant="link"
        size="sm"
        className="font-normal text-foreground transition-colors hover:text-[color:var(--brand)] hover:no-underline"
        onClick={onMagic}
      >
        Request a magic link
      </Button>
    </div>
  </div>
);

// ── View: request a magic link (email + send) ─────────────────────────
const MagicRequestView = ({ email, setEmail, onSend, onBack }) => {
  const valid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim());
  return (
    <div className="flex w-full max-w-md flex-col gap-10">
      <AuthHeading title="Sign in with a magic link">
        Enter your MFM email and we'll send a one-time link to sign you in — no password needed.
      </AuthHeading>
      <form
        className="flex flex-col items-center gap-4 px-4 sm:px-12"
        onSubmit={(e) => { e.preventDefault(); if (valid) onSend(email.trim()); }}
      >
        <input
          type="email"
          autoFocus
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          placeholder="you@mfm.agency"
          className="brand-input h-12 w-full rounded-md border border-input bg-background px-3.5 text-sm text-foreground placeholder:text-muted-foreground"
        />
        <button
          type="submit"
          disabled={!valid}
          className="btn-fill-hover flex h-12 w-full items-center justify-center rounded-md bg-primary px-4 text-[15px] font-medium text-primary-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:pointer-events-none disabled:opacity-50"
        >
          Send magic link
        </button>
        <BackLink onClick={onBack} />
      </form>
    </div>
  );
};

// ── View: check your inbox ────────────────────────────────────────────
const MagicSentView = ({ email, onResend, onBack }) => {
  const [secs, setSecs] = React.useState(180); // 3:00 cooldown before resend
  React.useEffect(() => {
    if (secs <= 0) return;
    const id = setInterval(() => setSecs((s) => (s <= 1 ? 0 : s - 1)), 1000);
    return () => clearInterval(id);
  }, [secs]);
  const mm = Math.floor(secs / 60);
  const ss = String(secs % 60).padStart(2, "0");
  const ready = secs <= 0;

  return (
    <div className="flex w-full max-w-md flex-col gap-10">
      <AuthHeading title="Check your inbox">
        We sent a magic link to <span className="font-medium text-foreground">{email}</span>. Open it to sign in — the link expires in 15 minutes.
      </AuthHeading>
      <div className="flex flex-col items-center gap-5 px-4 sm:px-12">
        <button
          type="button"
          disabled={!ready}
          onClick={() => { if (ready) { onResend && onResend(); setSecs(180); } }}
          className="flex h-11 w-full items-center justify-center rounded-md border border-input bg-background px-5 text-sm font-medium text-foreground transition-colors hover:bg-accent hover:text-accent-foreground disabled:pointer-events-none disabled:opacity-50"
        >
          {ready ? "Resend" : `Resend in ${mm}:${ss}`}
        </button>
        <BackLink onClick={onBack} />
      </div>
    </div>
  );
};

// ── View: no account / permission error ───────────────────────────────
const NoAccountView = ({ email, onBack }) => (
  <div className="flex w-full max-w-md flex-col gap-10">
    <AuthHeading title="No account found">
      We couldn't find an IRIS account for <span className="font-medium text-foreground">{email}</span>. Contact your admin to get access.
    </AuthHeading>
    <div className="flex flex-col items-center gap-5 px-4 sm:px-12">
      <BackLink onClick={onBack} />
    </div>
  </div>
);

// ── Shell + state machine ─────────────────────────────────────────────
const AuthScreen = ({ mode = "login", onSubmit, initialView, initialEmail }) => {
  // Preview shortcut: ?auth=signin|magic-request|magic-sent|no-account jumps
  // straight to a view (and ?email= prefills the address shown).
  const params = typeof window !== "undefined" ? new URLSearchParams(window.location.search) : new URLSearchParams();
  const startView = initialView
    || (["signin", "magic-request", "magic-sent", "no-account"].includes(params.get("auth")) ? params.get("auth") : "signin");
  const [view, setView] = React.useState(startView);
  const [email, setEmail] = React.useState(initialEmail || params.get("email") || "jaap@mfm.agency");

  // Demo routing: provisioned MFM emails get a link; anything else hits the
  // "no account" wall (mirrors admin-managed access).
  const handleSend = (value) => {
    const provisioned = /@mfm\.(agency|com)$/i.test(value);
    setView(provisioned ? "magic-sent" : "no-account");
  };

  const body =
    view === "signin" ? (
      <SignInView
        onGoogle={() => onSubmit && onSubmit({ method: "google" })}
        onMagic={() => setView("magic-request")}
      />
    ) : view === "magic-request" ? (
      <MagicRequestView email={email} setEmail={setEmail} onSend={handleSend} onBack={() => setView("signin")} />
    ) : view === "magic-sent" ? (
      <MagicSentView email={email} onResend={() => {}} onBack={() => setView("signin")} />
    ) : (
      <NoAccountView email={email} onBack={() => setView("signin")} />
    );

  return (
    <div className="relative flex h-full w-full flex-col overflow-hidden bg-background">
      <header className="flex items-center px-5 py-4 md:px-8">
        <img src="../../assets/logos/mfm-mark-orange.svg" alt="MFM" width="64" height="30" style={{ display: "block" }} />
      </header>

      {/* Bottom padding = the illustration's rendered height (it's full-width,
          so height = 100vw × 670/2880 ≈ 23.3vw) → content centers in the gap. */}
      <div className="relative z-10 flex flex-1 flex-col items-center justify-center px-4" style={{ paddingBottom: "23.3vw" }}>
        {body}
      </div>

      {/* Decorative illustration pinned to the bottom edge, full-width. */}
      {["assets/welcome-illo.png", "assets/welcome-illo-dark.png"].map((src, i) => (
        <img
          key={src}
          src={src}
          alt=""
          aria-hidden="true"
          className={i === 0 ? "welcome-illo-light" : "welcome-illo-dark"}
          style={{ position: "absolute", left: 0, bottom: 0, width: "100%", height: "auto", pointerEvents: "none", userSelect: "none", zIndex: 0 }}
        />
      ))}

      {/* Preview-only state switcher (like the theme toggle) — not shipped. */}
      <AuthStateSwitcher view={view} setView={setView} />
    </div>
  );
};

// Preview-only segmented control to jump between the four auth states without
// having to type emails. Mirrors the dev theme toggle; would be removed in prod.
const AUTH_STATES = [
  { key: "signin", label: "Sign in" },
  { key: "magic-request", label: "Request link" },
  { key: "magic-sent", label: "Check inbox" },
  { key: "no-account", label: "No account" },
];
const AuthStateSwitcher = ({ view, setView }) => (
  <div
    className="fixed bottom-3 left-3 z-50 flex items-center gap-1.5 rounded-lg border border-border p-1"
    style={{ background: "var(--card)", boxShadow: "var(--shadow-md)" }}
  >
    <span className="px-1.5 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">State</span>
    {AUTH_STATES.map((s) => (
      <button
        key={s.key}
        type="button"
        onClick={() => setView(s.key)}
        aria-pressed={view === s.key}
        className="rounded-md px-2 py-1 text-xs font-medium transition-colors"
        style={
          view === s.key
            ? { background: "var(--secondary)", color: "var(--foreground)" }
            : { background: "transparent", color: "var(--muted-foreground)" }
        }
      >
        {s.label}
      </button>
    ))}
    {/* Simulates the invited-user entry (clicking the email invite) → onboarding. */}
    <span className="mx-0.5 h-4 w-px" style={{ background: "var(--border)" }}></span>
    <button
      type="button"
      onClick={() => { window.location.href = "Onboarding.html"; }}
      className="rounded-md px-2 py-1 text-xs font-medium text-muted-foreground transition-colors hover:text-[color:var(--brand)]"
      title="Simulate clicking the email invite — start onboarding"
    >
      Invite ↗
    </button>
  </div>
);

Object.assign(window, { AuthScreen, GoogleSignInButton, GoogleG });
