/* global React, I, S, SB */
/* Pamp — Auth (sign in / up / reset) — wired to Supabase */

const { useState: useAuthState, useCallback: useAuthCallback } = React;

function isEmail(v) { return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v || ""); }

function Auth({ role = "user", onSignedIn, onBack }) {
  const toast = window.useToast();
  const [mode, setMode] = useAuthState("signin");
  const [step, setStep] = useAuthState(1);
  const [showPwd, setShowPwd] = useAuthState(false);
  const [submitting, setSubmitting] = useAuthState(false);
  const [errors, setErrors] = useAuthState({});

  const [form, setForm] = useAuthState({
    email: "", password: "",
    firstName: "", lastName: "",
    businessName: "", category: "", city: "", staffSize: "", paymentMethod: "",
    location: "", interests: [],
  });

  const updateField = (k, v) => {
    setForm((f) => ({ ...f, [k]: v }));
    setErrors((e) => ({ ...e, [k]: undefined }));
  };

  const titleMap = {
    signin: "Welcome back.",
    signup: role === "vendor" ? "Open your studio." : "Create your account.",
    reset:  "Reset password.",
  };
  const subMap = {
    signin: "",
    signup: role === "vendor"
      ? "Set up your business profile in three short steps."
      : "Two minutes. Then we’ll handle the rest.",
    reset: "Enter your email and we’ll send a reset link.",
  };

  const handleSignIn = useAuthCallback(async () => {
    const e = {};
    if (!form.email) e.email = "Email is required";
    else if (!isEmail(form.email)) e.email = "Enter a valid email";
    if (!form.password) e.password = "Password is required";
    if (Object.keys(e).length) { setErrors(e); return; }

    setSubmitting(true);
    try {
      const result = await SB.signIn({ email: form.email, password: form.password });
      if (!result.ok) { toast.error(result.message || "Sign in failed"); return; }
      const userRole = result.profile?.role;
      if (role === "admin" && userRole !== "admin") {
        toast.error("This account isn't an admin. Use the matching portal.");
        await SB.signOut();
        return;
      }
      toast.success(`Welcome back${result.profile?.full_name ? `, ${result.profile.full_name.split(" ")[0]}` : ""}.`);
      const sess = await SB.getSession();
      onSignedIn?.({ profile: result.profile, accessToken: sess.access_token, user: sess.user });
    } catch (err) {
      toast.error(err.message || "Sign in failed");
    } finally {
      setSubmitting(false);
    }
  }, [form, role, onSignedIn, toast]);

  const validateSignupStep = (s) => {
    const e = {};
    if (s === 1) {
      if (!form.firstName) e.firstName = "Required";
      if (!form.lastName) e.lastName = "Required";
      if (!form.email) e.email = "Email is required";
      else if (!isEmail(form.email)) e.email = "Enter a valid email";
      if (!form.password) e.password = "Password is required";
      else if (form.password.length < 8) e.password = "At least 8 characters";
    }
    if (s === 2 && role === "vendor") {
      if (!form.businessName) e.businessName = "Required";
      if (!form.city) e.city = "Required";
    }
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const handleSignUp = useAuthCallback(async () => {
    if (!validateSignupStep(step)) return;
    const maxStep = role === "vendor" ? 3 : 2;
    if (step < maxStep) { setStep(step + 1); return; }
    setSubmitting(true);
    try {
      const fullName = `${form.firstName} ${form.lastName}`.trim();
      const payload = {
        email: form.email, password: form.password,
        role: role === "vendor" ? "vendor" : "user", fullName,
      };
      if (role === "vendor") {
        payload.businessName = form.businessName;
        payload.ownerName = fullName;
      }
      const result = await SB.signUp(payload);
      if (!result.ok) { toast.error(result.message || "Sign up failed"); return; }
      toast.success("Account created. Check your inbox to verify your email.");
      const signin = await SB.signIn({ email: form.email, password: form.password });
      if (signin.ok) {
        const sess = await SB.getSession();
        onSignedIn?.({ profile: signin.profile, accessToken: sess.access_token, user: sess.user });
      } else {
        setMode("signin"); setStep(1);
      }
    } catch (err) {
      toast.error(err.message || "Sign up failed");
    } finally {
      setSubmitting(false);
    }
  }, [form, role, step, onSignedIn, toast]);

  const handleReset = useAuthCallback(async () => {
    if (!form.email) { setErrors({ email: "Email is required" }); return; }
    if (!isEmail(form.email)) { setErrors({ email: "Enter a valid email" }); return; }
    setSubmitting(true);
    try {
      const { error } = await SB.client.auth.resetPasswordForEmail(form.email, {
        redirectTo: window.location.origin + "/#/auth/" + role,
      });
      if (error) toast.error(error.message || "Reset failed");
      else { toast.success("Reset link sent — check your inbox."); setMode("signin"); }
    } finally {
      setSubmitting(false);
    }
  }, [form.email, role, toast]);

  return (
    <div className="auth-page page-enter">
      <div className="auth-left">
        <div className="row between">
          <button className="row-tight" style={{ color: "var(--ink-2)", fontSize: 13 }} onClick={onBack}>
            <I.chevR size={14} style={{ transform: "rotate(180deg)" }} /> Back to portals
          </button>
          <S.Brand />
        </div>

        <div style={{ flex: 1, display: "flex", flexDirection: "column", justifyContent: "center", maxWidth: 420, margin: "auto", width: "100%", paddingTop: 56 }}>
          <div className="eyebrow" style={{ marginBottom: 18 }}>
            <span className="dot" style={{
              background: role === "vendor" ? "var(--pos)" : role === "admin" ? "var(--ink)" : "var(--accent)",
              marginRight: 8, verticalAlign: "middle",
            }} />
            {role === "vendor" ? "Vendor portal" : role === "admin" ? "Admin portal" : "Client portal"}
          </div>
          <h1 className="display" style={{ fontSize: 44, lineHeight: 1.02, letterSpacing: "-0.035em", margin: "0 0 12px" }}>
            {titleMap[mode]}
          </h1>
          {subMap[mode]
            ? <p className="muted" style={{ fontSize: 14, marginBottom: 28 }}>{subMap[mode]}</p>
            : <div style={{ marginBottom: 28 }} />}

          {mode === "signin" && (
            <div className="col" style={{ gap: 16 }}>
              <FormField label="Email" error={errors.email}>
                <S.Input icon={<I.mail size={15} />} placeholder="you@example.com" value={form.email} onChange={(e) => updateField("email", e.target.value)} />
              </FormField>
              <FormField label="Password" error={errors.password}
                right={<button type="button" style={{ fontSize: 12, color: "var(--accent-ink)" }} onClick={() => { setMode("reset"); setErrors({}); }}>Forgot?</button>}>
                <PasswordInput show={showPwd} onToggle={() => setShowPwd(s => !s)} value={form.password} onChange={(e) => updateField("password", e.target.value)} placeholder="Your password" />
              </FormField>
              <label className="row-tight" style={{ fontSize: 12.5, color: "var(--ink-2)" }}>
                <input type="checkbox" defaultChecked style={{ accentColor: "var(--accent)" }} />
                Keep me signed in on this device
              </label>
              <S.Btn variant="primary" size="lg" onClick={handleSignIn} disabled={submitting} iconRight={<I.arrowR size={16} />}>
                {submitting ? "Signing in…" : "Sign in"}
              </S.Btn>
              {role !== "admin" && (
                <S.Btn variant="outline" size="lg" onClick={() => { setMode("signup"); setStep(1); setErrors({}); }}>
                  Create new account
                </S.Btn>
              )}
            </div>
          )}

          {mode === "signup" && (
            <div className="col" style={{ gap: 16 }}>
              <StepDots count={role === "vendor" ? 3 : 2} active={step} />
              {step === 1 && <>
                <div className="grid-2">
                  <FormField label="First name" error={errors.firstName}>
                    <S.Input placeholder="Alex" value={form.firstName} onChange={(e) => updateField("firstName", e.target.value)} />
                  </FormField>
                  <FormField label="Last name" error={errors.lastName}>
                    <S.Input placeholder="Mor" value={form.lastName} onChange={(e) => updateField("lastName", e.target.value)} />
                  </FormField>
                </div>
                <FormField label="Email" error={errors.email}>
                  <S.Input icon={<I.mail size={15} />} placeholder="you@example.com" value={form.email} onChange={(e) => updateField("email", e.target.value)} />
                </FormField>
                <FormField label="Password" error={errors.password} hint="At least 8 characters">
                  <PasswordInput show={showPwd} onToggle={() => setShowPwd(s => !s)} value={form.password} onChange={(e) => updateField("password", e.target.value)} />
                </FormField>
              </>}
              {step === 2 && role === "vendor" && <>
                <FormField label="Business name" error={errors.businessName}>
                  <S.Input icon={<I.store size={15} />} placeholder="Maison Color & Co." value={form.businessName} onChange={(e) => updateField("businessName", e.target.value)} />
                </FormField>
                <FormField label="Category">
                  <div className="row" style={{ gap: 8, flexWrap: "wrap" }}>
                    {["Hair","Nails","Spa","Massage","Barber","Wellness","Fitness"].map((c) => (
                      <span key={c} className={form.category === c ? "chip chip-accent" : "chip"}
                        style={{ cursor: "pointer", height: 30 }}
                        onClick={() => updateField("category", c)}>{c}</span>
                    ))}
                  </div>
                </FormField>
                <FormField label="City" error={errors.city}>
                  <S.Input icon={<I.location size={15} />} placeholder="Accra, Ghana" value={form.city} onChange={(e) => updateField("city", e.target.value)} />
                </FormField>
              </>}
              {step === 2 && role !== "vendor" && <>
                <FormField label="Where are you?">
                  <S.Input icon={<I.location size={15} />} placeholder="City or zip" value={form.location} onChange={(e) => updateField("location", e.target.value)} />
                </FormField>
                <FormField label="I'm interested in">
                  <div className="row" style={{ gap: 8, flexWrap: "wrap" }}>
                    {["Hair","Nails","Massage","Facials","Brows","Lashes","Barber"].map((c) => {
                      const active = form.interests.includes(c);
                      return (
                        <span key={c} className={active ? "chip chip-accent" : "chip"}
                          style={{ cursor: "pointer", height: 30 }}
                          onClick={() => {
                            updateField("interests", active ? form.interests.filter(x => x !== c) : [...form.interests, c]);
                          }}>+ {c}</span>
                      );
                    })}
                  </div>
                </FormField>
              </>}
              {step === 3 && role === "vendor" && <>
                <FormField label="Number of staff">
                  <div className="grid-3" style={{ gap: 8 }}>
                    {["1","2-5","6-15","16-30","30+"].map((v) => (
                      <S.Btn key={v} variant={form.staffSize === v ? "primary" : "outline"} onClick={() => updateField("staffSize", v)}>{v}</S.Btn>
                    ))}
                  </div>
                </FormField>
                <FormField label="Where do you take payments today?">
                  <div className="grid-2" style={{ gap: 8 }}>
                    {["In-person card","Cash","Other platform","Just starting"].map((v) => (
                      <S.Btn key={v} variant={form.paymentMethod === v ? "primary" : "outline"} onClick={() => updateField("paymentMethod", v)}>{v}</S.Btn>
                    ))}
                  </div>
                </FormField>
              </>}
              <div className="row" style={{ gap: 10, marginTop: 8 }}>
                {step > 1 && <S.Btn variant="outline" onClick={() => setStep(step - 1)}>Back</S.Btn>}
                <div className="spacer" />
                <S.Btn variant="primary" size="lg" onClick={handleSignUp} disabled={submitting} iconRight={<I.arrowR size={16} />}>
                  {submitting ? "Working…" : step < (role === "vendor" ? 3 : 2) ? "Continue" : "Create account"}
                </S.Btn>
              </div>
              <div className="muted" style={{ fontSize: 13, textAlign: "center" }}>
                Already have an account?{" "}
                <button type="button" style={{ color: "var(--accent-ink)", fontWeight: 500 }} onClick={() => { setMode("signin"); setErrors({}); }}>Sign in →</button>
              </div>
            </div>
          )}

          {mode === "reset" && (
            <div className="col" style={{ gap: 16 }}>
              <FormField label="Email" error={errors.email}>
                <S.Input icon={<I.mail size={15} />} placeholder="you@example.com" value={form.email} onChange={(e) => updateField("email", e.target.value)} />
              </FormField>
              <S.Btn variant="primary" size="lg" onClick={handleReset} disabled={submitting} iconRight={<I.arrowR size={16} />}>
                {submitting ? "Sending…" : "Send reset link"}
              </S.Btn>
              <div className="muted" style={{ fontSize: 13, textAlign: "center" }}>
                Remembered it?{" "}
                <button type="button" style={{ color: "var(--accent-ink)", fontWeight: 500 }} onClick={() => { setMode("signin"); setErrors({}); }}>Sign in →</button>
              </div>
            </div>
          )}
        </div>
      </div>

      <div className="auth-right">
        <div style={{ position: "relative", zIndex: 2 }}>
          <div className="eyebrow">
            <span className="dot" style={{ background: "var(--accent)", marginRight: 8, verticalAlign: "middle" }} />
            Voices from Pamp
          </div>
        </div>
        <div style={{ position: "relative", zIndex: 2 }}>
          <div className="display" style={{ fontSize: 38, lineHeight: 1.1, letterSpacing: "-0.03em", maxWidth: 460 }}>
            “Pamp tripled our booking conversion and gave back twenty hours of admin every week.”
          </div>
          <div className="row" style={{ marginTop: 28, gap: 14 }}>
            <S.Avatar name="Léa Marchand" size="lg" />
            <div>
              <div style={{ fontWeight: 500 }}>Léa Marchand</div>
              <div className="tiny" style={{ color: "oklch(80% 0.04 290)" }}>Owner · Maison Color, Paris</div>
            </div>
          </div>
        </div>
        <div className="row" style={{ gap: 20, position: "relative", zIndex: 2 }}>
          <div>
            <div className="display" style={{ fontSize: 32 }}>4.9</div>
            <div className="tiny" style={{ color: "oklch(80% 0.04 290)" }}>App Store · 18k reviews</div>
          </div>
          <div style={{ width: 1, height: 36, background: "oklch(100% 0 0 / 0.12)" }} />
          <div>
            <div className="display" style={{ fontSize: 32 }}>32m</div>
            <div className="tiny" style={{ color: "oklch(80% 0.04 290)" }}>avg. monthly bookings</div>
          </div>
        </div>
      </div>
    </div>
  );
}

function FormField({ label, right, error, hint, children }) {
  return (
    <div className="form-field">
      <div className="row between">
        <label>{label}</label>
        {right}
      </div>
      {children}
      {error
        ? <div className="field-error">{error}</div>
        : hint
          ? <div className="field-hint">{hint}</div>
          : null}
    </div>
  );
}

function PasswordInput({ show, onToggle, placeholder = "••••••••", value, onChange }) {
  return (
    <S.Input
      icon={<I.lock size={15} />}
      placeholder={placeholder}
      type={show ? "text" : "password"}
      value={value}
      onChange={onChange}
      suffix={
        <button type="button" onClick={onToggle}
          aria-label={show ? "Hide password" : "Show password"}
          style={{ color: "var(--ink-3)", display: "inline-flex", padding: 4, marginRight: -4, borderRadius: 999 }}>
          {show ? <I.eyeOff size={16} /> : <I.eye size={16} />}
        </button>
      }
    />
  );
}

function StepDots({ count, active }) {
  return (
    <div className="row" style={{ gap: 6 }}>
      {[...Array(count)].map((_, i) => (
        <div key={i} style={{
          height: 4, flex: 1, borderRadius: 999,
          background: i < active ? "var(--accent)" : "var(--surface-3)",
          transition: "background 0.2s",
        }} />
      ))}
    </div>
  );
}

window.Auth = Auth;
