// ============================================================================
// public/screens/auth.jsx — Login + Signup (real, backend-wired)
// ----------------------------------------------------------------------------
// Mirrors the design from voais_ui/screens/dashboard.jsx::AuthScreen, but
// every interaction calls VoaisAPI and surfaces real errors / loading states.
// On success, onAuth(sessionObject) is invoked so the shell can route to the
// dashboard.
// ============================================================================

const { useState, useEffect, useRef, useCallback } = React;

function AuthScreen({ onAuth }) {
  const [mode, setMode] = useState("login");      // "login" | "signup" | "admin"
  const [showPw, setShowPw] = useState(false);
  const [error, setError] = useState(null);
  const [info, setInfo] = useState(null);
  const [submitting, setSubmitting] = useState(false);
  const [needsSlugForLogin, setNeedsSlugForLogin] = useState(false);

  // Signup form state
  const [signup, setSignup] = useState({
    name: "", company: "", email: "", password: "",
    slug: "", industry: "", agree: true,
  });
  const [slugTouched, setSlugTouched] = useState(false);
  const [slugStatus, setSlugStatus] = useState(null); // null | "checking" | "free" | "taken" | "invalid"

  // Login form state
  const [login, setLogin] = useState({ email: "", password: "", slug: "", remember: true });

  // Admin login state
  const [admin, setAdmin] = useState({ id: "", password: "" });

  // Platform config (sets initial mode and toggles).
  const [config, setConfig] = useState({ platformName: "VoAIs Call", signupOpen: true, trialDays: 14 });

  // Load /api/config on mount — also sniff for "?admin" in URL to flip to admin mode.
  useEffect(() => {
    VoaisAPI.config().then((r) => {
      if (r.ok && r.data) setConfig((c) => ({ ...c, ...r.data }));
    }).catch(() => {});
    if (location.hash === "#admin" || location.search.indexOf("admin") >= 0) {
      setMode("admin");
    }
  }, []);

  // Live slug availability check — debounced.
  useEffect(() => {
    if (mode !== "signup") return;
    const raw = signup.slug.trim().toLowerCase();
    if (!raw) { setSlugStatus(null); return; }
    setSlugStatus("checking");
    const handle = setTimeout(async () => {
      const r = await VoaisAPI.auth.checkSlug(raw);
      if (r.ok) {
        setSlugStatus(r.data.available ? "free" : (r.data.reason === "invalid" ? "invalid" : "taken"));
      } else {
        setSlugStatus(null);
      }
    }, 400);
    return () => clearTimeout(handle);
  }, [signup.slug, mode]);

  // Auto-derive slug from company name once, unless user has typed in slug field.
  useEffect(() => {
    if (mode !== "signup") return;
    if (slugTouched) return;
    const s = slugify(signup.company);
    setSignup((v) => ({ ...v, slug: s }));
  }, [signup.company, slugTouched, mode]);

  // ── Handlers ──────────────────────────────────────────────────────────
  const handleLogin = useCallback(async (e) => {
    if (e) e.preventDefault();
    setError(null);
    if (!login.email || !login.password) {
      setError("Email and password are required.");
      return;
    }
    setSubmitting(true);
    try {
      const r = await VoaisAPI.auth.login({
        email: login.email.trim(),
        password: login.password,
        slug: needsSlugForLogin ? login.slug.trim().toLowerCase() : undefined,
      });
      if (r.ok) {
        onAuth(VoaisAPI.getSession());
        return;
      }
      if (r.status === 409 && r.data?.needsSlug) {
        setNeedsSlugForLogin(true);
        setError(r.data.msg || "Enter your workspace URL to continue.");
      } else {
        setError(r.data?.msg || "Login failed. Please try again.");
      }
    } catch (err) {
      setError("Network error. Please retry.");
    } finally {
      setSubmitting(false);
    }
  }, [login, needsSlugForLogin, onAuth]);

  const handleSignup = useCallback(async (e) => {
    if (e) e.preventDefault();
    setError(null);
    if (!signup.name.trim())     return setError("Enter your full name.");
    if (!signup.company.trim())  return setError("Enter your company / organization name.");
    if (!signup.email.trim())    return setError("Enter your work email.");
    if (signup.password.length < 8) return setError("Password must be at least 8 characters.");
    if (!signup.agree)           return setError("Please agree to the Terms and Privacy Policy.");
    if (slugStatus === "taken")  return setError("That workspace URL is already taken.");
    if (slugStatus === "invalid")return setError("Workspace URL must be 3–48 chars: lowercase letters, numbers, hyphens.");

    setSubmitting(true);
    try {
      const r = await VoaisAPI.auth.signup({
        name: signup.name.trim(),
        company: signup.company.trim(),
        email: signup.email.trim(),
        password: signup.password,
        slug: signup.slug.trim().toLowerCase() || undefined,
        industry: signup.industry || undefined,
      });
      if (r.ok) {
        onAuth(VoaisAPI.getSession());
        return;
      }
      setError(r.data?.msg || "Sign-up failed. Please try again.");
    } catch (err) {
      setError("Network error. Please retry.");
    } finally {
      setSubmitting(false);
    }
  }, [signup, slugStatus, onAuth]);

  const handleAdminLogin = useCallback(async (e) => {
    if (e) e.preventDefault();
    setError(null);
    if (!admin.id || !admin.password) {
      setError("Both fields are required.");
      return;
    }
    setSubmitting(true);
    try {
      const r = await VoaisAPI.auth.adminLogin({
        email: admin.id.trim(),
        password: admin.password,
      });
      if (r.ok) {
        onAuth(VoaisAPI.getSession());
        return;
      }
      setError(r.data?.msg || "Login failed. Please try again.");
    } catch (err) {
      setError("Network error. Please retry.");
    } finally {
      setSubmitting(false);
    }
  }, [admin, onAuth]);

  // Mode switch resets transient state.
  const switchMode = (m) => {
    setMode(m);
    setError(null); setInfo(null); setNeedsSlugForLogin(false);
  };

  // ── Render ────────────────────────────────────────────────────────────
  return (
    <div className="auth-shell">

      {/* ===== Left — brand / marketing side ===== */}
      <div className="auth-brand">
        <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 40 }}>
          <div className="brand-mark" style={{ width: 36, height: 36, borderRadius: 12 }}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2.4" strokeLinecap="round">
              <path d="M5 12h2l2-6 4 12 2-9 2 5h2"/>
            </svg>
          </div>
          <div>
            <div style={{ fontWeight: 600, fontSize: 17 }}>VoAIs Call</div>
            <div style={{ fontSize: 11, opacity: 0.6, letterSpacing: "0.08em", textTransform: "uppercase", marginTop: 2 }}>by Hidrogen</div>
          </div>
        </div>

        <div style={{ flex: 1, display: "flex", flexDirection: "column", justifyContent: "center", maxWidth: 480, position: "relative", zIndex: 2 }}>
          <Badge tone="blue" dot>v1.0 · Now in production</Badge>
          <h2 style={{ fontSize: 38, fontWeight: 600, letterSpacing: "-0.025em", lineHeight: 1.15, margin: "20px 0 14px" }}>
            Replace your call center with <span style={{ color: "var(--accent)" }}>autonomous AI agents</span>.
          </h2>
          <p style={{ fontSize: 15, color: "rgba(255,255,255,0.6)", lineHeight: 1.6, margin: 0 }}>
            Run 1,000 parallel calls. Hindi + Hinglish + English. Lead qualification, demo bookings, callbacks — all hands-off.
          </p>

          <div style={{ marginTop: 36, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
            {[
              { k: "1,284", v: "calls running now" },
              { k: "63.2%", v: "average connect rate" },
              { k: "₹1.40", v: "per qualified lead" },
              { k: "780ms", v: "AI response latency" },
            ].map((x, i) => (
              <div key={i} style={{ background: "rgba(255,255,255,0.04)", border: "1px solid rgba(255,255,255,0.08)", borderRadius: 16, padding: 14 }}>
                <div style={{ fontSize: 22, fontWeight: 600, letterSpacing: "-0.02em" }}>{x.k}</div>
                <div style={{ fontSize: 11.5, color: "rgba(255,255,255,0.55)", marginTop: 2 }}>{x.v}</div>
              </div>
            ))}
          </div>
        </div>

        <div style={{ marginTop: 28, color: "rgba(255,255,255,0.4)", fontSize: 12, position: "relative", zIndex: 2 }}>
          Trusted by Mercedes-Benz · IIM Lucknow · STPI · MeitY · Brij Tower
        </div>

        {/* decorative waveform */}
        <div style={{ position: "absolute", inset: 0, opacity: 0.4, overflow: "hidden", pointerEvents: "none" }}>
          <svg width="100%" height="100%" preserveAspectRatio="none" viewBox="0 0 600 800" style={{ position: "absolute", bottom: -100, left: 0 }}>
            <defs>
              <linearGradient id="auth-wave" x1="0" y1="0" x2="0" y2="1">
                <stop offset="0" stopColor="#3B7BFF" stopOpacity="0"/>
                <stop offset="0.7" stopColor="#3B7BFF" stopOpacity="0.4"/>
                <stop offset="1" stopColor="#3B7BFF" stopOpacity="0"/>
              </linearGradient>
            </defs>
            {Array.from({ length: 80 }).map((_, i) => {
              const x = i * 8;
              const h = 80 + 100 * Math.abs(Math.sin(i * 0.4)) + 60 * Math.abs(Math.cos(i * 0.27));
              return <rect key={i} x={x} y={400 - h/2} width="3" height={h} fill="url(#auth-wave)" rx="1.5"/>;
            })}
          </svg>
        </div>
        <div style={{ position: "absolute", top: -100, right: -100, width: 400, height: 400, background: "radial-gradient(circle, rgba(59,123,255,0.3), transparent 60%)", borderRadius: "50%", pointerEvents: "none" }}/>
      </div>

      {/* ===== Right — the form ===== */}
      <div className="auth-form-side">
        <div style={{ width: "100%", maxWidth: 380 }}>
          <h1 style={{ fontSize: 26, fontWeight: 600, letterSpacing: "-0.02em", margin: "0 0 8px" }}>
            {mode === "login" ? "Welcome back" : mode === "signup" ? "Create your workspace" : "Super-admin sign in"}
          </h1>
          <p style={{ color: "var(--ink-3)", margin: "0 0 28px", fontSize: 14 }}>
            {mode === "login" && "Sign in to continue managing your calling campaigns."}
            {mode === "signup" && `Start a free ${config.trialDays}-day trial. No credit card required.`}
            {mode === "admin"  && "Platform administration. Tenant operators use the regular sign-in."}
          </p>

          {/* Error + info banners */}
          {error && (
            <div className="auth-banner err" role="alert">
              <I.alert size={14}/>
              <span>{error}</span>
            </div>
          )}
          {info && (
            <div className="auth-banner info">
              <I.check size={14}/>
              <span>{info}</span>
            </div>
          )}

          {/* ===== LOGIN ===== */}
          {mode === "login" && (
            <form onSubmit={handleLogin} style={{ display: "flex", flexDirection: "column", gap: 14 }} noValidate>
              <Field label="Work email">
                <input className="input" type="email" autoComplete="email" required autoFocus
                       placeholder="you@company.in"
                       value={login.email}
                       onChange={(e) => setLogin({ ...login, email: e.target.value })}/>
              </Field>

              <Field label="Password">
                <PasswordInput
                  value={login.password}
                  show={showPw}
                  onShow={setShowPw}
                  onChange={(v) => setLogin({ ...login, password: v })}
                  autoComplete="current-password"
                />
              </Field>

              {needsSlugForLogin && (
                <Field label="Workspace URL" hint="The slug your workspace lives at — e.g. mercedes-lucknow">
                  <input className="input" required
                         placeholder="your-workspace"
                         value={login.slug}
                         onChange={(e) => setLogin({ ...login, slug: e.target.value })}/>
                </Field>
              )}

              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: -4 }}>
                <label className="check">
                  <input type="checkbox" checked={login.remember}
                         onChange={(e) => setLogin({ ...login, remember: e.target.checked })}/>
                  Remember me
                </label>
                <a href="#" className="link" style={{ fontSize: 12.5 }} onClick={(e) => { e.preventDefault(); setInfo("Forgot password recovery is coming in Phase 2. Contact support@voais.in to reset for now."); }}>
                  Forgot password?
                </a>
              </div>

              <Btn kind="primary" size="lg" type="submit" disabled={submitting} style={{ marginTop: 6 }}>
                {submitting ? "Signing in…" : "Sign in"} {!submitting && <I.arrow_right size={14}/>}
              </Btn>
            </form>
          )}

          {/* ===== SIGNUP ===== */}
          {mode === "signup" && (
            <form onSubmit={handleSignup} style={{ display: "flex", flexDirection: "column", gap: 14 }} noValidate>
              <Field label="Full name">
                <input className="input" required autoFocus
                       placeholder="e.g. Amit Yadav"
                       value={signup.name}
                       onChange={(e) => setSignup({ ...signup, name: e.target.value })}/>
              </Field>

              <Field label="Company / organization">
                <input className="input" required
                       placeholder="e.g. Hidrogen Labs"
                       value={signup.company}
                       onChange={(e) => setSignup({ ...signup, company: e.target.value })}/>
              </Field>

              <Field label="Workspace URL"
                     hint={<SlugHint status={slugStatus} slug={signup.slug}/>}>
                <div className="input-with-prefix">
                  <span className="input-prefix">voais.in/t/</span>
                  <input className="input"
                         placeholder="your-workspace"
                         value={signup.slug}
                         onChange={(e) => { setSlugTouched(true); setSignup({ ...signup, slug: e.target.value.toLowerCase() }); }}/>
                </div>
              </Field>

              <Field label="Work email">
                <input className="input" type="email" autoComplete="email" required
                       placeholder="you@company.in"
                       value={signup.email}
                       onChange={(e) => setSignup({ ...signup, email: e.target.value })}/>
              </Field>

              <Field label="Password" hint="Minimum 8 characters, including at least one letter and one number.">
                <PasswordInput
                  value={signup.password}
                  show={showPw}
                  onShow={setShowPw}
                  onChange={(v) => setSignup({ ...signup, password: v })}
                  autoComplete="new-password"
                />
              </Field>

              <label className="check" style={{ marginTop: -4, alignItems: "flex-start" }}>
                <input type="checkbox"
                       checked={signup.agree}
                       onChange={(e) => setSignup({ ...signup, agree: e.target.checked })}/>
                <span style={{ fontSize: 12.5, color: "var(--ink-3)" }}>
                  I agree to the <a className="link" href="#">Terms</a> and <a className="link" href="#">Privacy Policy</a>
                </span>
              </label>

              <Btn kind="primary" size="lg" type="submit" disabled={submitting} style={{ marginTop: 6 }}>
                {submitting ? "Creating…" : "Create workspace"} {!submitting && <I.arrow_right size={14}/>}
              </Btn>
            </form>
          )}

          {/* ===== ADMIN LOGIN ===== */}
          {mode === "admin" && (
            <form onSubmit={handleAdminLogin} style={{ display: "flex", flexDirection: "column", gap: 14 }} noValidate>
              <Field label="Email or username">
                <input className="input" required autoFocus
                       placeholder="amit@hidrogen.in"
                       value={admin.id}
                       onChange={(e) => setAdmin({ ...admin, id: e.target.value })}/>
              </Field>

              <Field label="Password">
                <PasswordInput
                  value={admin.password}
                  show={showPw}
                  onShow={setShowPw}
                  onChange={(v) => setAdmin({ ...admin, password: v })}
                  autoComplete="current-password"
                />
              </Field>

              <Btn kind="primary" size="lg" type="submit" disabled={submitting} style={{ marginTop: 6 }}>
                {submitting ? "Signing in…" : "Sign in as admin"} {!submitting && <I.arrow_right size={14}/>}
              </Btn>
            </form>
          )}

          {/* Mode switcher footer */}
          <div style={{ textAlign: "center", marginTop: 24, color: "var(--ink-3)", fontSize: 13 }}>
            {mode === "login" && config.signupOpen && (
              <>New to VoAIs? <a href="#" className="link" onClick={(e) => { e.preventDefault(); switchMode("signup"); }}>Create an account</a></>
            )}
            {mode === "login" && !config.signupOpen && (
              <>Signups are invite-only. <a href="#" className="link" onClick={(e) => { e.preventDefault(); setInfo("Contact your workspace admin for an invite."); }}>Need access?</a></>
            )}
            {mode === "signup" && (
              <>Already have an account? <a href="#" className="link" onClick={(e) => { e.preventDefault(); switchMode("login"); }}>Sign in</a></>
            )}
            {mode === "admin" && (
              <>Not an admin? <a href="#" className="link" onClick={(e) => { e.preventDefault(); switchMode("login"); }}>Workspace sign-in</a></>
            )}
          </div>

          <div style={{ marginTop: 28, padding: 14, background: "var(--surface)", border: "1px solid var(--line)", borderRadius: 12, display: "flex", alignItems: "center", gap: 12 }}>
            <div style={{ flexShrink: 0, color: "var(--accent)" }}><I.shield size={18}/></div>
            <div>
              <div style={{ fontSize: 12.5, fontWeight: 600 }}>SOC 2 Type II + DPDP compliant</div>
              <div style={{ fontSize: 11.5, color: "var(--ink-3)" }}>India data residency · TRAI/DND compliant calling.</div>
            </div>
          </div>
        </div>
      </div>

    </div>
  );
}

