/* login.jsx — email + password sign in / sign up for Advokacy.
   On success, stores the session (AdvAuth) and lands on ?next= (default the Ask
   page). Ask is free and needs no account; Document Intelligence requires one. */
const { useState, useEffect } = React;

function LoginApp(){
  const params = new URLSearchParams(location.search);
  const next = params.get("next") || PAGES.ask;          // land on Ask by default
  const [mode, setMode]   = useState("login");           // login | signup
  const [email, setEmail] = useState("");
  const [password, setPw] = useState("");
  const [showPw, setShow] = useState(false);
  const [name, setName]   = useState("");
  const [err, setErr]     = useState("");
  const [busy, setBusy]   = useState(false);

  // Already signed in? Go straight where they were headed.
  useEffect(() => { if(AdvAuth.isLoggedIn()) location.replace(next); }, []);

  async function submit(e){
    if(e) e.preventDefault();
    setErr("");
    if(!email.trim() || !password){ setErr("Enter your email and password."); return; }
    if(mode==="signup" && name.trim().length < 2){ setErr("Please enter your full name."); return; }
    if(mode==="signup" && password.length < 8){ setErr("Password must be at least 8 characters."); return; }
    setBusy(true);
    try{
      if(mode==="login") await AdvAuth.login(email.trim(), password);
      else await AdvAuth.signup({ email: email.trim(), password, full_name: name.trim() });
      location.replace(next);
    }catch(ex){ setErr(ex.message || "Something went wrong. Please try again."); setBusy(false); }
  }

  const isLogin = mode==="login";
  return (
    <div className="auth-page">
      {/* brand / value panel (hidden on small screens) */}
      <aside className="auth-aside">
        <a className="auth-aside-brand" href={PAGES.ask}><span className="auth-logo">A</span> Advokacy</a>
        <div className="auth-aside-body">
          <h2 className="auth-aside-h">Research grounded in real Indian case law.</h2>
          <ul className="auth-points">
            <li><span className="ap-ic"><Icon name="check" style={{width:13,height:13}}/></span> <b>Ask Advokacy</b> — free, no account needed</li>
            <li><span className="ap-ic"><Icon name="docs" style={{width:13,height:13}}/></span> <b>Document Intelligence</b> — read &amp; interrogate your own files</li>
            <li><span className="ap-ic"><Icon name="scale" style={{width:13,height:13}}/></span> Every answer cites verified Indian Kanoon authorities</li>
          </ul>
        </div>
        <div className="auth-aside-foot mono">Your documents stay private to your account.</div>
      </aside>

      {/* form */}
      <main className="auth-main">
        <a className="auth-back mono" href={PAGES.ask}><Icon name="arrow" style={{width:14,height:14,transform:"rotate(180deg)"}}/> Back to Ask</a>
        <div className="auth-card">
          <div className="auth-brand auth-brand-sm"><span className="auth-logo">A</span> Advokacy</div>
          <h1 className="auth-h1">{isLogin ? "Welcome back" : "Create your account"}</h1>
          <p className="auth-sub">{isLogin
            ? "Sign in to use Document Intelligence. Ask Advokacy research stays free."
            : "Free to start. An account unlocks Document Intelligence — your private case files."}</p>

          <div className="auth-seg">
            <button type="button" className={"auth-seg-b"+(isLogin?" on":"")} onClick={()=>{setMode("login");setErr("");}}>Sign in</button>
            <button type="button" className={"auth-seg-b"+(!isLogin?" on":"")} onClick={()=>{setMode("signup");setErr("");}}>Create account</button>
          </div>

          <form onSubmit={submit} noValidate>
            {!isLogin &&
              <label className="auth-field">
                <span className="auth-label mono">Full name</span>
                <input className="auth-input" type="text" autoComplete="name" value={name}
                  onChange={e=>setName(e.target.value)} placeholder="Adv. Anita Rao" disabled={busy}/>
              </label>}
            <label className="auth-field">
              <span className="auth-label mono">Email</span>
              <input className="auth-input" type="email" autoComplete="email" value={email}
                onChange={e=>setEmail(e.target.value)} placeholder="you@firm.in" disabled={busy} autoFocus/>
            </label>
            <label className="auth-field">
              <span className="auth-label mono">Password</span>
              <div className="auth-pw">
                <input className="auth-input" type={showPw?"text":"password"}
                  autoComplete={isLogin?"current-password":"new-password"} value={password}
                  onChange={e=>setPw(e.target.value)} placeholder={isLogin?"Your password":"At least 8 characters"} disabled={busy}/>
                <button type="button" className="auth-pw-tog mono" onClick={()=>setShow(s=>!s)} tabIndex={-1}>{showPw?"Hide":"Show"}</button>
              </div>
            </label>

            {err && <div className="auth-err"><Icon name="shield" style={{width:14,height:14}}/> {err}</div>}

            <button className="btn btn-primary auth-submit" type="submit" disabled={busy}>
              {busy ? "Please wait…" : (isLogin ? "Sign in" : "Create account")} <Icon name="arrow"/>
            </button>
          </form>

          <div className="auth-switch mono">
            {isLogin
              ? <>New to Advokacy? <button type="button" onClick={()=>{setMode("signup");setErr("");}}>Create an account</button></>
              : <>Already have an account? <button type="button" onClick={()=>{setMode("login");setErr("");}}>Sign in</button></>}
          </div>
        </div>
        <div className="auth-legal mono">By continuing you agree to use Advokacy as a research assistant, not legal advice.</div>
      </main>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<LoginApp/>);
