// My Collection, authentication surfaces.
// Three full-screen editorial auth views (login / signup / forgot) plus the
// soft signup gate that appears when a logged-out reader tries to save a record.
// Wired to real Supabase auth via window.BBR_auth.
const { useState: useAuthState } = React;

function GoogleMark() {
  return (
    <svg width="17" height="17" viewBox="0 0 18 18" aria-hidden="true">
      <path fill="#4285F4" d="M17.64 9.2c0-.64-.06-1.25-.16-1.84H9v3.48h4.84a4.14 4.14 0 0 1-1.8 2.72v2.26h2.92c1.7-1.57 2.68-3.88 2.68-6.62z"/>
      <path fill="#34A853" d="M9 18c2.43 0 4.47-.8 5.96-2.18l-2.92-2.26c-.8.54-1.84.86-3.04.86-2.34 0-4.32-1.58-5.03-3.7H.96v2.33A9 9 0 0 0 9 18z"/>
      <path fill="#FBBC05" d="M3.97 10.72a5.4 5.4 0 0 1 0-3.44V4.95H.96a9 9 0 0 0 0 8.1l3.01-2.33z"/>
      <path fill="#EA4335" d="M9 3.58c1.32 0 2.5.45 3.44 1.35l2.58-2.58C13.46.9 11.43 0 9 0A9 9 0 0 0 .96 4.95l3.01 2.33C4.68 5.16 6.66 3.58 9 3.58z"/>
    </svg>
  );
}
function AppleMark() {
  return (
    <svg width="16" height="18" viewBox="0 0 16 18" aria-hidden="true" fill="currentColor">
      <path d="M13.3 9.55c-.02-1.96 1.6-2.9 1.67-2.95-.91-1.33-2.33-1.51-2.83-1.53-1.2-.12-2.35.71-2.96.71-.61 0-1.55-.69-2.55-.67-1.31.02-2.52.76-3.2 1.93-1.36 2.37-.35 5.87.98 7.79.65.94 1.42 2 2.43 1.96.97-.04 1.34-.63 2.52-.63 1.18 0 1.5.63 2.53.61 1.04-.02 1.7-.96 2.34-1.9.74-1.09 1.04-2.15 1.06-2.2-.02-.01-2.03-.78-2.05-3.1zM11.4 3.5c.54-.65.9-1.56.8-2.46-.78.03-1.71.52-2.27 1.17-.5.57-.94 1.5-.82 2.38.87.07 1.76-.44 2.29-1.09z"/>
    </svg>
  );
}

function SocialButtons({ verb }) {
  const [note, setNote] = useAuthState("");
  const google = async () => {
    setNote("");
    try { await window.BBR_auth.signInWithGoogle(); }
    catch (e) { setNote("Google sign-in had a problem, try email instead."); }
  };
  return (
    <div className="auth-social">
      <button type="button" className="auth-soc-btn" onClick={google}>
        <GoogleMark /> {verb} with Google
      </button>
      {note && <p className="auth-err" style={{ marginTop: 8 }}>{note}</p>}
    </div>
  );
}

function AuthAside({ mode }) {
  const quotes = {
    login: <>Your shelf, <em>valued.</em> Pick up where you left off.</>,
    signup: <>Turn the records you love into a collection that <em>knows its worth.</em></>,
    forgot: <>It happens to the best of us. We'll get you back to your shelf.</>,
  };
  return (
    <aside className="auth-aside">
      <span className="grainwash" />
      <div className="auth-brand"><span className="dot" /> The Lead-In</div>
      <div className="auth-aside-quote">
        <div className="q">{quotes[mode]}</div>
      </div>
      <div className="auth-aside-meta">
        <span>Est. 100 greatest albums</span>
        <span>·</span>
        <span>Collection · Valuation · Wishlist</span>
      </div>
    </aside>
  );
}

// Turn a Supabase error into a friendly line.
function friendlyError(e) {
  const raw = (e && e.message ? e.message : String(e));
  const m = raw.toLowerCase();
  if (m.includes("invalid login")) return "That email and password don't match. Try again?";
  if (m.includes("already registered")) return "There's already an account with that email, try signing in.";
  if (m.includes("password")) return "Password needs to be at least 6 characters.";
  if (m.includes("invalid email") || m.includes("not a valid email") || m.includes("unable to validate email")) return "That doesn't look like a valid email address.";
  if (m.includes("email not confirmed")) return "Please confirm your email first, check your inbox for the link.";
  if (m.includes("rate limit") || m.includes("too many")) return "Too many attempts, give it a minute and try again.";
  if (m.includes("signups not allowed") || m.includes("not allowed for otp") || m.includes("disabled")) return "Sign-ups are currently restricted for this email. Try another address or contact us.";
  // Don't mask anything else behind a misleading 'invalid email' message, surface it.
  return raw || "Something went wrong. Please try again.";
}