// ── Helpers ────────────────────────────────────────────────────────────

// Password input with show/hide affordance.
function PasswordInput({ value, onChange, show, onShow, autoComplete, ...rest }) {
  return (
    <div className="input-with-suffix">
      <input className="input"
             type={show ? "text" : "password"}
             required
             autoComplete={autoComplete || "current-password"}
             placeholder="••••••••"
             value={value}
             onChange={(e) => onChange(e.target.value)}
             {...rest}/>
      <button type="button" className="input-suffix-btn" onClick={() => onShow(!show)} title={show ? "Hide" : "Show"} tabIndex={-1}>
        {show ? <I.x size={14}/> : <I.search size={14}/>}
      </button>
    </div>
  );
}

function SlugHint({ status, slug }) {
  if (!slug) return <span style={{ color: "var(--ink-3)" }}>This is the URL of your workspace.</span>;
  if (status === "checking") return <span style={{ color: "var(--ink-3)" }}>Checking availability…</span>;
  if (status === "free")     return <span style={{ color: "var(--ok)" }}>✓ Available.</span>;
  if (status === "taken")    return <span style={{ color: "var(--err)" }}>Already taken — try a different one.</span>;
  if (status === "invalid")  return <span style={{ color: "var(--err)" }}>Use 3–48 lowercase letters, numbers, hyphens.</span>;
  return null;
}

function slugify(name) {
  return String(name || "")
    .toLowerCase()
    .normalize("NFKD")
    .replace(/[\u0300-\u036f]/g, "")
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "")
    .slice(0, 48);
}

// Expose globally so app.jsx can route to it.
window.AuthScreen = AuthScreen;
