// login.jsx — login screen with Supabase auth
const { useState: useStateL } = React;

const PHASE_LABEL = {
  auth:    "Verifying credentials…",
  profile: "Loading your workspace…",
  done:    "Welcome back!",
};
const PHASE_WIDTH = { auth: "38%", profile: "72%", done: "100%" };

function LoginPage({ onLogin }) {
  const [email, setEmail] = useStateL("");
  const [pw, setPw] = useStateL("");
  const [showPw, setShowPw] = useStateL(false);
  const [busy, setBusy] = useStateL(false);
  const [phase, setPhase] = useStateL("idle");
  const [error, setError] = useStateL(null);

  async function submit(e) {
    e?.preventDefault();
    setBusy(true);
    setError(null);
    setPhase("auth");

    try {
      const { data, error: authErr } = await sb.auth.signInWithPassword({ email, password: pw });
      if (authErr) throw authErr;

      // check sessionStorage cache to skip second round-trip
      const cacheKey = `trapo_profile_${data.user.id}`;
      let profile = null;
      try { const c = sessionStorage.getItem(cacheKey); if (c) profile = JSON.parse(c); } catch {}

      if (!profile) {
        setPhase("profile");
        const { data: p, error: profErr } = await sb.from("profiles")
          .select("role, name, initials, color")
          .eq("id", data.user.id)
          .single();
        if (profErr || !p) throw new Error("Profile not found. Ask your admin to set up your account.");
        profile = p;
        try { sessionStorage.setItem(cacheKey, JSON.stringify(profile)); } catch {}
      }

      // broadcast concurrent-login event to any existing session on this account
      try {
        const ch = sb.channel(`user-session-${data.user.id}`);
        await ch.subscribe((status) => {
          if (status === "SUBSCRIBED") {
            ch.send({ type: "broadcast", event: "new_login", payload: { at: new Date().toISOString() } });
          }
        });
        // clean up after a moment — this channel is only for sending
        setTimeout(() => sb.removeChannel(ch), 2000);
      } catch {}

      setPhase("done");
      setTimeout(() => onLogin(profile.role, data.user, profile), 500);
    } catch (err) {
      setError(err.message || "Sign-in failed. Check your email and password.");
      setBusy(false);
      setPhase("idle");
    }
  }

  const isDone = phase === "done";

  return (
    <div className="flex h-screen w-screen overflow-hidden bg-white" style={{ fontFamily: "var(--font-ui)" }}>

      {/* top progress bar */}
      {busy && (
        <div className="fixed top-0 left-0 right-0 h-[2.5px] z-50 bg-zinc-100">
          <div style={{ width: PHASE_WIDTH[phase] || "10%", background: isDone ? "#10b981" : "var(--accent)", transition: "width 0.5s cubic-bezier(.4,0,.2,1), background 0.3s" }} className="h-full rounded-r-full" />
        </div>
      )}

      {/* left brand panel */}
      <div className="hidden lg:flex flex-col justify-between w-[44%] max-w-[560px] p-10 text-zinc-300 relative overflow-hidden" style={{ background: "#0a0a0a" }}>
        <div className="absolute inset-0 opacity-[0.4]" style={{ background: "radial-gradient(600px 300px at 20% 0%, rgba(13,148,136,0.18), transparent 70%)" }} />
        <div className="relative flex items-center gap-2.5">
          <div className="flex items-center justify-center w-9 h-9 rounded-lg font-bold text-white text-[17px]" style={{ background: "#0d9488" }}>T</div>
          <div className="leading-tight">
            <div className="text-white font-semibold text-[15px] tracking-tight">TRAPO <span className="text-zinc-500 font-normal">OpsPilot</span></div>
            <div className="text-[11px] text-zinc-500">Internal Operations Platform</div>
          </div>
        </div>

        <div className="relative">
          <h2 className="text-[26px] font-semibold text-white leading-tight tracking-tight">Exception management,<br />on autopilot.</h2>
          <p className="text-[13.5px] text-zinc-400 mt-3 leading-relaxed max-w-sm">
            AI-surfaced exceptions, role-based workflows and a single operational view across orders, warranty and installations.
          </p>
          <div className="grid grid-cols-3 gap-4 mt-8 max-w-sm">
            {[["1,284","Active orders"],["47","Open today"],["4.2h","Avg resolution"]].map(([n,l]) => (
              <div key={l}>
                <div className="text-[22px] font-semibold text-white tabular-nums tracking-tight">{n}</div>
                <div className="text-[11px] text-zinc-500 mt-0.5">{l}</div>
              </div>
            ))}
          </div>
        </div>

        <div className="relative text-[11px] text-zinc-600">© 2026 TRAPO Sdn Bhd · Authorised personnel only</div>
      </div>

      {/* right form */}
      <div className={`flex-1 flex items-center justify-center px-6 py-10 overflow-y-auto transition-opacity duration-300 ${isDone ? "opacity-0" : "opacity-100"}`}>
        <form onSubmit={submit} className="w-full max-w-[380px]">
          {/* mobile logo */}
          <div className="lg:hidden flex items-center gap-2.5 mb-8">
            <div className="flex items-center justify-center w-9 h-9 rounded-lg font-bold text-white text-[17px]" style={{ background: "#0d9488" }}>T</div>
            <span className="font-semibold text-[15px] text-zinc-900">TRAPO OpsPilot</span>
          </div>

          <h1 className="text-[20px] font-semibold text-zinc-900 tracking-tight">Sign in to your workspace</h1>
          <p className="text-[13px] text-zinc-500 mt-1">Use your TRAPO operations credentials.</p>

          {/* error banner */}
          {error && (
            <div className="mt-4 flex items-start gap-2 px-3 py-2.5 rounded-lg bg-red-50 border border-red-200 text-[12.5px] text-red-700">
              <Icon name="alert" size={14} className="mt-0.5 shrink-0" />
              <span>{error}</span>
            </div>
          )}

          {/* email */}
          <label className="block mt-6">
            <span className="text-[12.5px] font-medium text-zinc-700">Work email</span>
            <div className="flex items-center gap-2 mt-1.5 h-10 px-3 rounded-lg border border-zinc-300 focus-within:border-zinc-900 focus-within:ring-2 focus-within:ring-zinc-900/5 transition-all bg-white">
              <Icon name="mail" size={16} className="text-zinc-400" />
              <input type="email" value={email} onChange={e => setEmail(e.target.value)} required disabled={busy}
                placeholder="you@trapo.co"
                className="flex-1 bg-transparent outline-none text-[13.5px] text-zinc-800 placeholder:text-zinc-300 disabled:opacity-60" />
            </div>
          </label>

          {/* password */}
          <label className="block mt-4">
            <div className="flex items-center justify-between mb-1.5">
              <span className="text-[12.5px] font-medium text-zinc-700">Password</span>
              <a href="#" className="text-[12px] font-medium" style={{ color: "var(--accent-ink)" }}>Forgot password?</a>
            </div>
            <div className="flex items-center gap-2 h-10 px-3 rounded-lg border border-zinc-300 focus-within:border-zinc-900 focus-within:ring-2 focus-within:ring-zinc-900/5 transition-all bg-white">
              <Icon name="lock" size={16} className="text-zinc-400" />
              <input type={showPw ? "text" : "password"} value={pw} onChange={e => setPw(e.target.value)} required disabled={busy}
                placeholder="••••••••"
                className="flex-1 bg-transparent outline-none text-[13.5px] text-zinc-800 placeholder:text-zinc-300 disabled:opacity-60" />
              <button type="button" onClick={() => setShowPw(s => !s)} className="text-zinc-400 hover:text-zinc-600">
                <Icon name={showPw ? "eyeoff" : "eye"} size={16} />
              </button>
            </div>
          </label>

          <button type="submit" disabled={busy}
            className="mt-6 w-full h-10 rounded-lg text-white text-[14px] font-semibold inline-flex items-center justify-center gap-2 transition-all hover:brightness-110 active:brightness-95 disabled:cursor-not-allowed"
            style={{ background: isDone ? "#10b981" : "var(--accent)", transition: "background 0.3s, opacity 0.2s", opacity: busy && !isDone ? 0.85 : 1 }}>
            {busy
              ? <><Icon name={isDone ? "check" : "refresh"} size={16} className={isDone ? "" : "animate-spin"} /> {PHASE_LABEL[phase]}</>
              : <>Sign in <Icon name="arrow_r" size={16} /></>
            }
          </button>

          <div className="mt-4 flex items-center gap-1.5 text-[12px]">
            <input type="checkbox" id="keep" defaultChecked className="rounded border-zinc-300 accent-teal-600" />
            <label htmlFor="keep" className="text-zinc-500 cursor-pointer">Keep me signed in</label>
          </div>

          <div className="mt-7 pt-5 border-t border-zinc-100 flex items-start gap-2 text-[11.5px] text-zinc-400 leading-relaxed">
            <Icon name="shieldcheck" size={14} className="mt-0.5 shrink-0 text-zinc-400" />
            <span>This is a restricted internal system. Access is logged and monitored. Unauthorised use is prohibited.</span>
          </div>
        </form>
      </div>
    </div>
  );
}

Object.assign(window, { LoginPage });