function AuthScreen({ mode, onMode, onAuthed, onClose }) {
  // mode: 'login' | 'signup' | 'forgot'
  const [sent, setSent] = useAuthState(false);
  const [busy, setBusy] = useAuthState(false);
  const [err, setErr] = useAuthState("");
  const [name, setName] = useAuthState("");
  const [email, setEmail] = useAuthState("");
  const [password, setPassword] = useAuthState("");
  const [showPass, setShowPass] = useAuthState(false);

  const submit = async (e) => {
    e.preventDefault();
    setErr("");
    setBusy(true);
    try {
      if (mode === "forgot") {
        await window.BBR_auth.resetPassword(email);
        setSent(true);
      } else if (mode === "signup") {
        const user = await window.BBR_auth.signUp({ name, email, password });
        // If email confirmation is ON, user may be null until confirmed.
        if (user) onAuthed(user);
        else { setErr(""); setSent(true); }
      } else {
        const user = await window.BBR_auth.signIn({ email, password });
        onAuthed(user);
      }
    } catch (e2) {
      setErr(friendlyError(e2));
    } finally {
      setBusy(false);
    }
  };

  // Magic link: email a passwordless sign-in link to the address entered.
  const magicLink = async () => {
    setErr("");
    if (!email) { setErr("Enter your email above, then request a link."); return; }
    setBusy(true);
    try {
      await window.BBR_auth.signInWithMagicLink(email);
      setSent(true);
    } catch (e2) {
      setErr(friendlyError(e2));
    } finally {
      setBusy(false);
    }
  };

  return (
    <div className="auth">
      <AuthAside mode={mode} />
      <div className="auth-main">
        <button className="auth-close" onClick={onClose}>
          <svg width="13" height="13" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M1 1l12 12M13 1L1 13"/></svg>
          Browse the site
        </button>

        {mode === "login" && (
          sent ? (
            <div className="auth-form">
              <div className="auth-kicker">Welcome back</div>
              <h1 className="auth-h">Check your inbox</h1>
              <p className="auth-sub">We've sent a sign-in link to {email}. Click it and you'll be signed in, no password needed.</p>
              <button className="auth-submit" type="button" onClick={() => setSent(false)}>Back to sign in</button>
            </div>
          ) : (
          <form className="auth-form" onSubmit={submit}>
            <div className="auth-kicker">Welcome back</div>
            <h1 className="auth-h">Sign in</h1>
            <p className="auth-sub">Access your collection, valuations, and wishlist.</p>
            <SocialButtons verb="Continue" />
            <div className="auth-or">or with email</div>
            <div className="auth-field">
              <label>Email</label>
              <input className="auth-input" type="email" placeholder="you@example.com"
                value={email} onChange={(e) => setEmail(e.target.value)} required />
            </div>
            <div className="auth-field">
              <div className="auth-field-row">
                <label>Password</label>
                <a onClick={() => onMode("forgot")}>Forgot?</a>
              </div>
              <div className="auth-pass-wrap">
                <input className="auth-input" type={showPass ? "text" : "password"} placeholder="Your password"
                  value={password} onChange={(e) => setPassword(e.target.value)} required />
                <button type="button" className="auth-pass-toggle" onClick={() => setShowPass((v) => !v)}
                  aria-label={showPass ? "Hide password" : "Show password"} aria-pressed={showPass}>
                  {showPass ? "Hide" : "Show"}
                </button>
              </div>
            </div>
            {err && <p className="auth-err">{err}</p>}
            <button className="auth-submit" type="submit" disabled={busy}>{busy ? "Signing in\u2026" : "Sign in"}</button>
            <p className="auth-foot" style={{ marginTop: 10 }}>
              <a onClick={magicLink}>Email me a sign-in link instead</a>
            </p>
            <p className="auth-foot">New here? <a onClick={() => onMode("signup")}>Create a free account</a></p>
          </form>
          )
        )}

        {mode === "signup" && (
          <form className="auth-form" onSubmit={submit}>
            <div className="auth-kicker">Free account</div>
            <h1 className="auth-h">{sent ? "Check your inbox" : "Start your collection"}</h1>
            {sent ? (
              <>
                <p className="auth-sub">We've sent a confirmation link to {email}. Click it to activate your account, then sign in.</p>
                <button className="auth-submit" type="button" onClick={() => onMode("login")}>Back to sign in</button>
              </>
            ) : (
              <>
                <p className="auth-sub">Track your vinyl, see what it's worth, and build a wishlist, free forever.</p>
                <SocialButtons verb="Sign up" />
                <div className="auth-or">or with email</div>
                <div className="auth-field">
                  <label>Name</label>
                  <input className="auth-input" type="text" placeholder="Your name"
                    value={name} onChange={(e) => setName(e.target.value)} required />
                </div>
                <div className="auth-field">
                  <label>Email</label>
                  <input className="auth-input" type="email" placeholder="you@example.com"
                    value={email} onChange={(e) => setEmail(e.target.value)} required />
                </div>
                <div className="auth-field">
                  <label>Password</label>
                  <div className="auth-pass-wrap">
                    <input className="auth-input" type={showPass ? "text" : "password"} placeholder="Choose a password (min 6 characters)"
                      value={password} onChange={(e) => setPassword(e.target.value)} required />
                    <button type="button" className="auth-pass-toggle" onClick={() => setShowPass((v) => !v)}
                      aria-label={showPass ? "Hide password" : "Show password"} aria-pressed={showPass}>
                      {showPass ? "Hide" : "Show"}
                    </button>
                  </div>
                </div>
                {err && <p className="auth-err">{err}</p>}
                <button className="auth-submit" type="submit" disabled={busy}>{busy ? "Creating\u2026" : "Create account"}</button>
                <p className="auth-foot">Already a member? <a onClick={() => onMode("login")}>Sign in</a></p>
                <p className="auth-legal">By creating an account you agree to our <a>Terms</a> and <a>Privacy Policy</a>.</p>
              </>
            )}
          </form>
        )}

        {mode === "forgot" && (
          <form className="auth-form" onSubmit={submit}>
            <div className="auth-kicker">Reset password</div>
            <h1 className="auth-h">{sent ? "Check your inbox" : "Forgot password"}</h1>
            {!sent ? (
              <>
                <p className="auth-sub">Enter your email and we'll send a link to set a new password.</p>
                <div className="auth-field">
                  <label>Email</label>
                  <input className="auth-input" type="email" placeholder="you@example.com"
                    value={email} onChange={(e) => setEmail(e.target.value)} required />
                </div>
                {err && <p className="auth-err">{err}</p>}
                <button className="auth-submit" type="submit" disabled={busy}>{busy ? "Sending\u2026" : "Send reset link"}</button>
                <p className="auth-foot"><a onClick={() => onMode("login")}>&larr; Back to sign in</a></p>
              </>
            ) : (
              <>
                <p className="auth-sub">We've sent a reset link to your email. It expires in 30 minutes.</p>
                <button className="auth-submit" type="button" onClick={() => onMode("login")}>Back to sign in</button>
                <p className="auth-foot">Didn't get it? <a onClick={() => setSent(false)}>Try another email</a></p>
              </>
            )}
          </form>
        )}
      </div>
    </div>
  );
}

