// Auth modals — Login, Reset Password, Request Access success.
// Each is self-contained and uses CSS classes from the main stylesheet.

const { useState } = React;

function ModalShell({ onClose, children }) {
  return (
    <div className="scrim" onClick={(e)=>{if(e.target===e.currentTarget) onClose()}}>
      <div className="modal" role="dialog" aria-modal="true">
        <button className="modal-x" onClick={onClose} aria-label="Close"><IconX size={16}/></button>
        {children}
      </div>
    </div>
  );
}

function BrandMark({sub}) {
  return (
    <div className="modal-brand">
      <div style={{display:"flex",alignItems:"center",gap:10}}>
        <div className="brand-mark"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><path d="M4 14l4-4 4 4 4-6 4 6"/></svg></div>
        <div style={{fontSize:20,fontWeight:600,letterSpacing:"-0.02em"}}>BaySync</div>
      </div>
      {sub && <div className="sub">{sub}</div>}
    </div>
  );
}

function LoginModal({ onClose, onForgot, onRequestAccess }) {
  const [empId, setEmpId] = useState("");
  const [pin, setPin] = useState(["","","","","",""]);
  const [remember, setRemember] = useState(true);
  const [err, setErr] = useState("");
  const [loading, setLoading] = useState(false);
  const inputs = React.useRef([]);

  function setDigit(i, v) {
    v = v.replace(/\D/g,"").slice(-1);
    const next = [...pin]; next[i] = v; setPin(next);
    if (v && i < 5) inputs.current[i+1]?.focus();
  }
  function onKey(i, e) {
    if (e.key === "Backspace" && !pin[i] && i > 0) inputs.current[i-1]?.focus();
  }
  function submit(e) {
    e.preventDefault();
    setErr("");
    if (!empId.trim() || pin.join("").length < 4) { setErr("Enter your employee ID and PIN."); return; }
    setLoading(true);
    window.top.location.href = "/login";
  }

  return (
    <ModalShell onClose={onClose}>
      <BrandMark sub="Sign in to your service department"/>
      <form onSubmit={submit}>
        <div className="field">
          <label>Employee ID or email</label>
          <input value={empId} onChange={e=>setEmpId(e.target.value)} autoFocus placeholder="e.g. 141 or jpowell@dealer.com"/>
        </div>
        <div className="field">
          <label>6-digit PIN</label>
          <div className="pin">
            {pin.map((d,i)=>(
              <input key={i} ref={el=>inputs.current[i]=el} value={d}
                onChange={e=>setDigit(i, e.target.value)}
                onKeyDown={e=>onKey(i,e)}
                inputMode="numeric" maxLength={1} type="password"/>
            ))}
          </div>
        </div>

        {err && <div style={{fontSize:12.5,color:"#fca5a5",background:"rgba(239,68,68,.08)",border:"1px solid rgba(239,68,68,.3)",padding:"8px 10px",borderRadius:8}}>{err}</div>}

        <label className="check">
          <input type="checkbox" checked={remember} onChange={e=>setRemember(e.target.checked)}/>
          Remember this device for 30 days
        </label>

        <button className="btn btn-primary" type="submit" disabled={loading}>
          {loading ? "Signing in…" : "Log In"} <IconArrow size={14}/>
        </button>

        <div className="row-between">
          <a href="#" onClick={e=>{e.preventDefault();onForgot()}}>Forgot password?</a>
          <span style={{color:"var(--ink-mute)",fontSize:12,fontFamily:'"JetBrains Mono",monospace'}}>SSO available in v1.2</span>
        </div>
      </form>

      <hr/>
      <div className="alt-link">
        New to BaySync? <a href="#" onClick={e=>{e.preventDefault();onRequestAccess()}}>Request access →</a>
      </div>
    </ModalShell>
  );
}

function ResetModal({ onClose, onBack }) {
  const [email, setEmail] = useState("");
  const [sent, setSent] = useState(false);

  function submit(e){
    e.preventDefault();
    setSent(true);
  }

  return (
    <ModalShell onClose={onClose}>
      <BrandMark sub={sent ? "Check your inbox" : "Reset your password"}/>
      {!sent ? (
        <form onSubmit={submit}>
          <div className="field">
            <label>Work email</label>
            <input type="email" autoFocus value={email} onChange={e=>setEmail(e.target.value)} placeholder="you@dealer.com" required/>
          </div>
          <p style={{margin:0,fontSize:12.5,color:"var(--ink-mute)",lineHeight:1.5}}>
            We'll email a one-time link to reset your password or PIN. Reset links expire in 30 minutes.
          </p>
          <button type="submit" className="btn btn-primary">Send reset link <IconArrow size={14}/></button>
          <div className="row-between" style={{justifyContent:"center"}}>
            <a href="#" onClick={e=>{e.preventDefault();onBack()}}>← Back to login</a>
          </div>
        </form>
      ) : (
        <div className="success" style={{padding:"24px 8px"}}>
          <div className="check"><IconCheck size={28}/></div>
          <div style={{fontSize:16,fontWeight:600,letterSpacing:"-0.01em"}}>If this email has access,</div>
          <div style={{fontSize:13.5,color:"var(--ink-dim)",maxWidth:"36ch",lineHeight:1.5,marginTop:-6}}>
            reset instructions will be sent to <b style={{color:"#fff",fontWeight:500}}>{email || "your inbox"}</b> within a minute.
          </div>
          <button className="btn btn-ghost" onClick={onBack}>Back to login</button>
        </div>
      )}
    </ModalShell>
  );
}

Object.assign(window, { ModalShell, LoginModal, ResetModal, BrandMark });