function SignupGate({ intent, onSignup, onLogin, onClose }) {
  // intent: 'collection' | 'wishlist'
  const head = intent === "wishlist" ? "Save it to your wishlist" : "Add it to your collection";
  return (
    <div className="gate-backdrop" onClick={onClose}>
      <div className="gate" onClick={(e) => e.stopPropagation()}>
        <div className="gate-top">
          <span className="grainwash" />
          <button className="gate-x" onClick={onClose}>&times;</button>
          <div className="gate-eyebrow">Free account</div>
          <h2 className="gate-h">{head}</h2>
        </div>
        <div className="gate-body">
          <p className="gate-p">Create a free account to track your vinyl, see what it's worth, and build your wishlist.</p>
          <div className="gate-list">
            {[
              "Log every record and pressing you own",
              "See a live estimate of what your collection is worth",
              "Queue up what to buy next, and buy it on vinyl",
            ].map((t, i) => (
              <div className="gate-li" key={i}>
                <span className="gi">
                  <svg width="11" height="11" viewBox="0 0 12 12" fill="none" stroke="currentColor" strokeWidth="1.8"><path d="M2 6.5l2.6 2.6L10 3"/></svg>
                </span>
                {t}
              </div>
            ))}
          </div>
          <div className="gate-actions">
            <button className="mc-btn solid" style={{ justifyContent: "center" }} onClick={onSignup}>Create free account</button>
            <button className="gate-skip" onClick={onLogin}>Already have an account? Sign in</button>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { AuthScreen, SignupGate, GoogleMark, AppleMark });
